用户登录是我们开发网站的基本需求,我们可以使用过滤器实现网站登录功能的开发,在前面的SpringBoot 过滤器 一章中,我们已经了解了SpringBoot的过滤器的基本用法和过滤器的相关选项。
这里主要讲解如何使用SpringBoot 过滤器实现用户登录的功能。
开发流程
在开始之前,先了解登录功能的开发流程。
1.首先登录需要2个页面,登录页和用户首页,所对应的地址分别为
登录页:/admin/login, 模板文件src\main\resources\templates\admin\index.html
欢迎页:/admin/index,模板文件src\main\resources\templates\admin\index.html
2.然后定义过滤器对/admin/*进行拦截,如果用户没有登录则做重定向跳转到/admin/login页面。
3. 编写登录页面和登录逻辑
登录和欢迎页面
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h2>过滤器登录页面</h2>
<form action="#">
<div id="box">
账号:<input type="text" name="uname" id="uname">
<br>
密码:<input type="password" name="passwd" id="passwd">
<br>
<input id="btnLogin" class="button" type="button" value="登录">
</div>
</form>
<script>
$("#btnLogin").click(function(){
var uname=$("#uname").val();
var passwd=$("#passwd").val();
console.log(name,passwd);
$.ajax({
url:'/admin/login',
type:'post',
data:{'uname':uname,'passwd':passwd},
dataType:'json',
success:function(data){
if(data.code==200){
alert(data.msg);
location.href='/admin/index';
}else{
alert(data.msg);
}
},
error:function(){
console.log('请求出错!');
}
})
});
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎页</title>
</head>
<body>
<h2>欢迎页面</h2>
<p th:text="'欢迎用户:' + ${session.admin}"></p>
</body>
</html>
登录过滤器
这里使用url匹配的方法判断url是否以/admin/*的格式,对所有/admin/*的url进行拦截。
1. 过滤器方法文件
package com.example.yxjc.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AdminUrlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("########## 登录校验过滤器 ##########");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//登录判断
HttpSession session = request.getSession();
String uri = request.getRequestURI();
if (!uri.equals("/admin/login")) {
if (session.getAttribute("admin") == null){
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
response.sendRedirect( basePath + "admin/login");
return ;
}
}
System.out.println("########## 继续执行 ##########");
//调用下一个过滤器
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
2. 过滤器配置文件
package com.example.yxjc.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AdminUrlFilterConfig {
@Bean
public FilterRegistrationBean< AdminUrlFilter > filterRegistrationBean() {
FilterRegistrationBean < AdminUrlFilter > registrationBean = new FilterRegistrationBean();
AdminUrlFilter adminUrlFilter = new AdminUrlFilter();
registrationBean.setFilter(adminUrlFilter);
registrationBean.addUrlPatterns("/admin/*");//后台登录地址拦截
registrationBean.setOrder(2);
return registrationBean;
}
}
控制器
为了方便,这里登录校验的判断不做数据库的查询,仅仅判断用户名是否等于admin。
返回值请参考:SpringBoot统一返回格式。
@Controller
public class AdminController {
@GetMapping("/admin/index")
public String index() {
return "admin/index";
}
@ResponseBody
@PostMapping("/admin/login")
public Response doLogin(String uname, String passwd, HttpServletRequest request) {
//todo 数据查询用户
if (uname.equals("admin") && passwd.equals("123")) {
HttpSession session = request.getSession();
session.setAttribute("admin","admin");
return Response.success();
}
return Response.error();
}
@GetMapping("/admin/login")
public String login() {
return "admin/login";
}
}