首页 > 解决方案 > 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>

标签: spring-mvcspring-boot

解决方案


我认为这可能会有所帮助,

@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 状态码的响应。

如果有帮助请推广。


推荐阅读