Springmvc攔截器的實(shí)現(xiàn)原理-創(chuàng)新互聯(lián)

這篇文章主要介紹了Spring mvc攔截器的實(shí)現(xiàn)原理,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

創(chuàng)新互聯(lián)長(zhǎng)期為上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為紅塔企業(yè)提供專業(yè)的網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì),紅塔網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

概述

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

過(guò)濾器與攔截器的區(qū)別:攔截器是AOP思想的具體應(yīng)用。

過(guò)濾器

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

攔截器

  • 攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用

  • 攔截器只會(huì)攔截訪問(wèn)的控制器方法, 如果訪問(wèn)的是jsp/html/css/image/js是不會(huì)進(jìn)行攔截的

自定義攔截器

那如何實(shí)現(xiàn)攔截器呢?

想要自定義攔截器,必須實(shí)現(xiàn) HandlerInterceptor 接口。

新建一個(gè)Moudule , 添加web支持

配置web.xml 和 springmvc-servlet.xml 文件

編寫一個(gè)攔截器

package com.xiaohua.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 httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    System.out.println("------------處理前------------");
    return true;
  }

  //在請(qǐng)求處理方法執(zhí)行之后執(zhí)行
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    System.out.println("------------處理后------------");
  }

  //在dispatcherServlet處理后執(zhí)行,做清理工作.
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    System.out.println("------------清理------------");
  }
}

在springmvc的配置文件中配置攔截器

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

編寫一個(gè)Controller,接收請(qǐng)求

package com.xiaohua.controller;

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

//測(cè)試攔截器的控制器
@Controller
public class InterceptorController {

  @RequestMapping("/interceptor")
  @ResponseBody
  public String testFunction() {
    System.out.println("控制器中的方法執(zhí)行了");
    return "hello";
  }
}

前端 index.jsp

<a href="${pageContext.request.contextPath}/interceptor" rel="external nofollow" >攔截器測(cè)試</a>

啟動(dòng)tomcat 測(cè)試一下!

驗(yàn)證用戶是否登陸(認(rèn)證用戶)

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

有一個(gè)登陸頁(yè)面,需要寫一個(gè)controller訪問(wèn)頁(yè)面。

登陸頁(yè)面有一提交表單的動(dòng)作。需要在controller中處理。判斷用戶名密碼是否正確。如果正確,向session中寫入用戶信息。返回登陸成功。

攔截用戶請(qǐng)求,判斷用戶是否登陸。如果用戶已經(jīng)登陸。放行, 如果用戶未登陸,跳轉(zhuǎn)到登陸頁(yè)面

代碼編寫

編寫一個(gè)登陸頁(yè)面 login.jsp

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

<h2>登錄頁(yè)面</h2>
<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>

編寫一個(gè)Controller處理請(qǐng)求

package com.xiaohua.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";
  }
}

編寫一個(gè)登陸成功的頁(yè)面 success.jsp

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

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

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

在 index 頁(yè)面上測(cè)試跳轉(zhuǎn)!啟動(dòng)Tomcat 測(cè)試,未登錄也可以進(jìn)入主頁(yè)!

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

編寫用戶登錄攔截器

package com.xiaohua.interceptor;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
    // 如果是登陸頁(yè)面則放行
    System.out.println("uri: " + request.getRequestURI());
    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;
  }

  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

  }
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  }
}

在Springmvc的配置文件中注冊(cè)攔截器

<!--關(guān)于攔截器的配置-->
<mvc:interceptors>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean id="loginInterceptor" class="com.xiaohua.interceptor.LoginInterceptor"/>
  </mvc:interceptor>
</mvc:interceptors>

再次重啟Tomcat測(cè)試!

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Spring mvc攔截器的實(shí)現(xiàn)原理”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián)建站,關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站bm7419.com,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

本文標(biāo)題:Springmvc攔截器的實(shí)現(xiàn)原理-創(chuàng)新互聯(lián)
鏈接地址:http://bm7419.com/article18/dcoidp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作網(wǎng)站內(nèi)鏈、外貿(mào)建站、App設(shè)計(jì)、定制網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

營(yíng)銷型網(wǎng)站建設(shè)