拦截器
1.定义
Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。
常用:未登录拦截、角色分配、自动登录、权限控制等
2.自定义拦截器
//自定义的拦截器需要实现HandlerIntercrptor,并且实现其中的方法
public class LoginIntercrptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { //Controller执行前调用此方法 // 返回true表示继续执行,返回false中止执行 // 常用于登录校验、权限拦截等 HttpSession httpSession = request.getSession(); User user = (User) httpSession.getAttribute("user"); if (user!=null) { //不为空表示登录了直接放行 return true; }else { response.sendRedirect(request.getContextPath()+"/login.html"); } return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { // controller执行后但未返回视图前调用此方法 // 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示 } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { // controller执行后且视图返回后调用此方法 // 这里可得到执行controller时的异常信息 // 这里可记录操作日志 } }
3.配置文件进行声明
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <!--扫描controller注解--> <context:component-scan base-package="com.itqf.controller"/>
<!--配置处理器--> <mvc:annotation-driven/>
<!--配置拦截器-->
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/login.html"/> <!--添加自己定义的拦截器--> <bean class="com.itqf.interceptor.LoginIntercrptor"></bean> </mvc:interceptor> </mvc:interceptors>
<!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"/> <property name="prefix" value="/"/> </bean> </beans>
4.页面属性
<form action="/login.html" method="post"> 用户名:<input type="text" name="name"><br> 密码:<input type="password" name="pwd"> <input type="submit" value="登录"> </form>
5.控制器类
@Controller
public class LoginController { @RequestMapping("/index.html") public String index(){ return "login"; } @RequestMapping("/login.html") public String login(User user, HttpSession session){ System.out.println(user); if (user == null){ }else { if ("root".equals(user.getName())||"111".equals(user.getPwd())){ //登陆成功 session.setAttribute("user",user);
//成功跳转到index页面 return "forward:index.jsp"; } } return "login"; } }