2014-10-01 304 views
23

我想有一個@RestController這需要一個@PathVariable返回一個特定的對象JSON格式,在適當的狀態代碼一起。到目前爲止,代碼的方式,它將返回JSON格式的對象,因爲它默認使用內置於Jackson庫中的Spring 4。如何在Spring MVC @RestController中響應HTTP狀態碼@ResponseBody類返回一個對象?

但是我不知道如何使它所以它會給我們說希望有一個API變量,然後JSON數據的消息給用戶,那麼出錯代碼(或取決於如果一切順利成功代碼)。例如輸出爲:

請輸入API值作爲參數(注:這可能是JSON,以及如果需要的話)

{ 「ID」:2, 「API」: 「3000105000」 ...... }(注:這將是JSON響應對象)

狀態代碼400(或專有狀態碼)


與參數中的URL看起來像這樣

http://localhost:8080/gotech/api/v1/api/3000105000 

的代碼,我到目前爲止有:

@RestController 
@RequestMapping(value = "/api/v1") 
public class ClientFetchWellDataController { 

    @Autowired 
    private OngardWellService ongardWellService; 

    @RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET) 
    @ResponseBody 
    public OngardWell fetchWellData(@PathVariable String apiValue){ 
     try{ 
      OngardWell ongardWell = new OngardWell(); 
      ongardWell = ongardWellService.fetchOneByApi(apiValue); 

      return ongardWell; 
     }catch(Exception ex){ 
      String errorMessage; 
      errorMessage = ex + " <== error"; 
      return null; 
     } 
    } 
} 

回答

47

一個@RestController不適合這個。如果您需要返回不同類型的響應,請使用ResponseEntity<?>,您可以在其中明確設置狀態碼。

ResponseEntitybody將以與任何@ResponseBody帶註釋的方法的返回值相同的方式處理。

@RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET) 
public ResponseEntity<?> fetchWellData(@PathVariable String apiValue){ 
    try{ 
     OngardWell ongardWell = new OngardWell(); 
     ongardWell = ongardWellService.fetchOneByApi(apiValue); 

     return new ResponseEntity<>(ongardWell, HttpStatus.OK); 
    }catch(Exception ex){ 
     String errorMessage; 
     errorMessage = ex + " <== error"; 
     return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); 
    } 
} 

注意,你不需要@ResponseBody@RestController註解類中的一個@RequestMapping方法。

26

的慣用方法是使用異常處理程序,而不是在你的正常請求處理方法捕捉異常的。異常的類型決定了響應代碼。 (403爲安全錯誤,500爲意外的平臺異常,無論你喜歡什麼)

@ExceptionHandler(MyApplicationException.class) 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
public String handleAppException(MyApplicationException ex) { 
    return ex.getMessage(); 
} 

@ExceptionHandler(Exception.class) 
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
public String handleAppException(Exception ex) { 
    return ex.getMessage(); 
} 
+0

mmmmm還挺有意義的,那麼我現有的代碼在哪裏呢?或者是你發佈了自己的代碼,我會打電話來處理我的異常?對不起,我從來沒有見過這樣的代碼,看起來非常有用,儘管如此感謝您的幫助 – Cris 2014-10-01 05:13:37

+1

它與您的代碼位於同一控制器中。只需將try-catch從處理程序方法中取出即可。 – Affe 2014-10-01 05:29:55

+0

這是寫作RestAPIs我認爲非常有用和更好的方式。 如果我有多個控制器,是否必須爲所有控制器編寫這些處理程序,或者我可以將這些處理程序放入基類還是接口中並使用它? – shraddha 2017-11-07 00:50:54

相關問題