基于404处理的Spring注释

时间:2015-03-12 10:04:43

标签: java spring spring-mvc spring-security spring-annotations

我想处理任何404例外并将这些请求重定向到我的信息中心。 在基于web.xml的配置中,使用

很容易
<error-page>
    <error-code>404</error-code>
    <location>/weberror.jsp</location>
</error-page>

我目前有一个基于注释的配置,所以我不想那样处理它,我尝试了以下但是没有使用ResourceNotFoundException

@ControllerAdvice
public class GlobalExceptionHandler {

@Autowired private LoginUserService loginUserService;

@ExceptionHandler(Exception.class)
public ModelAndView handleGeneralException(Exception exception) {
    ...
}

@ExceptionHandler(AccessDeniedException.class)
public ModelAndView handleAccessException(AccessDeniedException exception) {
    return new ModelAndView("accessDeniedView");
}

//this isn't working!!! I'd like to handle it my 404 but still my apache 404 page comes up instead
@ExceptionHandler(ResourceNotFoundException.class)
public ModelAndView handleResourceNotFoundException(ResourceNotFoundException exception) {
    return new ModelAndView("dashboardView");
}
}

2 个答案:

答案 0 :(得分:0)

您可以将错误页面替换为错误状态,如下所示:

@ControllerAdvice
class GlobalControllerExceptionHandler {
      @ResponseStatus(HttpStatus.CONFLICT)  //
      @ExceptionHandler(DataIntegrityViolationException.class)
        public void handleConflict() {
                           // Nothing to do
       }
 }

答案 1 :(得分:0)

请查看http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-customer-servlet-container-error-page,您需要一个如下控制器来处理所有此类错误。

@Controller 公共类ErrorController {

@RequestMapping(value="/error", produces="application/json")
@ResponseBody
public Map<String, Object> handle(HttpServletRequest request) {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("status", request.getAttribute("javax.servlet.error.status_code"));
    map.put("reason", request.getAttribute("javax.servlet.error.message"));

    return map;
}

}