App下載

Java代碼詳解SpringMVC中的攔截器使用方法

猿友 2021-08-05 14:56:49 瀏覽數(shù) (2087)
反饋

簡(jiǎn)介

SpringMVC的處理器攔截器類似于Servlet開(kāi)發(fā)中的過(guò)濾器Filter,用于對(duì)處理器進(jìn)行預(yù)處理和后處理。開(kāi)發(fā)者可以自己定義一些攔截器來(lái)實(shí)現(xiàn)特定的功能。

過(guò)濾器

  1. servlet規(guī)范中的一部分,任何java web工程都可以使用
  2. 在url-pattern中配置了/*之后,可以對(duì)所有要訪問(wèn)的資源進(jìn)行攔截

攔截器

  1. 攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
  2. 攔截器只會(huì)攔截訪問(wèn)的控制器方法, 如果訪問(wèn)的是jsp/html/css/image/js是不會(huì)進(jìn)行攔截的

過(guò)濾器與攔截器的區(qū)別:

攔截器是AOP思想的具體應(yīng)用。

攔截器初體驗(yàn)

1.新建一個(gè)項(xiàng)目,添加web支持,在IDEA導(dǎo)入該項(xiàng)目依賴的lib包。

2.配置web.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-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>

3.配置springmvc-servlet.xml

<?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
             http://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/mvc
             http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 掃描指定包,讓指定包下的注解生效   -->
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>

    <!-- 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>

4.編寫(xiě)自定義的攔截器。(實(shí)現(xiàn)HandlerInterceptor接口)

package interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    //在請(qǐng)求處理的方法之前執(zhí)行
    //如果返回true執(zhí)行下一個(gè)攔截器
    //如果返回false就不執(zhí)行下一個(gè)攔截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------處理前------------");
        return true;
    }
    //在請(qǐng)求處理方法執(zhí)行之后執(zhí)行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("------------處理后------------");
    }
    //在dispatcherServlet處理后執(zhí)行,做清理工作.
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("------------清理------------");
    }
}

事實(shí)上,只要重寫(xiě)preHandle方法就可以。

5.在springmvc-servlet.xml文件中配置攔截器

    <!--關(guān)于攔截器的配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--/** 包括路徑及其子路徑-->
            <!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會(huì)被攔截-->
            <!--/admin/** 攔截的是/admin/下的所有-->
            <mvc:mapping path="/**"/>
            <!--bean配置的就是攔截器-->
            <bean class="interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

6.編寫(xiě)controller

package controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class InterceptorController {
    @RequestMapping("/interceptor")
    public String test(){
        System.out.println("InterceptorController");
        return "ok";
    }
}

7.配置Tomcat,進(jìn)行測(cè)試

初體驗(yàn):自定義攔截器實(shí)現(xiàn)了HandlerInterceptor接口,重寫(xiě)了preHandle方法。在preHandle方法中,返回值決定了是否攔截,當(dāng)返回值為true時(shí),不攔截;反之則攔截。

8.結(jié)果:

  • 返回值為true,攔截器不攔截,跳轉(zhuǎn)
  • 返回值為false,攔截器攔截,不跳轉(zhuǎn)

攔截器再體驗(yàn)-登錄驗(yàn)證

實(shí)現(xiàn)思路

  1. 有一個(gè)登陸頁(yè)面,需要寫(xiě)一個(gè)controller訪問(wèn)頁(yè)面。
  2. 登陸頁(yè)面有一提交表單的動(dòng)作。需要在controller中處理。判斷用戶名密碼是否正確。如果正確,向session中寫(xiě)入用戶信息。返回登陸成功。
  3. 攔截用戶請(qǐng)求,判斷用戶是否登陸。如果用戶已經(jīng)登陸。放行, 如果用戶未登陸,跳轉(zhuǎn)到登陸頁(yè)面

登錄界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>

<h1>登錄頁(yè)面</h1>
<hr>

<body>
<form action="${pageContext.request.contextPath}/user/login">
  用戶名:<input type="text" name="username"> <br>
  密碼:<input type="password" name="pwd"> <br>
   <input type="submit" value="提交">
</form>
</body>
</html>

controller處理請(qǐng)求

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

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

   //跳轉(zhuǎn)到登陸頁(yè)面
   @RequestMapping("/jumplogin")
   public String jumpLogin() throws Exception {
       return "login";
  }

   //跳轉(zhuǎn)到成功頁(yè)面
   @RequestMapping("/jumpSuccess")
   public String jumpSuccess() throws Exception {
       return "success";
  }

   //登陸提交
   @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 過(guò)期
       session.invalidate();
       return "login";
  }
}

登錄成功頁(yè)面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>

<h1>登錄成功頁(yè)面</h1>
<hr>

${user}
<a href="${pageContext.request.contextPath}/user/logout">注銷</a>
</body>
</html>

index頁(yè)面

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

index頁(yè)面

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

編寫(xiě)控制器

package interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().contains("login")) {
            return true;
        }

        HttpSession session = request.getSession();

        // 如果用戶已登陸,不攔截
        if(session.getAttribute("user") != null) {
            return true;
        }

        // 用戶沒(méi)有登陸,攔截,并跳轉(zhuǎn)到登陸頁(yè)面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}

在springmvc-servlet.xml配置攔截器

<mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean id="loginInterceptor" class="interceptor.LoginInterceptor"/>
        </mvc:interceptor>

配置Tomcat,測(cè)試。

結(jié)果:沒(méi)有登錄就無(wú)法直接訪問(wèn)登陸成功頁(yè)面。

以上就是 SpringMVC 攔截器的基本內(nèi)容和使用的詳細(xì)內(nèi)容,想要了解更多關(guān)于SpringMVC攔截器的資料,請(qǐng)關(guān)注W3Cschool其它相關(guān)文章!也希望大家能夠多多支持!

0 人點(diǎn)贊