SpringMVC -- 梗概--源码--贰--拦截器:Interceptor
附:实体类
1.配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 前端控制器 /=默认的url-pattern /a/b/c /a /a/d/c /a/d /a / *注意:此控制器默认加载/WEB-INF下的xxx-servlet.xml文件 :其中xxx等于【DispatcherServlet的配置名】 --> <servlet> <servlet-name>mvc62</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc62.xml</param-value> </init-param> <!-- 随项目启动而启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc62</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 专治Post请求参数乱码 --> <filter> <filter-name>encoding62</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 将请求的编码方式设置为utf-8 --> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding62</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2.配置SpringMVC.xml
<?xml version="1.0" encoding="utf-8"?> <!-- xmlns:xml name space 是每一个schema唯一标识 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 扫描所有控制器中的注解 --> <context:component-scan base-package="com.c61.controller"></context:component-scan> <!-- MVC中基于注解开发,导入注解驱动 <mvc:annotation-driven/> --> <mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 支持的格式:application/json --> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 视图解析器:解析视图 控制器方法的返回值,会被视图解析器捕获。"abc" 根据捕获的内容,解析出一个视图地址:/abc.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源:html,js,css,jpg 访问404 解决 --> <mvc:default-servlet-handler/> <!-- 声明异常处理器 --> <bean class="com.c61.ex.resolver.MyExceptionResolver"></bean> <!-- 拦截器配置 --> <!-- /a/b inter1 inter2 拦截顺序:先配置先拦截 具体顺序:pre1==pre2==contorller==post2==post1==after2==after1 --> <mvc:interceptors> <mvc:interceptor> <!-- 定义要拦截的路径 /inter/* 匹配 /inter/a /inter/b inter/cssdafasfsafs 不能匹配/inter/a/b /inter/** 匹配 /inter/a /inter/xxsjaflsajf /inter/a/b/c/e/d/xxxcvx *注意:exclude-mapping不能单独使用。要配合mapping使用 :在mapping匹配的范围中排除一些个。 --> <mvc:mapping path="/inter/**"/> <mvc:mapping path="/a/b"/> <mvc:mapping path="/c/**"/> <mvc:exclude-mapping path="/inter/test/*"/> <mvc:exclude-mapping path="/c/b/**"/> <!-- 声明拦截器 --> <bean class="com.c61.interceptor.MyInterceptor"/> </mvc:interceptor> <mvc:interceptor> <!-- 定义要拦截的路径 --> <mvc:mapping path="/inter/test"/> <!-- 声明拦截器 --> <bean class="com.c61.interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors> <!-- 声明文件上传解析器 注意:此解析器,id必须为:multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大允许的上传大小 byte --> <property name="MaxUploadSize" value="2097152"></property> </bean> <!-- 注册,验证码生成器 --> <bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend"> <constructor-arg> <props> <!-- 是否有边框 边框颜色 边框粗细 --> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.border.thickness">20</prop> <prop key="kaptcha.textproducer.font.color">black</prop> <prop key="kaptcha.image.width">200</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.textproducer.font.size">40</prop> <prop key="kaptcha.session.key">code61</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">Arial,Courier</prop> <!-- <prop key="kaptcha.background.clear.from">black</prop> <prop key="kaptcha.background.clear.to">255,0,0</prop> --> </props> </constructor-arg> </bean> </beans>
3.配置控制器
package com.c61.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.c61.service.UserService; import com.c61.service.UserServiceImpl; @Controller @RequestMapping("/inter") public class InterceptorController { @RequestMapping("/test") public String testInter(){ System.out.println("Controller testAAA"); return "forward:/index.jsp"; } @RequestMapping("/test/b") public String testInter2(){ System.out.println("Controller testBBB"); return "forward:/index.jsp"; } @RequestMapping("/test/c/e/f") public String testInter3(){ System.out.println("Controller testCCC"); return "forward:/index.jsp"; } }
4.配置拦截器
Class : MyInterceptor
package com.c61.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor{ /** * 在Controller之前执行(常用) * 抽取Controller中的冗余功能 */ public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception { System.out.println("pre Handle"); //return false;//中断请求,则后续的controller,postHandle...都不在执行 //return true;//请求继续 return true; } /** * 在Controller之后,在响应之前,执行(了解) * 可以做视图和数据的最终定制 * */ public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView mav) throws Exception { System.out.println("post Handle"); } /** * 在视图渲染完毕后执行(了解) * 资源回收 */ public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) throws Exception { System.out.println("after Comletion"); } }
Class : MyInterceptor2
package com.c61.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor2 implements HandlerInterceptor{ /** * 在Controller之前执行(常用) * 抽取Controller中的冗余功能 */ public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception { System.out.println("pre Handle222"); //return false;//中断请求,则后续的controller,postHandle...都不在执行 //return true;//请求继续 String path=req.getContextPath(); res.sendRedirect(path+"/index.jsp"); return false; } /** * 在Controller之后,在响应之前,执行(了解) * 可以做视图和数据的最终定制 * */ public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView mav) throws Exception { System.out.println("post Handle222"); } /** * 在视图渲染完毕后执行(了解) * 资源回收 */ public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) throws Exception { System.out.println("after Comletion222"); } }
5.配置视图
View : index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <img height="100px" width="100px" src="${pageContext.request.contextPath}/up61/${requestScope.name}"/> </body> </html>
Client : inter/test
Console :
Client :
Client : inter/test/b
Console :
Client :
Client : inter/test/c/e/f
Console :
Client :
1 定制
public class MyInterceptor implements HandlerInterceptor{
/**
* 在Controller之前执行(常用)
* 抽取Controller中的冗余功能
*/
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
Object handler) throws Exception {
//return false;//中断请求,则后续的controller,postHandle...都不再执行
//return true;//请求继续
if(xxx){
String path=req.getContextPath();
res.sendRedirect(path+"/index.jsp");//中断之前设置错误视图
return false;
}
return true
}
/**
* 在Controller之后,在响应之前,执行(了解)
* 可以做视图和数据的最终定制
*/
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView mav) throws Exception {
}
/**
* 在视图渲染完毕后执行(了解)
* 资源回收
*/
public void afterCompletion(HttpServletRequest req,
HttpServletResponse res, Object handler, Exception ex)
throws Exception {
}
}
2 配置
<mvc:interceptors> <mvc:interceptor> <!-- 定义要拦截的路径 --> <mvc:mapping path="/inter/test"/> <mvc:mapping path="/inter/a"/> <mvc:mapping path="/inter/b"/> <!-- 声明拦截器 --> <bean class="com.c61.interceptor.MyInterceptor"/> </mvc:interceptor> <mvc:interceptor> <!-- 定义要拦截的路径 --> <mvc:mapping path="/inter/**"/> <mvc:exclude-mapping path="/inter/test/**"/> <!-- 声明拦截器 --> <bean class="com.c61.interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors> *注意: 1>当有多个拦截器同时拦截时,先配置的先拦截。如过Controller1 先后被inter1和inter2拦截,则具体的拦截路程为: pre1==pre2==contorller==post2==post1==after2==after1 2>/* 只能匹配一级路径:/a /b /c /xxxxxx . 却不能匹配:/a/b /e/d/c /** 能匹配任意多级路径:/a /b /a/b/c /xxs/xxx/xxx/xx 3>mvc:exclude-mapping 不能单独使用,必须配合 mvc:mapping 使用 . 作用是在mvc:mapping的基础上排除一些路径
啦啦啦