springboot学习[版本2.6.2]拦截器day4-1

拦截器

  • 为什么使用拦截器
  • HandlerInterceptor拦截器接口
  • 实例(主要好懂,比废话实用)
    • 实例目录
    • 先建立一个拦截器实例实现HandlerInterceptor接口
    • 将拦截器注册到容器中实现 WebMvcConfigurer接口
      • addPathPatterns方法拦截所有请求包括静态资源
      • excludePathPatterns方法设置拦截器放行路径
    • TableController
    • User
    • 静态页面准备
      • login.html
      • main.html
      • basic_html

为什么使用拦截器

拦截器用于拦截用户的请求并进行相应的处理(统一处理登录验证,页面编码等)

HandlerInterceptor拦截器接口

springboot学习[版本2.6.2]拦截器day4-1_第1张图片

实例(主要好懂,比废话实用)

实例目录

springboot学习[版本2.6.2]拦截器day4-1_第2张图片

先建立一个拦截器实例实现HandlerInterceptor接口

package com.example.day3.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 进行登录检查的拦截器
 * 1.配置拦截器拦截哪些请求
 * 2.把这些配置放置在容器中
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        log.info("拦截的请求路径是{}",requestURI);
        //登录检查逻辑
        HttpSession session = request.getSession();

        Object loginUser = session.getAttribute("loginUser");

        if (loginUser != null) {
            //放行
            return true;
        } else {
            //进行拦截
            //未登录跳转到登录页
            //将提示信息放在请求域中
            request.setAttribute("msg", "请先登录");
//            response.sendRedirect("/");
            //将请求域中的消息进行转发
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        }
    }

    /**
     * 目标方法执行完成以后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle:{}",modelAndView);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}",ex);
    }
}

将拦截器注册到容器中实现 WebMvcConfigurer接口

注意一定要加@Configuration注解,这样拦截器才能作用

package com.example.day3.config;

import com.example.day3.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 1、编写一个拦截器实现HandlerInterceptor接口
 * 2、拦截器注册到容器巾(实现WebMvcConfigurer的addInterceptors)
 * 3、指定拦截规则【如I果是拦裁所有,静态资源也会被拦哉】
 */
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns拦截所有请求包括静态资源
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/", "/login");//拦截器放行路径
    }
}

addPathPatterns方法拦截所有请求包括静态资源

若有多个路径可以全写进去

addPathPatterns("/**","....")

excludePathPatterns方法设置拦截器放行路径

若有多个路径可以全写进去

excludePathPatterns("/", "/login","....")

TableController

package com.example.day3.controller;

import com.example.day3.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * 进入table列表页的一系列跳转
 */
@Controller
public class TableController {

    @GetMapping("/basic_table")
    public String basic_table(HttpSession session, Model model) {
        List<User> users = Arrays.asList(new User("韩金轮","123456"),
                new User("大司马","456789"),
                new User("韩金龙","111111"));
        model.addAttribute("users",users);
        return "table/basic_table";
    }

    @GetMapping("/dynamic_table")
    public String dynamic_table() {
        return "table/dynamic_table";
    }

    @GetMapping("/response_table")
    public String response_table() {
        return "table/response_table";
    }

    @GetMapping("/editable_table")
    public String editable_table() {
        return "table/editable_table";
    }
}

User

package com.example.day3.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private String username;
    private String password;

}

静态页面准备

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #container{
      height: 100vh;
      width: 100vw;
      display: flex;
      justify-content:center;
      align-content: center;
    }
    #form_wrap{
      height: 500px;
      width: 350px;
      margin: 50px;
    }
  </style>
</head>
<body>
  <div id="container">
    <div id="form_wrap">
      <form th:action="@{/login}" method="post">
        username:<input type="text" name="username"/><br><br>
        password:<input type="text" name="password"/><br><br>
        <input type="submit" value="login"><br>
        <label style="color: orangered" th:text="${msg}"></label>
      </form>
    </div>
  </div>
</body>
</html>

main.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>main</h2>
    <div>[[${session.loginUser.username}]]</div><br>
    <a th:href="@{/basic_table}">basic_table</a><br>
    <a th:href="@{/dynamic_table}">dynamic_table</a><br>
    <a th:href="@{/response_table}">response_table</a><br>
    <a th:href="@{/editable_table}">editable_table</a><br>
</body>
</html>

basic_html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h2>basic_html</h2>
</body>
</html>

你可能感兴趣的:(笔记,Java学习,#,SpringBoot,spring,boot,java,spring)