java - 无法在 Spring 中处理未映射的 urls/404 错误

标签 java spring spring-mvc

我想处理 Spring MVC 应用程序中未映射的 urls/404 错误我找到了一个示例 Here SO Answer ,我基于Java的配置并尝试了这种方式

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.app.controller" })
public class ServletConfigurer extends WebMvcConfigurerAdapter {
    private Properties errorResolverProperties;
    private Properties errorProperties;     
    /// Here I'm configuring <beans as mentioned in SO Answer
    @Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        errorResolverProperties = new Properties();
        errorProperties = new Properties();
        errorProperties.put("/**", pageNotFoundController());
        errorResolverProperties.put("mappings", errorProperties);       
        return simpleUrlHandlerMapping;
    }
    // this is my Controller
    @Bean
    public PageNotFoundController pageNotFoundController(){
        return new PageNotFoundController();
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions("/WEB-INF/tiles_xml/tiles.xml");
        return tilesConfigurer;     
    }       
}

我的 Controller 是

@Controller
public class PageNotFoundController {
    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleINFException(PageNotFoundException ex) {
        return "error";
    }
}

最后是

public class PageNotFoundException extends RuntimeException {    

    private static final long serialVersionUID = 1L;

    public PageNotFoundException(String message) {
        super(message);
    }
}

但它总是显示相同的 Apache 错误页面,而不是自定义/我的错误页面。

更新

public class AppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {  

        WebApplicationContext rootContext = getWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(rootContext)); 
        servletContext.setInitParameter("defaultHtmlEscape", "true");
        // add the dispatcher servlet and map it to /
        DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "springDispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private AnnotationConfigWebApplicationContext getWebApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.app.config");
        return context;
    }

}

就是这样..

最佳答案

如果你想全局捕获它,你需要一个ControllerAdvice:

@ControllerAdvice
public class ExceptionHandlerController {
    public static final String DEFAULT_ERROR_VIEW = "error";
    public static final String STATUS_CODE = "404";
    public static final String TYPE = "Custom Type";

    @ExceptionHandler(value = {NoHandlerFoundException.class})
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
        ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);
        mav.addObject("timestamp", new Date());
        mav.addObject("status", STATUS_CODE);
        mav.addObject("type", TYPE);
        mav.addObject("message", String.format("The requested url is: %s", request.getRequestURL()));
        return mav;
    }
}

现在您需要激活,在 404 的情况下抛出异常:

@Autowired
public void configureDispatcher(DispatcherServlet dispatcherServlet){
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
}

将其插入任何带@Configuration注释的类中。

就是这样!

更新

将您的类(class)更改为

@Configuration
public class AppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {   
        WebApplicationContext rootContext = getWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(rootContext)); 
        servletContext.setInitParameter("defaultHtmlEscape", "true");
    }

    private AnnotationConfigWebApplicationContext getWebApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.app.config");
        return context;
    }

   @Autowired
   public void configureDispatcher(DispatcherServlet dispatcherServlet){
       dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
   }

}

关于java - 无法在 Spring 中处理未映射的 urls/404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34758577/

相关文章:

java - 如何在 Scala/Java 中测量从虚拟机中窃取的时间?

java - 用值初始化的多维 ArrayList

java - 如何在 neo4j 中使用条件匹配

spring-mvc - Spring MVC 映射 Guava Multimap

java - Spring MVC : How to redirect to a page with error?

java - Spring hibernate 验证

java - 将带有 @ManyToOne 的子实体删除到其他实体时出现 NullPointerException

java - Autowiring 由 EasyMock 工厂方法生成的 bean?

java - 当我尝试在 CRUD Spring boot 应用程序中添加新客户端时,捕获 NullPointerException

java - 在另一个类(class)开始另一项 Activity