拦截器概述
| SpringMVC的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并做相应的处理。 |
| 例如:进行权限验证、记录请求信息的日志、判断用户是否登录等。 |
拦截器的定义
| 要使用SpringMVC的拦截器,就需要对拦截器类进行定义和配置。通常拦截器类可以通过两种方式来定义。 |
- 通过实现HandlerInterceptor接口
- 继承HandlerInterceptor接口的实现类HAndlerInterceptorAdapter
- 实现WebRequestInterceptor接口
- 继承WebRequestInterceptor接口的实现类
这里我们用HandlerInterceptor接口的定义方式为例:
- 自定义拦截器类
| |
| |
| |
| public class MyInterceptor implements HandlerInterceptor { |
| |
| |
| |
| public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { |
| System.out.println("------------处理前------------"); |
| return true; |
| } |
| |
| public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { |
| System.out.println("------------处理后------------"); |
| } |
| |
| public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { |
| System.out.println("------------清理------------"); |
| } |
| } |
- 拦截器的配置
要是自定义的拦截器类生效,还需要再SpringMVC的配置文件中进行配置
| |
| <mvc:interceptors> |
| <mvc:interceptor> |
| |
| |
| |
| <mvc:mapping path="/**"/> |
| |
| <bean class="com.pp.config.LoginInterceptor"/> |
| </mvc:interceptor> |
| </mvc:interceptors> |
- 编辑一个拦截器的控制器——InterceptorController
| |
| @Controller |
| public class InterceptorController { |
| @RequestMapping("/interceptor") |
| @ResponseBody |
| public String test(){ |
| System.out.println("控制器中的方法执行了~~~"); |
| return "hello"; |
| } |
| } |
- 配置tomcat测试
在浏览器地址栏输入http://localhost:8080/interceptor
这时候回发现拦截器放行时,前端显示hello!
注意:配置多个拦截器,直接在配置文件中增加mvc:interceptor即可!
案例:实现用户登录权限验证!
需求:
只有登录后的用户才能访问系统的主页面,如果没有登陆系统而直接访问主页面,则拦截器会将请求拦截,并转发到登陆页面要求重新登录!相同的如果用户名或密码错误,也会要求重新登录。
- 创建一个User类
| @Data |
| @AllArgsConstructor |
| @NoArgsConstructor |
| @Builder |
| public class User { |
| private Integer id; |
| private String username; |
| private String password; |
| } |
- 创建控制器类LoginController,在该类中定义向主页跳转,向登陆页面跳转,执行用户登录等操作。
| @Controller |
| public class LoginController { |
| |
| |
| |
| |
| @RequestMapping(value = "/login",method = RequestMethod.GET) |
| public String toLogin(){ |
| return "login"; |
| } |
| |
| |
| |
| |
| @RequestMapping(value = "/login",method = RequestMethod.POST) |
| public String login(User user, Model model, HttpSession httpSession){ |
| |
| String username = user.getUsername(); |
| String password = user.getPassword(); |
| |
| if (username != null && username.equals("panpan") && |
| password != null && password.equals("123456")){ |
| |
| httpSession.setAttribute("USER_SESSION",user); |
| |
| |
| return "redirect:main"; |
| } |
| model.addAttribute("msg","用户名或密码错误,请重新登录"); |
| return "login"; |
| } |
| |
| |
| |
| @RequestMapping("/main") |
| public String toMain(){ |
| return "main"; |
| } |
| |
| |
| |
| public String logout(HttpSession httpSession){ |
| |
| httpSession.invalidate(); |
| |
| return "redirect:login"; |
| } |
| } |
注意:向用户登录页面跳转和用户登录方法的@RequestMapping注解的value属性值相同,但是method属性值不同,这是因为跳转到登录页面接受的是GET方法提交的方法,而用户登录接受的是POST方式提交的方法。
- 创建LoginInterceptor
| public class LoginInterceptor implements HandlerInterceptor { |
| @Override |
| public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { |
| |
| String url = request.getRequestURI(); |
| |
| if(url.indexOf("/login") >= 0){ |
| return true; |
| } |
| |
| HttpSession session = request.getSession(); |
| User user = (User) session.getAttribute("USER_SESSION"); |
| |
| if(user != null){ |
| return true; |
| } |
| |
| request.setAttribute("msg","您还没有登录,请先登录!"); |
| request.getRequestDispatcher("/WEB-INF/jsp/login.jsp") |
| .forward(request,response); |
| return false; |
| } |
| @Override |
| public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { |
| |
| } |
| @Override |
| public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { |
| |
| } |
| } |
- 在Spring-mvc.xml中添加拦截器
| |
| <mvc:interceptors> |
| <mvc:interceptor> |
| |
| |
| |
| <mvc:mapping path="/**"/> |
| |
| <bean class="com.pp.config.LoginInterceptor"/> |
| </mvc:interceptor> |
| |
| <mvc:interceptor> |
| <mvc:mapping path="/**"/> |
| <bean class="com.pp.config.MyInterceptor"/> |
| </mvc:interceptor> |
| </mvc:interceptors> |
- 在jsp文件夹中创建main.jsp
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>首页</title> |
| </head> |
| <body> |
| 当前用户:${USER_SESSION.username} |
| <a href="${pageContext.request.contextPath}/logout">退出</a> |
| </body> |
| </html> |
| |
- 创建一个login.jsp
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>Title</title> |
| </head> |
| <body> |
| <h1>登陆页面</h1> |
| <span style="color: red">${msg}</span> |
| <form action="${pageContext.request.contextPath}/login" method="post" > |
| 用户名:<input type="text" name="username"> |
| 密 码:<input type="text" name="password"> |
| <input type="submit" value="登录"> |
| </form> |
| </body> |
| </html> |
- 最后!配置tomcat测试
- 当直接访问http://localhost:8080/main时,会发现要求重新登录

- 输入正确的用户名和密码即可正确跳转main页面,这里实现了退出登录,点击退出重新登陆!


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南