因为要自定义界面,所以就先引入thymeleaf模板引擎
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
在自定义的MySecurityConfig
类中重写授权方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/toLogin")//登录页面地址
.loginProcessingUrl("/user/login")//登录访问地址
.defaultSuccessUrl("/").permitAll()//登录成功后默认的跳转地址
.and().authorizeRequests()
.antMatchers("/hello","/css/**").permitAll()//设置无需认证的路径
.anyRequest().authenticated();
}
- “/css/**”:为了保证静态资源生效,这里要进行过滤处理
编写controller
类跳转到登录页面
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AllController {
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
}
编写login.html
页面
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link th:href="@{/css/index_log.css}" rel="stylesheet" />
</head>
<body>
<form id="form" class="login" method="post" th:action="@{/user/login}">
<h2>用户登录</h2>
<div class="login_box">
<input type="text" name='username' id='name' required/>
<label for="name">用户名</label>
</div>
<div class="login_box">
<input type="password" name='password' id='pwd' required="required">
<label for="pwd">密码</label>
</div>
<a onclick="form.submit()" href="javascript:void(0)">登录</a>
</form>
</body>
</html>
- 表单的提交方式必须是post
- 表单的提交地址就是
MySecurityConfig
类中设置的登录访问路径 - 用户名的name属性必须是
username
- 密码的name属性必须是
password
http://localhost:8080/ 访问测试
可以发现成功跳转到了自定义的登录页面上,输入账号密码验证
登陆成功!