8.SpringMVC interceptor

Reprinted: https: //blog.kuangstudy.com/index.php/archives/484/

A .SpringMVC interceptor

1 Introduction

(1) SpringMVC processor interceptors like filter Filter Servlet Development, processor for preprocessing and postprocessing. Developers can define some interceptors themselves to perform specific functions.

(2) the difference between the filter and the interceptor: Blocker is an application of AOP thought.

filter

  • Part of the servlet specification, any java web project can be used

  • After configuring / url-pattern in the *, can intercept all the resources you want to access

Interceptor

  • Interceptors are SpringMVC framework of their own, only to use the project to use the framework of SpringMVC

  • Interceptor will intercept access control method, if the visit is jsp / html / css / image / js will not be intercepted

2. Custom interceptors

(1) Step:

  1. The establishment of a common maven project springmvc-08-interceptor, add web framework, import jar package (slightly)

  2. Web.xml configuration and springmvc-servlet.xml (omitted)

  3. Custom interceptors MyInterceptor.java

  4. Placed springmvc-servlet.xml

  5. Write controller

  6. Configuring Tomcat and test

Custom interceptors MyInterceptor.java

Note: only rewriting preHandle general interceptor for processing prior to the controller

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 {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println ( "before the treatment ------------ ------------" );
         return  to true ;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println ( "------------ ------------ post-treatment" );
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println ( "------------ ------------ clean up" );
    }
}

Placed springmvc-servlet.xml

<! - arranged on interceptor -> 
< MVC: interceptors > 
    < MVC: Interceptor > 
        <! - / **: including a path and sub-path -> 
        <! - / ADMIN / *: blocked is / admin / add, etc. this, / admin / add / user will not be blocked -> 
        <-! / admin / **: that blocks all / admin / under -> 
        < MVC: Mapping path = "/ **" /> 
        ! <- bean is configured interceptor -> 
        < bean class = "ustc.wzh.config.MyInterceptor" /> 
    </ MVC: interceptor > 
</ MVC: interceptors >

Write controller

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

@RestController
public class TestController {

    @GetMapping("/test1")
    public String test1(){

        System.out.println ( "method of performing the controller" );
         return "Hello" ;
    }
}

test:

3. interceptor Case

(1) Purpose: Only logged-on user to enter the home main.jsp

(2) the step of:

  1. Add index.jsp placed login.jsp login page and home page links main.jsp

  2. Add login.jsp and Home main.jsp

  3. Add Controller

  4. Add interceptors and configure springmvc-servlet.xml

  5. test

Add index.jsp placed login.jsp login page and home page links main.jsp

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

  <h1><a href="${pageContext.request.contextPath}/user/jumpLogin">登录页面</a> </h1>

  <h1><a href="${pageContext.request.contextPath}/user/main">首页</a> </h1>
  </body>
</html>

Add login.jsp

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

<% - in all of the resources under the WEB-INF, only through the Controller, or Servlet access -%>
<H1> login page </ h1>
<hr>

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

Add main.jsp

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

${username}
<a href="${pageContext.request.contextPath}/user/logout">注销</a>

</body>
</html>

Add Controller

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

import javax.servlet.http.HttpSession;

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

    // landing submit 
    @PostMapping ( "/ the Login" )
     public String the Login (the HttpSession the session, String username, String pwd) {
         // record the user identity information to the session 
        System.out.println ( "receive front-end ===" + username) ;
         IF (username.equals ( "user1") && pwd.equals ( "123456" )) {
            session.setAttribute("username", username);
            session.setAttribute("password", pwd);
            return "main";
        } else {
            session.setAttribute("username", null);
            session.setAttribute("password", null);
            return "login";
        }

    }

    // jump to the landing page 
    @ RequestMapping ( "/ jumpLogin" )
     public String jumpLogin () {
         return "the Login" ;
    }

    // jump to the success page 
    @ RequestMapping ( "/ main" )
     public String main () {
         return "main" ;
    }

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

Add 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 {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是登陆页面则放行
        System.out.println("uri: " + request.getRequestURI());
        if (request.getRequestURI().contains("login") || request.getRequestURI().contains("jumpLogin")) {
            return true;
        }

        HttpSession session = request.getSession();


        // if the user has landed also released 
        IF (! Session.getAttribute ( "username") = null ) {
             return  to true ;
        }

        // user is not logged jump to the landing page 
        request.getRequestDispatcher ( "/ the WEB-INF / JSP / the login.jsp" ) .forward (Request, the Response);
         return  false ;
    }
}

Placed springmvc-servlet.xml

<mvc:interceptor>
    <! - / ** : including a path and sub-path ->
    <-! / Admin / *: intercept is / admin / add, etc. This, / admin / add / user will not be blocked ->
    <-! / Admin / **: that blocks all / admin / under ->
    <mvc:mapping path="/user/**"/>
    <-! Bean is configured interceptor ->
    <bean class="ustc.wzh.config.LoginInterceptor"/>
</mvc:interceptor>

Testing correct

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12339993.html