如何在Spring 4.3与Spring Security 4.2中将403重定向至404?
实现403错误重定向至404页面(Spring 4.3 + Spring Security 4.2)
可以实现,但需要结合web.xml和Spring Security的配置——因为Spring Security会拦截请求,单独配置web.xml可能无法生效。以下是具体步骤:
1. web.xml 错误页面映射配置
在web.xml中配置错误码与页面的映射,将403错误指向404页面的访问路径:
<error-page> <error-code>403</error-code> <location>/404</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/404.jsp</location> </error-page>
这里/404是404页面的访问路径,实际页面文件路径可根据你的视图结构调整。
2. 配置Spring Security允许访问404页面
由于Spring Security默认拦截所有请求,必须显式允许所有用户访问404页面的路径,同时指定Spring Security的访问拒绝处理器指向404页面:
方式一:Java配置类
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 其他安全配置(如登录、CSRF防护等) .authorizeRequests() .antMatchers("/404").permitAll() // 允许所有用户访问404路径 .anyRequest().authenticated() .and() .exceptionHandling() .accessDeniedPage("/404"); // 指定访问拒绝(403)时跳转的页面 } }
方式二:XML配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <security:http> <!-- 允许所有用户访问404路径 --> <security:intercept-url pattern="/404" access="permitAll"/> <!-- 其他拦截规则配置 --> <security:intercept-url pattern="/**" access="isAuthenticated()"/> <!-- 指定访问拒绝时跳转至404页面 --> <security:access-denied-handler error-page="/404"/> <!-- 其他安全配置(如登录表单等) --> </security:http> </beans>
3. 映射404路径至实际页面
如果你的404页面放在WEB-INF目录下(无法直接访问),需要添加一个控制器来映射路径:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ErrorPageController { @RequestMapping("/404") public String show404Page() { // 视图解析器会根据配置的前缀(如/WEB-INF/views/)和后缀(如.jsp)找到页面 return "404"; } }
关键说明
- 必须通过Spring Security的
accessDeniedPage指定403跳转目标,因为Spring Security的访问控制逻辑会优先于web.xml的错误页面配置。 - 确保404页面的访问路径被设置为
permitAll,否则触发403的用户会因权限不足无法访问404页面,导致二次错误。
内容的提问来源于stack exchange,提问作者dynamo
相关产品推荐
相关产品推荐

