Java 在SpringREST中发送jsp响应和状态代码
我想发送一个jsp错误页面和HTTP状态代码。我尝试了以下代码,但它只显示字符串,而没有显示index.jsp页面:Java 在SpringREST中发送jsp响应和状态代码,java,spring,rest,spring-restcontroller,Java,Spring,Rest,Spring Restcontroller,我想发送一个jsp错误页面和HTTP状态代码。我尝试了以下代码,但它只显示字符串,而没有显示index.jsp页面: @ExceptionHandler(Exception.class) public ResponseEntity handleException(HttpServletRequest req, Exception e) { return new ResponseEntity("index.jsp",HttpStatus.NOT_FOUND); } 有人能解释
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(HttpServletRequest req, Exception e)
{
return new ResponseEntity("index.jsp",HttpStatus.NOT_FOUND);
}
有人能解释一下怎么做吗
编辑:我尝试了modelandview方法,但它显示的状态代码不是404,而是200 OK状态代码。
ResponseEntity
将始终返回一个对象。在您的情况下,字符串
ResponseEntity("index.jsp",HttpStatus.NOT_FOUND);
要加载特定的jsp页面,可以使用ModelAndView
。
您还可以将附加信息传递给ModelView,这很方便
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("url", req.getRequestURL()); // Can read this in JSP by getting url
mav.setViewName("index"); // calls index.jsp
return mav;
}
编辑1:
mav.setStatus(HttpStatus.NOT_FOUND);
如何将状态代码与jsp页面一起发送?我尝试了上面的代码。我得到了jsp页面,但是状态代码是200而不是404。我已经更新了编辑1部分。。。你试过了吗……是的,我试过了……但状态仍然是200 Ok。在这里,状态似乎是modelandview的属性之一,而不是通常的“状态”。。我必须从回复中提取它,因为它不是独立提供的。