SpringMVC拦截器

本文介绍了SpringMVC中的处理器拦截器(HandlerInterceptor)如何实现类似Servlet过滤器的功能,以及自定义拦截器的步骤。通过一个用户登录认证的示例,展示了拦截器如何检查用户是否已登录,未登录时重定向到登录页面。登录拦截器的关键代码和配置都在文中详细给出。
摘要由CSDN通过智能技术生成

1. 概述

SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能

过滤器与拦截器的区别: 拦截器是AOP思想的具体应用

过滤器:

  • servlet规范中的一部分,任何java web工程都可以使用
  • 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截

拦截器:

  • 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
  • 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的

2. 自定义拦截器

  1. 编写拦截器(实现HandlerInterceptor接口)

    public class MyInterceptor implements HandlerInterceptor {
    	
        //在请求处理的方法之前执行
        //return true; 执行下一个拦截器,放行
        //return false; 不往下继续执行
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("======处理前======");
            return true;
        }
    
        //拦截日志
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("======处理后======");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("======清理======");
        }
    }
    
  2. 配置springmvc.xml

    <!--拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--/**包括这个文件夹下的所有的请求-->
            <mvc:mapping path="/**"/>
            <bean class="com.lrm.config.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    

由此即可完成拦截器功能

3. 用户登录认证拦截

原理

  • 表单提交登录之后,如果用户名和密码正确,则会向session中写入用户信息,返回登录成功
  • 拦截器拦截用户请求,若未登录(session为空)及拦截,已登录则放行
  1. 入口页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>入口页面</title>
      </head>
      <body>
        <h1><a href="${pageContext.request.contextPath}/goLogin">登录</a></h1>
        <h1><a href="${pageContext.request.contextPath}/main">首页</a></h1>
      </body>
    </html>
    
  2. 登录页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>登录页面</title>
    </head>
    <body>
    <h1>登录页面</h1>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username">
        密码:<input type="password" name="password">
        <input type="submit" value="登录">
    </form>
    </body>
    </html>
    
  3. Controller请求处理

    @Controller
    public class LoginController {
    
        @RequestMapping("/main")
        public String main(){
            return "main";
        }
    
        @RequestMapping("/goLogin")
        public String goLogin(){
            return "login";
        }
    
        //登录请求
        @RequestMapping("/login")
        public String login(HttpSession session, String username, String password, Model model){
            //把用户的信息存在Session中
            session.setAttribute("userLoginInfo",username);
            model.addAttribute("username",username);
            return "main";
    
        }
    
        //注销
        @RequestMapping("/logout")
        public String logout(HttpSession session){
            //移除Session
            session.removeAttribute("userLoginInfo");
            return "login";
    
        }
    }
    
  4. 首页

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>首页</title>
    </head>
    <body>
    <h1>首页</h1>
    
    <span>${username}</span>
    <p><a href="${pageContext.request.contextPath}/logout">注销</a></p>
    </body>
    </html>
    
  5. 登录拦截器

    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
            //已经登录 放行判断
            if (session.getAttribute("userLoginInfo")!=null){
                return true;
            }
            //登录页面放行
            if (request.getRequestURI().contains("goLogin")){
                return true;
            }
    
            //提交登录放行
            if (request.getRequestURI().contains("login")){
                return true;
            }
    
            //没有登录
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
        }
    }
    
  6. 配置springmvc.xml

    <!--拦截器配置-->
        <mvc:interceptors>
            <!--登录拦截器-->
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <bean class="com.lrm.config.LoginInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Remote_Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值