[英]How to set ResponseEntity to HTTP 404 for Spring MVC 4
我正在使用 Java 1.7 和 Spring 4 MVC 創建一個 Rest Controller,但如果我的 dao 返回一個空結果,則需要它返回一個 HTTP 404 ResponseEntity。
pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
休息控制器:
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderDao dao;
private HttpHeaders headers = null;
@Autowired
public OrderController(OrderDAO dao) {
this.dao = dao;
headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
}
@RequestMapping(value = "{orderId}/{productId}", method = RequestMethod.GET, produces = "APPLICATION/JSON")
public ResponseEntity<Object> getOrderDetails(@PathVariable("orderId") String orderId,
@PathVariable("productId") String productId) {
return new ResponseEntity<Object>(dao.getOrderDetails(orderId,productId), headers, HttpStatus.OK);
}
}
如何設置以便如果 dao.getOrderDetails(orderId,productId) 為空,它應該為訪問此 Rest Call 的客戶端程序返回 HTTP 404?
試過這個:
ResponseEntity<Object> response = new ResponseEntity<Object>(dao.getOrderDetails(orderId,productId), headers, HttpStatus.OK);
if (response == null) {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
return response;
但是 Eclipse 說這個 if 子句是“死代碼”......
是死代碼,因為response
變量永遠不會為null
。 試試這個:
Object data = dao.getMlsPlayerSeasonStats(profileId,sportsTeamId);// I don´t know the DAO operation return type
if (data == null) {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Object>(data, headers, HttpStatus.OK);;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.