2012-10-01 36 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

相关问题