gpt4 book ai didi

java - Spring JavaConfig 没有捕获 PageNotFound?

转载 作者:行者123 更新时间:2023-12-03 18:27:42 27 4
gpt4 key购买 nike

我正在尝试设置一个在我的 Spring WebMVCConfig 中未找到的页面,它无法正常工作..

这是我的配置:

@Configuration
@EnableWebMvc
@PropertySource("classpath:application.properties")
@Import(DatabaseConfig.class)
@ImportResource("/WEB-INF/spring/applicationContext.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {

private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);

@Autowired
Environment env;

@Bean
public ViewResolver resolver() {
UrlBasedViewResolver url = new UrlBasedViewResolver();
url.setPrefix("/WEB-INF/view/");
url.setViewClass(JstlView.class);
url.setSuffix(".jsp");
return url;
}

@Bean(name = "messageSource")
public MessageSource configureMessageSource() {
logger.debug("setting up message source");
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}

@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("setting up resource handlers");
registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.debug("configureDefaultServletHandling");
configurer.enable();
}

@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}


public @Bean HandlerExceptionResolver exceptionResolver() {
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "404");
mappings.put(DataAccessException.class.getName(), "dataAccessFailure");
mappings.put(TransactionException.class.getName(), "dataAccessFailure");

SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
resolver.setExceptionMappings(mappings);

return resolver;
}


@Bean
public DefaultAnnotationHandlerMapping mapping() {
DefaultAnnotationHandlerMapping m = new DefaultAnnotationHandlerMapping();
m.setDetectHandlersInAncestorContexts(true);
return m;
}
}

现在,如果我输入一个未映射的 URL,我会认为它会转到我的 404.jsp 页面吗?

最佳答案

配置自定义错误页面(针对 404 或任何其他错误代码)的方法是在 web.xml 中...

<error-page>
<error-code>404</error-code>
<location>/my-custom-page-not-found.html</location>
</error-page>

url 可以是静态页面、自定义 jsp 甚至是 Spring Controller 。

关于java - Spring JavaConfig 没有捕获 PageNotFound?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551036/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com