Spring Boot应用访问localhost:8080/hello跳转302到登录页问题咨询
问题原因
你的项目中引入了spring-boot-starter-security依赖,Spring Security默认开启全局身份校验规则:所有未经过登录认证的请求,都会被302重定向到系统默认的/login登录页,你当前写的Controller、页面模板代码本身没有逻辑问题。
解决方案
根据你的实际需求选择对应方案即可:
方案1:无需使用Spring Security功能
直接删除项目构建配置文件中的Spring Security依赖即可:
如果用Maven,删除pom.xml中的如下依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>如果用Gradle,删除build.gradle中的如下配置:
implementation 'org.springframework.boot:spring-boot-starter-security'保存配置后重新启动项目,访问
/hello即可正常返回页面。方案2:需要保留Spring Security,仅放行
/hello路径
新增Spring Security配置类,手动配置/hello路径无需登录即可访问:package com.example.biblioteca.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/hello").permitAll() // 放行/hello路径 .anyRequest().authenticated() // 其余路径仍需登录 ) .formLogin(form -> form.permitAll()); return http.build(); } }方案3:临时测试无需修改配置
项目启动时控制台会输出Spring Security默认生成的登录密码,格式类似Using generated security password: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,访问/login页输入用户名user,密码填控制台输出的字符串,登录成功后就可以正常访问/hello路径。
内容的提问来源于stack exchange,提问作者Gabrielbueno
相关产品推荐
相关产品推荐

