我試圖設置Spring MVC項目沒有調度器XML和Web XML(即沒有任何XML的所有)。因此,我使用Spring的@JavaConfig技術。然而,每當我試圖啓動我的服務器上的應用程序我的服務器它不工作(沒有引發任何異常它得到HTTP 404)。
下面是項目結構的快照...
爲什麼@JavaConfig在Spring MVC中不起作用?
而且這裏的代碼片段:
WebConfig.java
@EnableWebMvc
@Configuration
@ComponentScan({ "com.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
private static final String VIEW_LOCATION = "/WEB-INF/views/";
private static final String SUFFIX = ".jsp";
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// System.out.println("in resource");
// registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
// }
@Bean
public InternalResourceViewResolver viewResolver() {
System.out.println("in view");
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(VIEW_LOCATION);
viewResolver.setSuffix(SUFFIX);
return viewResolver;
}
}
Initializer.java
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private static final String MAPPING_URL = "/";
@Override
protected Class<?>[] getRootConfigClasses() {
System.out.println("in config");
return new Class[] { WebConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
System.out.println("dispatcher");
return new String[] { MAPPING_URL };
}
}
HelloController.java
@Controller
public class HelloController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome() {
System.out.println("in servlet");
return "index";
}
}
這裏是pox.xml片段:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>UI</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>UI Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
<finalName>UI</finalName>
</build>
</project>
你在嘗試什麼樣的網址? – Arpit
只需http:// localhost:8080/ –
什麼樣的應用服務器? – Brad