SpringBoot登录拦截

一、实现登录

1.1):项目目录

1.2):Controller 下面的 test这里账户密码我写成死的了

package com.sxtt.springboot.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;

/**
 * @author Laugh"
 */
@Controller
public class test {
    @RequestMapping({"/username"})
    //首先获取用户输入的账户并且不能为空 且 密码 为 123456才行
    public String test(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session){
        //1. 判断 username 不为空; 2. 判断输入账号是否为 laugh; 3. 判断输入密码是否为 123456;
        if (!StringUtils.isEmpty(username) && "laugh".equals(username) && "123456".equals(password)){

            //第一种:判断我们这里是否登录成功,如果登录成功 则跳转页面
            // return "Hello";
            //第二种:当然也可以重定向过去【推荐👍】
            // return "redirect:/Laugh.html";

            //把登录的用户存入Session中
            session.setAttribute("LoginUser",username);
            return "redirect:/Laugh.html";
        }else {
            //登录失败,在登录页回显 msg
            model.addAttribute("msg","账户或者密码错误!");
            return "index";
        }
    }
}

1.3):config 下面的 MyMvcConFig

package com.sxtt.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Laugh"
 */
@Configuration
public class MyMvcConFig implements WebMvcConfigurer {
    /**
     * 在@Configuration标注的重写配置文件中配置请求映射   快捷键 alt + ins   找ViewControllerRegistry就ok
     */
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/").setViewName("index");
        registry.addViewController("text").setViewName("index");
        registry.addViewController("index").setViewName("index");
        registry.addViewController("login").setViewName("index");
        registry.addViewController("login.html").setViewName("index");
        registry.addViewController("index.html").setViewName("index");

        //假设这个是咱们的内部页面 那我们是不是直接可以通过 这个链接:http://localhost:8080/laugh/Laugh.html 可以直接访问
        registry.addViewController("Laugh.html").setViewName("Hello");
    }

    //自定义的国际化就生效
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

1.4): Application

package com.sxtt.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Laugh"
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

1.5):登录页面 index.html

<!DOCTYPE HTML>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" th:href="@{/Css/bootstrap.css}">
    <link rel="stylesheet" th:href="@{Css/misc-pages.css}">
    <title>登录-员工OA系统</title>
</head>
<body class="simple-page">
    <div class="simple-page-wrap">

        <div class="simple-page-logo ">
            <a href="">
                <span></span>
                <span th:text="#{index.tip}">员工OA系统</span>
            </a>
        </div>

        <div class="simple-page-form" id="login-form">
            <h4 class="form-title m-b-xl text-center" th:text="#{index.please}">请输入用户名和密码</h4>
            <!--这块使用三元运算符,如果msg不为空则执行,为空则反之-->
            <p style="color: red;text-align: center" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
            <form th:action="@{/username}" method="post">
                <div class="form-group">
                    <input type="text" name="username" class="form-control" th:placeholder="#{index.name}" >
                </div>

                <div class="form-group">
                    <input type="password" name="password" class="form-control" th:placeholder="#{index.password}" >
                </div>

                <div class="form-group m-b-xl">
                    <input name="remenberme" value="remenberme" type="checkbox" id="keep_me_logged_in"  style="height:auto;margin:0 0 0 10px;" />
                    <label for="keep_me_logged_in" >[[#{index.remember}]]</label>
                </div>

                <a class="btn btn-sm" th:href="@{/index.html(lge='zh_CN')}">中文</a>
                <a class="btn btn-sm" th:href="@{/index.html(lge='en_US')}">English</a>

                <input type="submit" class="btn btn-primary" th:onclick = "btnRst_Click()"   th:value="#{index.log}" >
            </form>
        </div>

        <div class="simple-page-footer">
            <p>
                <small>[[#{index.newlelpp}]] ?</small>
                <a href="">[[#{index.Createaccount}]]</a>
            </p>
        </div>

    </div>
</body>
</html>

1.6):内部页面 Hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>内部页面</title>
</head>
<body>
    hello,我是[[${session.LoginUser}]],请多多关照!
</body>
</html>

1.7):properties 文件配置

#关闭模板引擎的缓存
spring.thymeleaf.cache=false
#变更虚拟目录  因为增加的虚拟目录所以访问路径需要有所修改哦~   http://localhost:8080/laugh/login
server.servlet.context-path=/laugh
#我们的配置文件的真实目录位置
spring.messages.basename=i18n.index

1.8):static 里面的静态资源下载【Img / Js 里面啥都没有哦~】

1.8):效果展示(这个"GIF"软件不推荐要充钱!)

二、增加拦截

2.1):config 下面的 loginHandlerinterceptor 

package com.sxtt.springboot.config;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 添加一个拦截器 判断用户是否登录
 * @author Laugh"
 */
public class loginHandlerinterceptor implements HandlerInterceptor {
    /**
     *快捷键注释来一个 : Alt + ins 选择 OM / 或者 Ctrl + o
     * @author Laugh"
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这里我们需要获取登录用户信息,获取到了 ok,放行通过,反之则不给放行,我们如何判断用户是否登录了呢?那就是获取Session喽
        Object loginUser = request.getSession().getAttribute("LoginUser");
        //逻辑判断
        if(loginUser == null){
            request.setAttribute("msg","你没有登录!请登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            return true;
        }
    }
}

2.2):config 下面的 MyMvcConFig (新增加了一个 addInterceptors 需要注意别躲复制哦~

package com.sxtt.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Laugh"
 */
@Configuration
public class MyMvcConFig implements WebMvcConfigurer {
    /**
     * 在@Configuration标注的重写配置文件中配置请求映射   快捷键 alt + ins   找ViewControllerRegistry就ok
     */
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/").setViewName("index");
        registry.addViewController("text").setViewName("index");
        registry.addViewController("index").setViewName("index");
        registry.addViewController("login").setViewName("index");
        registry.addViewController("login.html").setViewName("index");
        registry.addViewController("index.html").setViewName("index");

        //假设这个是咱们的内部页面 那我们是不是直接可以通过 这个链接:http://localhost:8080/laugh/Laugh.html 可以直接访问【没有拦截器就可以直接访问,有拦截器则反之】
        registry.addViewController("Laugh.html").setViewName("Hello");
    }

    //自定义的国际化就生效
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns("/**");拦截所有请求
        //excludePathPatterns排除掉这些请求  让不要拦截
        registry.addInterceptor(new loginHandlerinterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/username","/Css/*","Js/*","Img/*");
    }
}

2.3):直接访问,内部页面【Hello.html】

请求地址:http://localhost:8080/laugh/Laugh.html

已经拦截成功,因为没有登陆!

2.4):登录成功

登陆地址:http://localhost:8080/laugh/

 

posted @ 2023-12-05 17:18  Laugh"  阅读(72)  评论(0编辑  收藏  举报