SpringMVC拦截器

SpringMVC拦截器

概述

SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现待定的功能

过滤器与拦截器的区别:拦截器是AOP思想的具体应用

过滤器

  • servlet规范中的一部分,任何java web工程都可以使用
  • 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截

拦截器

  • 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
  • 拦截器会拦截访问的控制器方法,如果访问的是jsp/css/html/image/js是不会进行拦截的

拦截器的配置

<mvc:interceptors>
        
        <bean class="com.itheima.interceptor.CustomInterceptor"/>
        
        <mvc:interceptor>
            
            
            <mvc:mapping path="/**"/>
            
            <mvc:exclude-mapping path=""/>
            <bean class="com.itheima.interceptor.Intercepter1"/>
        mvc:interceptor>
        
        <mvc:interceptor>
            
            
            <mvc:mapping path="/hello"/>
            
            <bean class="com.itheima.interceptor.Intercepter2"/>
        mvc:interceptor>
    mvc:interceptors>

拦截器的执行流程

单个拦截器的执行流程

  • 定义CustomInterceptor拦截器
public class CustomInterceptor implements HandlerInterceptor {
     
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
     
        System.out.println("preHandle..........CustomInterceptor");
        //对拦截请求进行放行
        return true;
    }
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
     
        System.out.println("postHandle...........CustomInterceptor");
    }
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
     
        System.out.println("afterCompletion.......CustomInterceptor");
    }
}
  • 配置文件
<mvc:interceptors>
        
        <bean class="com.gd.interceptor.CustomInterceptor"/>
mvc:interceptors>
  • 执行结果
preHandle..........CustomInterceptor//后端控制器方法前执行 返回值为true则向下继续执行。1
postHandle...........CustomInterceptor//控制器方法之后调用 2
afterCompletion.......CustomInterceptor//整个请求完成,视图渲染完成之后调用 3

多个拦截器的执行流程

  • 第一个拦截器
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Intercepter1 implements HandlerInterceptor {
     
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
     
        System.out.println("Intercepter1........preHandle");
        return true;
    }
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
     
        System.out.println("Intercepter1.........postHandle");
    }
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
     
        System.out.println("Intercepter1.......afterCompletion");
    }
}
  • 第二个拦截器
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Intercepter2 implements HandlerInterceptor {
     
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
     
        System.out.println("Intercepter2.....preHandle");
        return true;
    }
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
     
        System.out.println("Intercepter2.....postHandle");
    }
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
     
        System.out.println("Intercepter2......afterCompletion");
    }
}
  • 配置
<mvc:interceptors>
      <mvc:interceptor>
          <mvc:mapping path="/toRegiester"/>
          <bean class="com.gd.interceptor.Intercepter1"/>
      mvc:interceptor>
          <mvc:interceptor>
              <mvc:mapping path="/**"/>
              <bean class="com.gd.interceptor.Intercepter2"/>
          mvc:interceptor>
mvc:interceptors>
  • 执行结果
Intercepter1........preHandle
Intercepter2.....preHandle
Intercepter2.....postHandle
Intercepter1.........postHandle
Intercepter2......afterCompletion
Intercepter1.......afterCompletion

用户登陆的权限认证

用户PO

import java.io.Serializable;
public class User implements Serializable {
     
    private Integer id;
    private String username;
    private String password;
}

UserController

import com.itheima.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
public class UserController {
     
    @RequestMapping(value = "/main",method = RequestMethod.GET)
    public String toMainPage(){
     
        return "main";
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLoginPage(){
     
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user, HttpSession session, Model model){
     
        String username = user.getUsername();
        String password = user.getPassword();
        if (username!=null && username.equals("admin")
                && password!=null && password.equals("123456")) {
     
            session.setAttribute("USER_SESSION",user);
            return "redirect:main";
        }
        model.addAttribute("msg","用户名或者密码错误");
        return "login";
    }
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpSession session){
     
        session.invalidate();
        return "redirect:login";
    }
}

用户登陆表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆页面title>
head>
<body>
${msg}
<form action="${pageContext.request.contextPath}/login" method="post">
    <input type="text" name="username"/><br/>
    <input type="text" name="password"/><br/>
    <input type="submit">
form>
body>
html>

主页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>系统主页title>
head>
<body>
<h1>用户信息h1>
<p>${USER_SESSION.username}p>
<a href="${pageContext.request.contextPath}/logout">注销a>
body>
html>

过滤器UserInterceptor

import com.itheima.po.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserInterceptor implements HandlerInterceptor {
     
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
     
        String uri = request.getRequestURI();
        System.out.println(uri);
        if (uri.indexOf("/login")>0) {
     
            return true;
        }
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        if (user!=null) {
     
            return true;
        }
        request.setAttribute("msg","你还没有登陆请先登陆!");
        request.getRequestDispatcher("/login").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配置

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.gd.interceptor.UserInterceptor"/>
        mvc:interceptor>
mvc:interceptors>

你可能感兴趣的:(spring,mvc,spring,interceptor)