• 中文
    • English
  • 注册
  • 查看作者
    • SpringMVC:使用拦截器拦截请求

      一.  数据准备

      index.jsp(注意:因为jsp中使用了jstl,需要添加jstl.jar和standard.jar依赖)

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
      <h1>首页</h1>
      <c:if test="${sessionScope.username != null}">
        <p>欢迎:${sessionScope.username},<a href="${pageContext.request.contextPath}/logout">退出</a></p>
      </c:if>
      <c:if test="${sessionScope.username == null}">
        <p><a href="${pageContext.request.contextPath}/login">去登陆</a></p>
      </c:if>
      <ul>
        <li><a href="${pageContext.request.contextPath}/user">个人中心</a></li>
        <li><a href="${pageContext.request.contextPath}/product">商品详情</a></li>
      </ul>
      </body>
      </html>

      login.jsp:

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <html>
      <head>
          <title>登录页面</title>
      </head>
      <body>
      <form action="${pageContext.request.contextPath}/doLogin" method="post">
          <%--    只有通过传参来返回的时候,才需要下面的三行代码,如果url是null,说明是直接登录,而不是被跳转到登录--%>
          <c:if test="${param.uri != null}">
              <input type="hidden" name="uri" value="${param.uri}">
          </c:if>
          <input type="text" name="username" placeholder="请输入用户名"> <br>
          <input type="password" name="password" placeholder="请输入密码"> <br>
          <input type="submit" value="登录">
      </form>
      </body>
      </html>

      product.jsp

      <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
      <!DOCTYPE html>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
      <h1>商品1</h1>
      <h1>商品2</h1>
      <h1>商品3</h1>
      <h1>商品4</h1>
      <h1>商品5</h1>
      </body>
      </html>

      user.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>个人中心</title>
      </head>
      <body>
      <h1>个人中心</h1>
      <p><a href="${pageContext.request.contextPath}/index">返回首页</a></p>
      </body>
      </html>

      Controller:

      package io.zhangjia.springmvc.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpSession;
      
      
      @Controller
      public class Test {
      
          @RequestMapping("/index")
          public String index(){
              return "index";
          }
      
          @RequestMapping("/login")
          public String login(){
              return "login";
          }
      
          @RequestMapping("/doLogin")
          public String doLogin(HttpServletRequest request,
                                HttpSession session,
                                String username,
                                String password,
                                String uri){
      //        模拟数据库登录,如果登录成功
      
              System.out.println("uri = " + uri);
      
              if(username != null && "1".equals(password)){
                  session.setAttribute("username",username);
      //          如果是从其他页面被拦截过来登录,则登录成功后返回该页面
                  if(uri != null) {
                      System.out.println("uri" + uri);
                      String contextPath = request.getContextPath();
                      uri = uri.replace(contextPath,"");
                      System.out.println("uri" + uri);
                      return "redirect:"+ uri;
      //          如果是直接登录
                  } else {
                      return "redirect:/index";
                  }
      //        如果登录不成功,则重定向到登录页面
              } else {
                  return "redirect:/login";
              }
          }
      
          @RequestMapping("/user")
          public String user(){
              return "user";
          }
      
          @RequestMapping("/product")
          public String product(){
              return "product";
          }
      
          @RequestMapping("/logout")
          public String logout(HttpSession session){
              session.invalidate();
              return "redirect:index";
          }
      
      }

      二.  添加并配置拦截器

      我们想通过拦截器实现以下功能:

      如果用户没登录,则点击个人中心跳转到登录页面,登录成功后回到个人中心,商品详情页无论是否登录,都可以直接访问

      LoginInterceptor:

      package io.zhangjia.springmvc.interceptors;
      
      import org.springframework.stereotype.Component;
      import org.springframework.web.servlet.HandlerInterceptor;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      
      @Component
      public class LoginInterceptor implements HandlerInterceptor {
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              HttpSession session = request.getSession();
              Object username = session.getAttribute("username");
              if (username != null) {
                  return true;
              } else {
      //          获取请求地址
                  String requestURI = request.getRequestURI();
                  System.out.println("requestURI = " + requestURI);
      //          没有登录,去登录
                  response.sendRedirect(request.getContextPath() + "/login?uri="+requestURI);
                  return false;
              }
          }
      }

      其中preHandler实现了如果用户已经登录,则放行,如果没有登录,则将被拦截页面的地址作为参数重定向到登录页面。接下来配置spring-mvc.xml,添加以下内容:

      <mvc:interceptors>
         <mvc:interceptor>
             <mvc:mapping path="/**"/>
             <mvc:exclude-mapping path="/login"/>
             <mvc:exclude-mapping path="/product"/>
             <mvc:exclude-mapping path="/index"/>
             <ref bean="loginInterceptor" />
         </mvc:interceptor>
      </mvc:interceptors>

      《SpringMVC:拦截器》一文中的拦截器配置不同,我们需要通过 <mvc:exclude-mapping path=”/xxxx”/>来选择哪些请求不需要拦截。

      此时如果我们在没有登录的情况下点击购物车,会先让我们登录,登录成功会回到购物车页面

      三.  总结

      1.  在Controller中完成请求的相关处理

      2.  在拦截器中根据拦截条件选择是放行还是拦截。

      3.  在spring-mvc.xml中配置拦截器

    • 0
    • 0
    • 0
    • 1.5k
    • 请登录之后再进行评论

      登录

      赞助本站

      • 支付宝
      • 微信
      • QQ

      感谢一直支持本站的所有人!

      单栏布局 侧栏位置: