【问题标题】:thymeleaf + springboot + springsecurity project configurationthymeleaf + springboot + springsecurity 项目配置
【发布时间】:2017-08-16 16:42:19
【问题描述】:
  • spring security 4.2.2
  • 百里香叶 3.0.3

我有一个 spring boot 项目,后来开始使用 spring security 来保护一些 API 端点,使用 spring security 实现的 default 登录页面进行身份验证,但现在我必须实现一个自定义登录页面。

我正在尝试学习本教程:http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/guides/html5/form-javaconfig.html

但我发现自己无法正确显示自定义表单。

我很确定这是因为我没有定义任何模板解析器,但公平地说,即使我阅读了所有示例,我仍然无法完全弄清楚如何定义。 所以我在这里使用:

SecurityConfig

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
    .antMatchers("/api/survey/report/**").hasRole(ADMIN_ROLE)
    .and().formLogin().loginPage("/login")
    .and().logout();
  }
}

自定义和新创建的登录控制器

@Controller
public class LoginController {

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

login.htm 作为指南:

<html xmlns:th="http://www.thymeleaf.org">
<head th:include="layout :: head(title=~{::title},links=~{})">
<title>Please Login</title>
</head>
<body th:include="layout :: body" th:with="content=~{::content}">
<div th:fragment="content">
<form name="f" th:action="@{/login}" method="post">
    <fieldset>
        <legend>Please Login</legend>
        <div th:if="${param.error}" class="alert alert-error">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}" class="alert alert-success">
            You have been logged out.
        </div>
        <label for="username">Username</label>
        <input type="text" id="username" name="username"/>
        <label for="password">Password</label>
        <input type="password" id="password" name="password"/>
        <div class="form-actions">
            <button type="submit" class="btn">Log in</button>
        </div>
    </fieldset>
</form>
</div>
</body>
</html>

就目前的情况而言,我相信我应该实现一个新类来确认我的百里香叶(在这里进行假设),但我已经有一个配置我的应用程序的类:MvcConfiguration

@Configuration
public class MvcConfiguration implements ServletContextInitializer,
EmbeddedServletContainerCustomizer {

虽然我可以在那里添加模板解析器,但无济于事。因为我的模板无法识别

注意:不将模板解析器添加到 MvcConfiguration 与添加它的结果相同:模板不可访问

我知道该指南基于 spring mvc 应用程序,我正在我自己的项目中实现它,但如果有人能指出我正确的方向,我将非常感激

编辑:

这是我得到最多的错误:java log

【问题讨论】:

  • 异常是在 ServletContext 中找不到“views/login.html”。在您的问题中,您说您的模板名为“login.htm”。这只是一个错字,你真的把它命名为“login.html”吗? “login.html”在您的项目中存在于哪里?是在 WEB-INF/views 文件夹下,还是其他地方?
  • 我在资源/视图中将其命名为 login.html

标签: java spring-mvc spring-boot spring-security thymeleaf


【解决方案1】:
  1. 确保您的文件存在于资源/模板下
  2. 让您在 pom.xml 中添加百里香叶依赖项(默认情况下百里香叶解析器解析视图)

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2021-01-21
    • 2021-04-05
    • 2017-06-01
    • 2022-09-29
    • 2020-12-20
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多