温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring中如何自定义登陆页面和主页

发布时间:2021-11-17 10:43:21 来源:亿速云 阅读:172 作者:小新 栏目:大数据

小编给大家分享一下spring中如何自定义登陆页面和主页,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

spring中如何自定义登陆页面和主页

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.

spring中如何自定义登陆页面和主页

语法错误

spring中如何自定义登陆页面和主页

高亮语法

<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>
<h2>欢迎光临</h2>
<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>
<h2 th:inline="text">不好意思,您没有访问权限</h2>
<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();//所有的请求需要在登陆之后才能访问
}

看完了这篇文章,相信你对“spring中如何自定义登陆页面和主页”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI