ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【SpringMVC系列】拦截器

2021-05-14 15:06:04  阅读:17  来源: 互联网

标签:拦截器 return SpringMVC request session 系列 public 页面


一、概述

1、拦截器:AOP思想的具体应用

  • SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。
  • SpringMVC中的拦截器是由实现 HandlerInterceptor 或者继承 HandlerInterceptorAdapter 来实现的.
  • SpringMVC拦截器的preHandle方法返回值是Boolean类型,所以条件够就放行,执行方法,而条件不足,前端无法知道是什么原因而被拦截,下面来解决这个问题。
 

2、过滤器和拦截器的区别

过滤器
  • servlet规范中的一部分,任何java web工程都可以使用
  • 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
拦截器
  • 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
  • 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
 

二、自定义实现拦截器

1、搭建基础项目、导入依赖(可以选择不要这么多依赖)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <groupId>com.jason</groupId>
    <artifactId>spring-07-intercepter</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>


        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>


        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>


        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>


</project>

2、配置web.xml和springmvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


    <!--注册servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--自动扫描-->
    <context:component-scan base-package="com.jason.controller"/>


    <!--静态资源过滤-->
    <mvc:default-servlet-handler/>


    <!--JSON乱码-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean
                            class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <!--视图解析器-->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

3、编写拦截器

public class MyInterceptor implements HandlerInterceptor {


  @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("===清 理===");
  }
}

4、设置拦截器

<!--关于拦截器的配置-->
<mvc:interceptors>
   <mvc:interceptor>
       <!--/** 包括路径及其子路径-->
       <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
       <!--/admin/** 拦截的是/admin/下的所有-->
       <mvc:mapping path="/**"/>
       <!--bean配置的就是拦截器-->
       <bean class="com.kuang.interceptor.MyInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

5、编写controller接收请求

@RestController
public class TestController {
  @RequestMapping("/t1")
  public String test(){
    System.out.println("TestController=>test()执行了...");
    return "√";
  }
}

6、视图页面

<a href="${pageContext.request.contextPath}/interceptor">拦截器测试</a>

7、配置tomcat测试

 

三、实现认证用户功能

1、实现思路

  • 有一个登陆页面,需要写一个controller访问页面。
  • 登陆页面有一提交表单的动作。需要在controller中处理。判断用户名密码是否正确。如果正确,向session中写入用户信息。返回登陆成功。
  • 拦截用户请求,判断用户是否登陆。如果用户已经登陆。放行, 如果用户未登陆,跳转到登陆页面
 

2、基础项目搭建通上面自定义拦截器

 

3、编写登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<h1>登录页面</h1>
<hr>
<body>
<form action="${pageContext.request.contextPath}/user/login">
  用户名:<input type="text" name="username">

  密码:<input type="password" name="pwd">

  <input type="submit" value="提交">
</form>
</body>
</html>

 

4、编写controller处理

@Controller
@RequestMapping("/user")
public class UserController {


  //跳转到登陆页面
  @RequestMapping("/jumplogin")
  public String jumpLogin() throws Exception {
    return "login";
  }


  //跳转到成功页面
  @RequestMapping("/jumpSuccess")
  public String jumpSuccess() throws Exception {
    return "login";
  }


  //登陆提交
  @RequestMapping("/login")
  public String login(HttpSession session, String username, String pwd) throws Exception {
    // 向session记录用户身份信息
    System.out.println("接收前端===" + username);
    session.setAttribute("user", username);
    return "success";
  }


  //退出登陆
  @RequestMapping("logout")
  public String logout(HttpSession session) throws Exception {
    // session 过期
    session.invalidate();
    return "login";
  }
}

 

5、登录成功页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录成功页面</h1>
<hr>
${user}
<a href="${pageContext.request.contextPath}/user/logout">注销</a>

</body>
</html>

 

6、index页面测试跳转

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
   <h1>首页</h1>
   <hr>
  <%--登录--%>
   <a href="${pageContext.request.contextPath}/user/jumplogin">登录</a>
   <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功页面</a>


  </body>
</html>

 

7、编写拦截器

public class LoginInterceptor implements HandlerInterceptor {
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
    HttpSession session = request.getSession();
    // 如果是登陆页面则放行
    System.out.println("uri: " + request.getRequestURI());
    if (request.getRequestURI().contains("login")) {
      return true;
    }

    if (request.getRequestURI().contains("jumplogin")) {
      return true;
    }

    // 如果用户已登陆也放行
    if (session.getAttribute("user") != null) {
      return true;
    }


    // 用户没有登陆跳转到登陆页面
    request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
    return false;
  }
}

8、配置文件中注册拦截器

<!--关于拦截器的配置-->
<mvc:interceptors>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
       <bean id="loginInterceptor" class="com.kuang.interceptor.LoginInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

9、配置tomcat测试

                                             

标签:拦截器,return,SpringMVC,request,session,系列,public,页面
来源: https://blog.csdn.net/whc888666/article/details/116791318

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有