springboot与thymeleaf与拦截器实现登陆拦截

时间:2019-02-14
本文章向大家介绍springboot与thymeleaf与拦截器实现登陆拦截,主要包括springboot与thymeleaf与拦截器实现登陆拦截使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先是写一个thymeleaf的login.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="/css/common.css" />
</head>
<body>
<form action="login" method="post">
    <div>
        <span id="basic-addon0">&nbsp;</span>
        <span style="font-size: 12px;color: red" th:text="${error}" aria-describedby="basic-addon0"></span>
        <br />
    </div>
    <div>
        <span id="basic-addon1">用户名</span>
        <input id="name" name="name" type="text" placeholder="用户名" aria-describedby="basic-addon1" />

    </div>
    <br />
    <div>
        <span id="basic-addon2">密码</span>
        <input id="password" name="password" type="password" placeholder="密码" aria-describedby="basic-addon2" />
    </div>
    <br />
    <button type="submit" style="width:190px;">登 录</button>

</form>
</body>
</html>

然后是写一个LoginController类:

package com.matai.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/")
public class LoginController {
    public static final String FAILED = "用户名或密码错误!";

    @Value("${user.username}")
    private String username;
    @Value("${user.password}")
    private String pwd;

    @GetMapping("/login")
    public ModelAndView login(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/login")
    public ModelAndView login(ModelAndView modelAndView, @Param("name") String name, @Param("password") String password, HttpSession session){
        if(!username.equals(name) || !pwd.equals(password)){
            modelAndView.addObject("error",FAILED);
            modelAndView.setViewName("login");
            return modelAndView;
        }
        session.setAttribute("account", name);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

用户名和密码是通过配置文件写死了的:

然后是拦截器:

package com.matai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {

    @Bean
    public SecurityInterceptor getSecurityInterceptor(){
        return  new SecurityInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //排除配置
        addInterceptor.excludePathPatterns("/login");
        //拦截配置
        addInterceptor.addPathPatterns("/**");
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, IOException {
            HttpSession session = request.getSession();
            //判断是否已有该用户登录的session
            if(session.getAttribute("account") !=null){
                return  true;
            }
            //跳转到登录页
            String url = "/login";
            response.sendRedirect(url);
            return false;
        }
    }
}

拦截器中主要就是先配置需要拦截和放开的url,其次就是判断用户是否登陆,未登陆就拦截,登陆了就放行即可。