【问题标题】:why is my ControllerAdvice not working in spring boot为什么我的 ControllerAdvice 在 Spring Boot 中不起作用
【发布时间】:2016-06-23 14:17:13
【问题描述】:

我使用 spring boot 和 spring security,我想为我的应用程序添加错误处理程序,这是我的 ControllerAdvice:

@ControllerAdvice
public class GlobalExceptionController  {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(Exception.class)
    public ModelAndView defaultError(HttpServletRequest req, Exception e)
            throws Exception {

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

}

这是我的 sn-p error.html 代码(使用百里香):

<div class="container">
        <h1 th:inline="text">Error</h1>
        <p th:text="${exception}"></p>
        <p th:text="${url}"></p>
</div>

还有这个spring安全配置sn-p代码:

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll().anyRequest()
        .fullyAuthenticated().and().formLogin().loginPage("/login")
        .failureUrl("/login?error").and().logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and()
        .exceptionHandling().accessDeniedPage("/access?error");

}

如果我尝试访问我的应用程序使用错误的 URL、对象异常和 GlobalExcetionController 中的 url 不会在 error.html 中呈现,为什么?

[更新]

我的 ControllerAdvice 仅在错误 404 时不起作用,但其他错误有效,如何设置 ExceptionHandler 来处理 404 错误?

【问题讨论】:

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


    【解决方案1】:

    [已解决]

    我将此@Bean 添加到我的 Spring Boot 配置中

    @Bean
        public EmbeddedServletContainerCustomizer containerCustomizer() {
            return new EmbeddedServletContainerCustomizer() {
                @Override
                public void customize(ConfigurableEmbeddedServletContainer container) {
    
                    ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND,
                            "/error404.html");
                    container.addErrorPages(error404Page);
    
                }
            };
        }
    

    error404.html 必须位于静态文件夹中

    感谢参考: http://www.sporcic.org/2014/05/custom-error-pages-with-spring-boot/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-15
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2018-10-13
      • 2021-07-07
      相关资源
      最近更新 更多