spring-mvc - Spring 错误响应从 JSON 自动转换为 Html
问题描述
当我最终运行项目时,我得到了正确的错误响应。
{
"timestamp": "2018-05-30T10:16:00.065+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No login found for username :string",
"path": "/gatepass/api/v1/logins/login"
}
但是当我在服务器上部署时它会自动转换为 HTML。如何解决这个问题?
<!doctype html>
<html lang="en">
<head>
<title>HTTP Status 500 – Internal Server Error</title>
<style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style>
</head>
<body>
<h1>HTTP Status 500 – Internal Server Error</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Message</b> No login found for username :string</p>
<p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p>
<hr class="line" />
<h3>Apache Tomcat/8.5.27</h3>
</body>
</html>
解决方案
我认为这可能会有所帮助,
@RequestMapping(value = "/userAuthenticationDemo",method = RequestMethod.GET , produces="application/json")
public ResponseEntity<?> userAuthenticationDemo(@RequestParam("username") String username, @RequestParam("password") String password, ) {
System.out.println("Authentication hit");
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);
JSONObject authRespObj = gstcService.userAuthenticationForPostalAppChecking(json);
if(authRespObj != null){
authRespObj.put("isErrorFlag", false);
return new ResponseEntity<>(authRespObj, new HttpHeaders(), HttpStatus.OK);
}else{
throw new UserException("_USER_AUTHENTICATION_FAILED");
}
}
这里对于我们需要使用的 JSON 数据响应produces="application/json"
。最好使用 Response Entity 而不是 @ResponseBody 。注意是特殊的,但是响应实体可以携带带有 Http 状态码的响应。
如果有帮助请推广。
推荐阅读
- docker - 在 docker 上测试没有启动服务的 kafka 消费者
- angularjs - 使用 angularjs 承诺添加两个随机数。程序未运行
- c - 如何在 proc/pid 中创建文件夹
- swift - CKSubscription(recordType:, predicate:, option:) 在 Swift 4.2 中缺失
- linux - Keep first duplicate and replace the rest with blank cell using Awk
- prolog - SWI-Prolog 检查不同列表中的两个元素是否在同一位置
- error-handling - 如何使一长串链式 as_ref().unwrap() 更有意义?
- android - LiveData Observer 没有被调用
- javascript - 在另一个 HTML 文件中使用文本
- visual-studio - 让视觉工作室“观看”一个 dist 文件夹