首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Spring MVC中返回403 Forbidden?

在Spring MVC中返回403 Forbidden的方法有很多种,这里给出一种常用的方法。

首先,需要在控制器中抛出一个AccessDeniedException异常,这个异常可以通过Spring Security提供的工具类AccessDeniedException来创建。

代码语言:java
复制
import org.springframework.security.access.AccessDeniedException;

@Controller
public class MyController {
    @GetMapping("/forbidden")
    public String forbidden() {
        throw new AccessDeniedException("您没有权限访问该页面");
    }
}

然后,需要在Spring Security的配置中添加一个AccessDeniedHandler,这个接口可以用来处理AccessDeniedException异常,并返回403 Forbidden的响应。

代码语言:java
复制
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/forbidden").hasRole("ADMIN")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler());
    }

    private AccessDeniedHandler accessDeniedHandler() {
        AccessDeniedHandlerImpl handler = new AccessDeniedHandlerImpl();
        handler.setErrorPage("/403");
        return handler;
    }
}

在这个配置中,我们使用了AccessDeniedHandlerImpl类来创建一个AccessDeniedHandler实例,并设置了一个错误页面/403。当AccessDeniedException异常被抛出时,Spring Security会调用这个处理器,并将请求重定向到/403页面。

最后,需要在视图层中创建一个/403页面,用来显示403 Forbidden的错误信息。

代码语言:html
复制
<!DOCTYPE html>
<html>
<head>
   <title>403 Forbidden</title>
</head>
<body>
    <h1>403 Forbidden</h1>
    <p>您没有权限访问该页面</p>
</body>
</html>

这样,当用户访问需要权限的页面时,就会收到403 Forbidden的响应,并显示错误信息。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券