java - Spring Boot自定义登录页面显示404

标签 java spring-boot spring-security freemarker

您好,我目前正在尝试使用 Spring Boot Security 设置一个简单的登录页面,但每当我尝试访问登录 View 时,都会收到 404“页面未找到”错误。

安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
}

登录 View ,使用 freemarker(位于 main/resources/templates/login.ftl):

<body class="login">
<div>
<div class="login_wrapper">
    <div class="animate form login_form">
        <section class="login_content">
            <form>
                <h1>Login Form</h1>
                <div>
                    <input type="text" class="form-control" placeholder="Username" required="" />
                </div>
                <div>
                    <input type="password" class="form-control" placeholder="Password" required="" />
                </div>
                <div>
                    <a class="btn btn-default submit" href="/units">Log in</a>
                </div>
                <div class="clearfix"></div>
            </form>
        </section>
    </div>
</div>
</div>
</body>

有人知道我做错了什么吗?感谢您的帮助!

最佳答案

您需要有一个用于/login 的 View Controller 。要么为此编写一个 Controller ,要么执行以下操作。

@EnableWebMvc
@ComponentScan("package_name")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    // ...

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}

设置 View rosolver:

@Bean  
public InternalResourceViewResolver viewResolver() {  
InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
    resolver.setPrefix("/WEB-INF/pages/");  
    resolver.setSuffix(".ftl");
    return resolver;  
}

现在将您的ftl 文件放入webapp/WEB-INF/pages 目录中。一切就绪。

关于java - Spring Boot自定义登录页面显示404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962793/

相关文章:

java - Windows 7 上 Apache Tomcat 8 的 %CATALINA_HOME% 环境变量

java - 如何在 Eclipse RCP 应用程序的 View 中显示 Google map

java - 为什么我不能在 Spring Boot 中通过 @Bean 注解注册 HttpRequestHandlerServlet

java - 在生产中使用 spring boot 有什么缺点?

azure - Spring Security支持多种身份验证类型

java - 在 Scene2d 中使用 TouchDown 事件移动 Actor

java - 如何确定java中构造函数中变量的类型?

amazon-web-services - AWS ELB 后面带有嵌入式 Tomcat 的 Spring Boot - HTTPS 重定向

java - 在哪里可以找到有关 spring-security 注释的更多信息

java - 如何正确使用 JTI 声明和 JWT 来防止重放攻击?