gpt4 book ai didi

javascript - ResponseEntity,如何获取html中的body

转载 作者:行者123 更新时间:2023-11-29 18:01:25 30 4
gpt4 key购买 nike

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

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

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

<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中的body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691579/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com