@ExceptionHandler方法不重定向返回视图

时间:2016-08-31 11:44:40

标签: spring spring-mvc controller hybris


我在@ControllerAdvice中遇到@ExceptionHandler方法的问题 发生异常时调用我的方法,但从不重定向到通过此方法返回的站点。我试图返回ModelANdView,RedirectView或String,但它永远不会正常工作 这是我的方法的实际代码:

public static final String REFERER_HEADER = "Referer";
public static final String REDIRECT = "redirect:";    

@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public RedirectView maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e,
                                                          HttpServletRequest request,HttpServletResponse response) {

    String sourcePage = request.getHeader(REFERER_HEADER);
    RedirectView rw = new RedirectView(REDIRECT + sourcePage);
    return rw;
}

但正如我所说,不重定向正确。在浏览器中,当发生异常时,我会留在页面上

1 个答案:

答案 0 :(得分:0)

你可以试试其中任何一个......

public static final String REFERER_HEADER = "Referer";
public static final String FORWARD_PREFIX = "forward:";    

@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public String maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e,
                                                      HttpServletRequest request,HttpServletResponse response) {

  String sourcePage = request.getHeader(REFERER_HEADER); // Assuming you have sourcePage eg : "/pageURL"
  return FORWARD_PREFIX + sourcePage;
}

OR

public static final String REFERER_HEADER = "Referer";

@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public ModelAndView maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e,
                                                  HttpServletRequest request,HttpServletResponse response) {

  String sourcePage = request.getHeader(REFERER_HEADER);
  final RedirectView rv = new RedirectView(sourcePage);
  rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
  rv.setUrl(sourcePage);
  final ModelAndView mv = new ModelAndView(rv);
  return mv;
}

但我不确定......