2013-04-23 66 views
1

我有以下REST服务建立在Spring周围。我想实现一个可以添加用户的POST方法。用户的数据位于请求正文中,可以使用JSON/XML。我想服务器端实现春天绑定一个bean来休息post请求

  1. 使用单一的实现输入的数据自动映射到Java bean的
  2. 和处理这两种类型的数据(JSON/XML)。

我已经在UserControlleraddUser@ModelAttribute尝试,但得到的user对象空各个领域。任何线索?

下面是Spring配置文件

<mvc:annotation-driven /> 

<context:component-scan base-package="com.rest.sg.controller" /> 

<bean 
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 
    <property name="order" value="1" /> 
    <property name="mediaTypes"> 
     <map> 
      <entry key="json" value="application/json" /> 
      <entry key="xml" value="application/xml" /> 
     </map> 
    </property> 

    <property name="defaultViews"> 
     <list> 
      <!-- JSON View --> 
      <bean 
       class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> 
      </bean> 
      <!-- XML view --> 
      <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> 
       <constructor-arg> 
        <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> 
         <property name="classesToBeBound"> 
          <list> 
           <value>com.rest.sg.bean.User</value> 
          </list> 
         </property> 
        </bean> 
       </constructor-arg> 
      </bean> 
     </list> 
    </property> 
    <property name="ignoreAcceptHeader" value="true" /> 

</bean> 

UserController类和ADDUSER方法

@Controller 
public class UserController { 

    @RequestMapping(method=RequestMethod.POST, value="/user") 
    @ResponseBody 
    public User addUser(@ModelAttribute("user") User user) { 
     userService.addUser(user); 
     return user; 
    } 

} 

和用户的Bean

@Entity 
@XmlRootElement 
@Table(name = "user", catalog = "blahblah") 
public class User implements java.io.Serializable { 

    // Fields 
    // Getter , Setters 
    ... 

} 

回答

1

你的控制器需要知道如何将数据映射。缺省值是映射对象属性的请求参数。

如果您发送的JSON表示User对象,你可以尝试

public User addUser(@RequestBody User user) { 
+0

如果我使用'code' @ RequestBody,我在客户端收到'code'HTTP状态415。错误描述是'code'服务器拒绝了这个请求,因为请求实体的格式不是所请求方法()的请求资源所支持的格式。 – 2013-04-24 05:57:30

+0

您的请求是否具有内容类型'application/json'(或'application/xml')?你有没有把杰克逊包括在你的类路径中(如果你的请求是JSON)? – zeroflagL 2013-04-24 07:52:38

+0

是的,我把杰克逊列入了课程路径。我试图用这两种类型,即JSON/XML,因为我想单一的方法来处理这两种数据类型(在我的问题中的第2点) – 2013-04-25 13:23:08

0

这样做:

@RequestMapping(value="/persons", method = RequestMethod.POST, 
       headers="Accept=*/*", 
       consumes="application/json") 
public User addUser(@RequestBody User u){ 
       //Code. 
} 

当发送请求,发送标题

Content-Type:application/json //This is important 
Accept: application/json 
+0

其实我想要这个方法来处理这两种数据类型,即XML/JSON(在我的问题中的第2点)。我认为这是可能的,但如何? – 2013-04-25 13:24:20

+0

你需要'ContentNegotiatingViewResolver' http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html – 2013-04-25 15:31:22

+0

我想我已经使用'ContentNegotiationViewResolver'但无法正常工作 – 2013-04-26 07:25:43