1.概述
与servlet技术相同,均属于web层开发项目,进行表现层开发
2.入门案例
使用SpringMVC技术需要先导入SpringMCV的坐标与Servlet的坐标
1.导入springmvc与servlet的坐标
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
2.编写usercontroller
@Controller
public class UserController {
// 设置当前操作的访问路径
@RequestMapping("/save")
// 设置当前操作返回值类型
@ResponseBody
public String save(){
System.out.println("user...save");
return "{'module':'springmvc'}";
}
}
3.编写springconfig
@Configuration
@ComponentScan("com.yrh.controller")
public class SpringMvcConfig {
}
4.导入springconfig
// 定义servlet容器启动的配置类,加载spring配置
public class ServletConfig extends AbstractDispatcherServletInitializer {
// 加载springmvc容器配置
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(SpringMvcConfig.class);
return context;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
针对上述配置方式,spring提供了一种更简单的配置方式
public class ServletContainersInitConfig extends
AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
3.请求与响应
4.Springmvc 拦截器
@Component
//定义拦截器类,实现HandlerInterceptor接口
//注意当前类必须受Spring容器控制
public class ProjectInterceptor implements HandlerInterceptor {
@Override
//原始方法调用前执行的内容
//返回值类型可以拦截控制的执行,true放行,false终止
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String contentType = request.getHeader("Content-Type");
HandlerMethod hm = (HandlerMethod)handler;
System.out.println("preHandle..."+contentType);
return true;
}
@Override
//原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
@Override
//原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
执行流程:
当配置多个拦截器时吗, 会形成拦截器链