Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、判断用户是否登录等。
拦截器依赖于web框架,在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。
package com.wt.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomHandlerInterceptor implements HandlerInterceptor {
/**
* 在控制器方法调用前执行
* 返回值为是否中断
* true:表示继续执行(下一个拦截器或处理器)
* false:则会中断后续的所有操作,所以我们需要使用response来继续响应后续请求
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
System.out.println("HandlerInterceptor preHandle ....");
return true;
}
/**
* 在控制器方法调用后,解析视图前调用,我们可以对视图和模型做进一步渲染或修改
* 可在modelAndView中加入数据,比如当前时间
*/
@Override
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {
System.out.println("HandlerInterceptor postHandle ....");
}
/**
* 整个请求完成,即视图渲染结束后调用,这个时候可以做些资源清理工作,或日志记录
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object object, Exception e) throws Exception {
System.out.println("HandlerInterceptor afterCompletion ....");
}
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**">mvc:mapping>
<bean class="com.wt.interceptor.CustomHandlerInterceptor">bean>
mvc:interceptor>
mvc:interceptors>
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount12")
public String findAccount12(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
System.out.println("controller的方法执行了......");
return "success";
}
}
<a href="/account/findAccount12">拦截器a>
package com.wt.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
String user = (String) request.getSession().getAttribute("user_session");
if (user != null) {//已经登录,继续执行
System.out.println("获得用户信息:"+user);
return true;
} else {//未登录,跳转到登录页面
response.sendRedirect(request.getContextPath() +"/login.jsp");
return false;
}
}
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**">mvc:mapping>
<bean class="com.wt.interceptor.LoginInterceptor">bean>
mvc:interceptor>
mvc:interceptors>
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount13")
public String findAccount13(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
System.out.println("controller的方法执行了......");
return "success";
}
}
<%
session.setAttribute("user_session","User{name:张二狗,age:18}");
%>
<a href="/account/findAccount13">登录拦截器a>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
bean>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping(path="/upload")
public String upload(HttpServletRequest request, MultipartFile upload,Model model) throws IOException {
System.out.println("springmvc方式的文件上传");
//获取要上传的文件目录
String path = request.getSession().getServletContext().getRealPath("/uploads");
System.out.println("path:"+path);
//根据文件上传的目录创建File对象,如果不存在则创建1个File对象
File file = new File(path);
if(!file.exists()){
//创建一个file对象
file.mkdirs();
}
//获取文件上传名称
String filename = upload.getOriginalFilename();
//完成文件上传
upload.transferTo(new File(path,filename));
model.addAttribute("msg", "欢迎你 springmvc");
return "success";
}
}
在index.jsp里面定义超链接
<form action="/account/upload" method="post" enctype="multipart/form-data">
文件: <input type="file" name="upload">input>
<input type="submit" value="提交">
form>
如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount14")
public String findAccount14(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
//模拟异常信息
int i = 10/0;
return "success";
}
}
<a href="/account/findAccount14">异常处理器a>
public class DataConvert implements Converter<String, Date> {
/***
* 配置时间转换类
* @param date
* @return
*/
@Override
public Date convert(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
<mvc:annotation-driven conversion-service="format"/>
<bean id="format" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.by.converter.DataConverter">bean>
set>
property>
bean>
web.xml
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.jpgurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.cssurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.jsurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.pngurl-pattern>
servlet-mapping>
在spring3.0.4以后的 SpringMVC 模块提供了静态资源映射器组件。通过mvc:resources标签配置静态资源映射器
修改SpringMVC配置文件
spring mvc.xml
<mvc:resources mapping="/img/**" location="/img/"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
在 SpringMVC 的配置文件中配置
<mvc:default-servlet-handler/>