Spring Security (二) :自定义登录界面

因为要自定义界面,所以就先引入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/ 访问测试
在这里插入图片描述
可以发现成功跳转到了自定义的登录页面上,输入账号密码验证
在这里插入图片描述
登陆成功!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值