我正在寻找一种干净的方法,当找不到请求的资源时,在 Spring 4 中返回自定义的 404 错误页面。对不同域类型的查询应该会导致不同的错误页面。
这里有一些代码来表明我的意图(Meter是一个域类):
@RequestMapping(value = "/{number}", method = RequestMethod.GET)
public String getMeterDetails(@PathVariable("number") final Long number, final Model model) {
final Meter result = meterService.findOne(number);
if (result == null) {
// here some code to return an errorpage
}
model.addAttribute("meter", result);
return "meters/details";
}
我想象了几种处理这个问题的方法。首先有可能创建像这样的
RuntimeException
@ResponseStatus(HttpStatus.NOT_FOUND)
public class MeterNotFoundExcption extends RuntimeException { }
然后使用异常处理程序呈现自定义错误页面(可能包含指向仪表列表或任何适当内容的链接)。
但我不喜欢用许多小例外来污染我的应用程序。
另一种可能性是使用
HttpServletResponse
并手动设置状态代码:
@RequestMapping(value = "/{number}", method = RequestMethod.GET)
public String getMeterDetails(@PathVariable("number") final Long number, final Model model,
final HttpServletResponse response) {
final Meter meter = meterService.findOne(number);
if (meter == null) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return "meters/notfound";
}
model.addAttribute("meter", meter);
return "meters/details";
}
但是使用这个解决方案,我必须为许多控制器方法(如编辑、删除)复制前 5 行。
有没有一种优雅的方法来防止多次重复这些行?
解决方案比想象的简单得多。人们可以使用一个通用的
ResourceNotFoundException
定义如下:
public class ResourceNotFoundException extends RuntimeException { }
然后可以使用
ExceptionHandler
注释处理每个控制器中的错误:
class MeterController {
// ...
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "meters/notfound";
}
// ...
@RequestMapping(value = "/{number}/edit", method = RequestMethod.GET)
public String viewEdit(@PathVariable("number") final Meter meter,
final Model model) {
if (meter == null) throw new ResourceNotFoundException();
model.addAttribute("meter", meter);
return "meters/edit";
}
}
每个控制器都可以为
ExceptionHandler
定义自己的 ResourceNotFoundException
。
修改了您的web.xml文件。使用以下代码。
<display-name>App Name </display-name>
<error-page>
<error-code>500</error-code>
<location>/error500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
通过以下代码访问它。
response.sendError(508802,"Error Message");
现在将此代码添加到 web.xml 中。
<error-page>
<error-code>508802</error-code>
<location>/error500.jsp</location>
</error-page>
您可以在 web.xml 中映射错误代码,如下所示
<error-page>
<error-code>400</error-code>
<location>/400</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500</location>
</error-page>
现在您可以创建一个控制器来映射发现任何这些错误时所点击的 url。
@Controller
public class HTTPErrorHandler{
String path = "/error";
@RequestMapping(value="/404")
public String error404(){
// DO stuff here
return path+"/404";
}
}
有关完整示例,请参阅我的教程
100% 免费 xml 的简单答案:
设置 DispatcherServlet 的属性
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
//that's important!!
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
创建@ControllerAdvice:
@ControllerAdvice
public class AdviceController {
@ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "redirect:/404";
}
@RequestMapping(value = {"/404"}, method = RequestMethod.GET)
public String NotFoudPage() {
return "404";
}
}
创建任意内容的404.jsp页面
仅此而已。
我们只需在 web.xml 文件中添加以下几行代码,并在项目根目录中引入一个名为 errorPage.jsp 的新 jsp 文件即可完成需求。
<error-page>
<error-code>400</error-code>
<location>/errorPage.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/errorPage.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errorPage.jsp</location>
</error-page>
我还需要不使用
org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer
。
根据
org.springframework.web.servlet.DispatcherServlet.setThrowExceptionIfNoHandlerFound(boolean)
:“请注意,如果使用 DefaultServletHttpRequestHandler,则请求将始终转发到默认 servlet,并且在这种情况下永远不会抛出 NoHandlerFoundException。”
之前
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.foo.web")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// ...
}
之后
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.foo.web")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
// ...
}
我正在使用 Netbeans 项目。我在 web.xml 中添加了以下几行。只有当我给出 WEB-INF 文件夹的路径时,它才有效,如下所示。
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/view/common/errorPage.jsp</location>
</error-page>
非常简单,
只需在模板文件夹中创建页面,我创建的名称为 error-404.html
然后你将创建一个特定的控制器来处理错误,这是我认为最好的方法
package com.logan.mvc.controllers;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError() {
return "error-404";
}
}