ResponseEntity,如何获取html中的body [英] ResponseEntity, how to obtain the body in html

查看:38
本文介绍了ResponseEntity,如何获取html中的body的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to show in browser the body of a ResponseEntity returned by a Controller (using Spring):

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

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

l.getReachableDate() returns a Date type, and I want to show it in a way like:

<header>
    <h1><span>Url is not reachable from</span> <!-- body --> </h1>
</header>

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

How can I get it shown?

推荐答案

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

I still not understand why you want to do this, but this way it should work

@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);
}

<小时>

经过一些评论....


after some comments....

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

Instead of redirecting the user to an resource not found page, it would been better to have an ResourceNotFoundRuntimeException (extends RuntimeException) and register an MVC exception handler (that is what prem kumar suggested, but wihtout the customized exception html text):

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);
    }
}

这篇关于ResponseEntity,如何获取html中的body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆