SpringBoot -- 登录 & 拦截器

SpringBoot – 登录 & 拦截器

一、登录

@Controller
public class LoginController {

    @PostMapping(value = "/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> map,
                        HttpSession session){
        //判断用户名是否为空且密码赋值为123456
        if(!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            ///main.html:当前目录下的main.html页面
            return "redirect:/main.html";
        } else {
            map.put("msg","用户名或密码错误");
            return  "login";
        }

    }
}

登录细节:

  1. 登录需要有用户名和密码,不为空则转发到主页面,若为空则返回登录页面

  2. 登录时通过 Httpsession 保存好用户名,方便查看用户的登录状态

     session.setAttribute("loginUser",username);
    
  3. 为了防止页面重复提交,使用重定向 redirect 转发页面

  4. 登录错误

    1) 显示错误提示,通过 Map<String,Object>集合 去保存错误信息

    map.put("msg","用户名或密码错误");
    

    2) 同时在登录页面进行提示:

    注意:这一句是在进行判断,当登录错误时这一句才会起作用,代码才显示在页面中,其他情况在网页查看源代码时看不到这一句代码。

    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    



二、若无登录,则拦截
  1. 先请求登录时的用户名,通过登录时保存的 session 去获取

    request.getSession().getAttribute("loginUser");
    
  2. 判断我们请求的用户名是否为空,若为空则进行错误提示并且不能进入到其他页面

    注意:这两步的步骤不能颠倒,不能错误提示不会出现在页面上

     request.setAttribute("msg","没有权限请先登录");
     request.getRequestDispatcher("/index.html").forward(request,response);
    
  3. 添加登录拦截器组件

    • addPathPatterns("/**"):添加所有页面
    • excludePathPatterns("/","/index.html","/user/login"):排除登录页面
    @Configuration
    public class MyConfig implements WebMvcConfigurer {
        //所有的WebMvcConfigurer组件都会一起起作用
        @Bean //将组件注册在容器
        public WebMvcConfigurer webMvcConfigurer(){
            WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
                //视图控制器
                 @Override
                public void addViewControllers(ViewControllerRegistry registry) {
                    registry.addViewController("/").setViewName("login");
                    registry.addViewController("/index.html").setViewName("login");
                    registry.addViewController("/main.html").setViewName("dashboard");
    
                }
               //添加拦截器
                @Override
                public void addInterceptors(InterceptorRegistry registry) {
                    registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login");
                }
            };
            return webMvcConfigurer;
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值