2012-10-01 38 views
1

嗨,這是不好的設計?如果一切按計劃進行,我想要返回配置文件。如果沒有,我想返回我的自定義錯誤消息。錯誤的設計讓控制器返回一個對象?

可以嗎?

@RequestMapping(value = "/{userId}", method = RequestMethod.PUT) 
public @ResponseBody 
Object saveUser(@PathVariable Long userId, ModelMap data, @Valid Profile profile, BindingResult bindingResult, HttpServletResponse response) { 

    if (bindingResult.hasErrors()) { 
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 
     return ValidationUtil.createValidationErrors(bindingResult); 
    } 
    profileService.save(profile); 
    return profile; 
} 

回答

0

如果您需要訪問配置文件對象,我建議您將它添加到會話或請求上下文中。然後,您可以從saveUser方法(或者ModelAndView對象,如果您願意的話)返回一個字符串,並且仍然可以將該對象用於以後的請求。

+0

我只需要返回一個json對象。我不需要配置文件。 – pethel

+0

再次,您可以將JSON對象放入請求(或模型)或會話中,然後返回一個字符串。 – TrueDub

+0

我只是在實現一個API。如果我使用jsps創建前端,該模型是否可用? – pethel

1

您應該使用@ExceptionHandler(Exception.class)和@ResponseStatus註釋

@ExceptionHandler (Exception.class) 
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT) 
public @ResponseBody 
Profile saveUser(@PathVariable Long userId, ModelMap data, @Valid Profile profile, BindingResult bindingResult, HttpServletResponse response) { 

    if (bindingResult.hasErrors()) { 
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 
     throw new Exception("message"); 
     if(ValidationUtil.createValidationErrors(bindingResult)) { 
      throw new Exception("message"); 
     } 
    } 
    profileService.save(profile); 
    return profile; 
} 

欲瞭解更多詳情,請參閱

http://jnb.ociweb.com/jnb/jnbNov2010.html

http://www.stormpath.com/blog/spring-mvc-rest-exception-handling-best-practices-part-1

http://blog.cuttleworks.com/2011/12/spring-restful-controllers-and-error-handling/

+0

我沒有實現前端。訪問我的API的人是否仍然使用該模型? – pethel

+0

這是否是一個RESTful的Web服務?或其他一些服務API? –

+0

這是一個安靜的API – pethel

相關問題