Spring MVC:如何返回自定义404 errorpages?

时间:2014-01-11 11:23:53

标签: java spring spring-mvc

我正在寻找一种干净的方法,在找不到请求的资源时,在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 { }

然后使用异常处理程序呈现自定义errorpage(可能包含指向米列表的链接或适当的任何内容)。

但我不喜欢用很少的例外来污染我的应用程序。

另一种可能性是使用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行(比如编辑,删除)。

是否有一种优雅的方法可以防止多次重复这些行?

8 个答案:

答案 0 :(得分:35)

解决方案比想象的要简单得多。可以使用如下定义的一个通用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

答案 1 :(得分:18)

修改了 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>

答案 2 :(得分:11)

您可以在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>

现在,您可以创建一个控制器来映射发现任何这些错误时被点击的网址。

@Controller
public class HTTPErrorHandler{

    String path = "/error";

    @RequestMapping(value="/404")
    public String error404(){
       // DO stuff here 
        return path+"/404";
    }
    }

有关完整示例,请参阅my tutorial about this

答案 3 :(得分:4)

您应该按照本文了解有关Spring MVC项目中异常处理的详细信息。

spring-mvc-exception-handling

在这种情况下,

@ControllerAdvice可以帮助你

答案 4 :(得分:4)

我们可以在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>

答案 5 :(得分:4)

100%免费xml的简单回答:

  1. 设置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();
    }
    

    }

  2. 创建@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";
    
    }
    

    }

  3. 使用任何内容创建404.jsp页面

  4. 就是这样。

答案 6 :(得分:1)

我还需要不使用org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer

根据org.springframework.web.servlet.DispatcherServlet.setThrowExceptionIfNoHandlerFound(boolean):“请注意,如果使用DefaultServletHttpRequestHandler,那么请求将始终转发到默认的servlet,并且在这种情况下永远不会抛出NoHandlerFoundException。”

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html#setThrowExceptionIfNoHandlerFound-boolean-

<强>之前

@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) {
  }

  // ...
}

答案 7 :(得分:0)

我正在处理一个Netbeans项目,我在web.xml中添加了以下几行,仅当我从WEB-INF文件夹中给出路径时才起作用。

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/view/common/errorPage.jsp</location>
    </error-page>