我想在浏览器中显示由Controller返回的ResponseEntity的主体(使用Spring):return new ResponseEntity<>(l.getReachableDate(), HttpStatus.NOT_FOUND);
l.getReachableDate()
返回日期类型,我想以如下方式显示它:
<header>
<h1><span>Url is not reachable from</span> <!-- body --> </h1>
</header>
如何显示它?
最佳答案
我仍然不明白您为什么要这样做,但是这样就可以了
@RequestMapping(value="/controller", method=GET)
public ResponseEntity<String> foo() {
String content =
"<header>"
+ "<h1><span>Url is not reachable from</span>" + l.getReachableDate() + "</h1>"
+ "</header>";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_HTML);
return new ResponseEntity<String>(content, responseHeaders, HttpStatus.NOT_FOUND);
}
经过一番评论...
与其将用户重定向到未找到资源的页面,还不如拥有一个
ResourceNotFoundRuntimeException
(扩展RuntimeException)并注册一个MVC异常处理程序(这是prem kumar所建议的,但是没有定制的异常html文本):public class ResourceNotFoundRuntimeException extends RuntimeException{
...
}
处理程序:
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(ResourceNotFoundRuntimeException .class)
public ResponseEntity<String> resourceNotFoundRuntimeExceptionHandling(){
String content =
"<header>"
+ "<h1><span>Url is not reachable from</span>" + l.getReachableDate() + "</h1>"
+ "</header>";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_HTML);
return new ResponseEntity<String>(content, responseHeaders, HttpStatus.NOT_FOUND);
}
}
关于javascript - ResponseEntity,如何在HTML中获取正文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34691579/