自定义登陆页面和主页

1、添加模版引擎

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、配置登陆页面路径

在WebSecurityConfig复写configure(HttpSecurity http),复写登陆页面的路径。
@Override
protected void configure (HttpSecurity http) throws Exception{
   http.formLogin()
           .loginPage("/login");
}

3、新建登陆页面,并跳转到登陆页

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login333</title>
</head>
<body>
  <div th:if="${param.error}">
      用户名密码错误,要不去<a th:href="@{/}">首页</a>看看?
  </div>
  <div th:if="${param.logout}">
      您已经登陆
  </div>
  <form th:action="@{/login}" method="post">
      <div><label>用户名:<input type="text" name="username"></label></div>
      <div><label>密码: <input type="password" name="password"></label></div>
      <div><input type="submit" value="登陆"></div>
  </form>
</body>
</html>

@GetMapping("/login")
public String login() {
    return "/login";
}

This application has no explicit mapping for /error, so you are seeing this as a fallback.

语法错误

高亮语法

<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

4、新建主页,并跳转到主页

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>欢迎光临</h1>
<p>点击<a th:href="@{/hello}">这里</a>打个招呼吧</p>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="退出登陆">
</form>
<p><a th:href="@{/hello/helloAdmin}">管理员</a></p>
<p><a th:href="@{/hello/helloUser}">普通用户</a></p>
</body>
</html>

@GetMapping({"","/","/index"})
public String index() {
    return "/index";
}

5、没有权限页面显示,及所有人可以访问登陆页,所有请求都要登陆后才能访问

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>没有权限</title>
</head>
<body>
<h1 th:inline="text">不好意思,您没有访问权限</h1>
<p><a th:href="@{/hello/helloUser}">前往普通用户界面</a></p>
<form th:if="${param.logout}}" method="退出登陆">
    <input type="submit" value="退出登陆">
</form>
</body>
</html>

@Override
protected void configure (HttpSecurity http) throws Exception{
   http.formLogin()
           .loginPage("/login")
   .and()
   .authorizeRequests()
           .antMatchers("/login").permitAll() //允许所有人可以访问登陆页面
   .anyRequest().authenticated();//所有的请求需要在登陆之后才能访问
}

转载于:https://my.oschina.net/u/2427561/blog/3089846

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值