<!--使用Java配置-->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<!--指定根配置类-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spittr.config.RootConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoader</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<!--使用Java配置-->
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--指定DispatcherServlet配置类-->
<param-value>com.spittr.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
@Configuration
@ComponentScan(basePackages = "com.spittr",
excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value= EnableWebMvc.class)})
public class RootConfig {
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.spittr")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setExposeContextBeansAsAttributes(true);
registry.viewResolver(viewResolver);
}
}
HelloController:
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(){
System.out.println("进入了hello方法");
return "hello";
}
}
hello.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Welcome to SpringMvc</h1>
</body>
</html>