SpringBoot实现简单的登陆拦截器学习笔记

x33g5p2x  于2022-03-13 转载在 Spring  
字(2.1k)|赞(0)|评价(0)|浏览(290)

1.登陆成功后设置Session

package com.ckm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpSession session)
    {
        System.out.println(username+" -->"+password);
        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else {
            model.addAttribute("msg","用户名或者密码错误!");
            return "index";
        }
    }

}

2.新建LoginHandlerInterceptor config类

package com.ckm.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginHandlerInterceptor implements HandlerInterceptor {
    //重写放行方法
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登陆成功后的Session
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null){
            //如果null则没有登陆,返回msg信息
            request.setAttribute("msg","没有权限,请先登陆!");
            //重定向到/index.html登陆页面
            request.getRequestDispatcher("/index.html").forward(request,response);
            //return false不放行
            return false;
        }else {
            //return true放行
            return true;
        }
    }
}

3.在继承WebMvcConfigurer接口的类中重写addInterceptors方法

//重写WebMvcConfigurer接口中addInterceptors方法
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                //拦截所有请求
                .addPathPatterns("/**")
                //哪些请求不会被拦截 登陆页 -- 静态资源文件 static下的所有文件
                .excludePathPatterns("/index.html","/","/user/login","/css/*","/js/**","/img/**");
    }

4.访问127.0.0.1:8080/main.html

相关文章