ResponseEntity,如何获取html中的body

San*_*Gil 2 html javascript spring response web

我想在浏览器中显示控制器返回的 ResponseEntity 的主体(使用 Spring):

return new ResponseEntity<>(l.getReachableDate(), HttpStatus.NOT_FOUND);

l.getReachableDate()返回一个 Date 类型,我想以如下方式显示它:

<header>
    <h1><span>Url is not reachable from</span> <!-- body --> </h1>
</header>
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它显示出来?

Ral*_*lph 5

我仍然不明白你为什么要这样做,但这样应该可以工作

@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);
}
Run Code Online (Sandbox Code Playgroud)

经过一些评论......

与其将用户重定向到资源未找到页面,不如拥有一个ResourceNotFoundRuntimeException(extends RuntimeException) 并注册一个 MVC 异常处理程序(这就是prem kumar 的建议,但没有自定义的异常 html 文本):

public class ResourceNotFoundRuntimeException extends RuntimeException{
...
}
Run Code Online (Sandbox Code Playgroud)

处理程序:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)