springmvc 拦截器
1.拦截器概念和Struts2一致。
2.实现拦截器
a)实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor{ //在请求处理的方法之前执行 //如果返回true,则执行下一个拦截器;如果返回false,则不执行下一个拦截器 @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("--------处理前-------"); return true; } //在请求处理的方法之后执行 @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("--------处理后-------"); } //在DispatcherServlet处理后执行----清理工作 @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub // System.out.println("--------处理前-------"); } }
b)配置拦截器--注意xsi要配置正确
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <!-- 对应的拦截器 --> <bean class="com.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
3.如果被拦截--能否到达指定页面?
使用HttpServletResponse或者HttpServletRequest可以实现转发或重定向
4.拦截器应用--登录拦截器
public class MyInterceptor implements HandlerInterceptor{ private List<String> allowedPass; //在请求处理的方法之前执行 //如果返回true,则执行下一个拦截器;如果返回false,则不执行下一个拦截器 @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception { // TODO Auto-generated method stub String url = req.getRequestURI().toString(); //先判断session中是否--如果提交过一次后,session里会保存user对象,直到浏览器关闭,所以此处需要判断 Object user = req.getSession().getAttribute("user"); if(user != null){ return true; } for(String temp:allowedPass){ if(url.endsWith(temp)){ return true; } } resp.sendRedirect(req.getContextPath()+"/login.jsp"); return false; } public void setAllowedPass(List<String> allowedPass) { this.allowedPass = allowedPass; } //在请求处理的方法之后执行 @Controller public class HelloController{ @RequestMapping("/login") public String hello(User user,HttpSession session){ if("admin".equals(user.getName()) && "123".equals(user.getPwd())){ session.setAttribute("user", user); return "redirect:/index.jsp"; } return "redirect:/login.jsp"; } @RequestMapping("/add") public String hello1(){ System.out.println("add"); return "redirect:/index.jsp"; }
注:add只是用来测试
配置xml--如果添加<value>add.do</value>则..../add.do不会被拦截
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.interceptor.MyInterceptor"> <property name="allowedPass"> <list> <value>login.do</value> </list> </property> </bean> </mvc:interceptor>