at com.jersey.test.RestClient.main(RestClient.java:75)
springMVC controller 如下:
@RequestMapping(value="/static/restful")
@Controller
public class StudentRestfulController {
private IBaseService<Student> studentService;
@RequestMapping(value="/addStudent",method=RequestMethod.POST)
public void addStudent(@RequestBody Student entity){
//this.studentService.save(entity);
System.out.println("firstname :"+entity.getFirstname()+" lastname "+entity.getLastname());
}
@RequestMapping(value="/batchAddStudent",method=RequestMethod.POST)
public void batchAddStudent(@RequestBody List<Student> students){
if(students!=null&&students.size()>0){
for(Student student:students){
this.studentService.save(student);
}
}
}
}
实体:
public class Student {
private String workUnit = null;
private String id = null;
private String loginname = null;
private String password = null;
private String lastname = null;
}
客户端调用代码:
public class RestClient {
private RestTemplate template;
private final static String url = "http://localhost:8080/rdb/static/restful/";
public void addStudent(Student stu){
template=new RestTemplate();
template.postForObject(url+"addStudent.do", stu, String.class);
}
}
解决方法:
一、在实体类中加上@XmlRootElement注解,SpringMVC就可以解析出来了
二、修改客户端中调用的代码
在RestTemplate模板中添加消息转换器,有两种方法
1.直接在代码中添加
public void addStudent(Student stu){
template=new RestTemplate();
List messageConverters=new ArrayList();
messageConverters.add(new SourceHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
template.setMessageConverters(messageConverters);
template.postForObject(url+"addStudent.do", stu, String.class);
}
2.在客户端XML配置文件中添加转换器
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/> <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
测试
public void testRest(Student stu){ BeanFactory bean=new ClassPathXmlApplicationContext("applicationContext.xml"); template=(RestTemplate)bean.getBean("restTemplate"); template.postForObject(url+"addStudent.do", stu, String.class); }