|  | 本文参考《精通Spring:JavaWeb开发技术详解》,作者:孙卫琴,清华大学出版社出版 
 在实际软件开发过程中,前端与后端的开发团队分别开发各自的软件模块。对于采用RESTFul风格的Web应用,如果要等到前端与后端均开发完成自己的模块后,才能整体调试和运行程序,这会大大影响软件开发的效率。
 
 Spring API提供了一个org.springframework.web.client.RestTemplate类,它支持在服务器端单独测试负责处理RESTFul风格的HTTP请求的控制器类。
 
 RestTemplate类提供了一些方法,模拟客户端发出RESTFul风格的HTTP请求:
 (1)新增操作:postForEntity(String url,Object request, Class<T> responseType, Object... uriVariables)
 (2)更新操作:put(String url, Object request,Object... uriVariables)
 (3)删除操作:delete(String url, Object...uriVariables)
 (4)查询操作:getForObject(String url,Class<T> responseType, Object... uriVariables)
 
 以上postForEntity()、put()、delete()和getForObject()方法分别采用POST、PUT、DELETE和GET请求方式,请求服务器端执行新增、更新、删除和查询操作。以上方法的url参数指定请求访问的URL,request参数表示请求正文数据,responseType参数指定返回数据的类型,uriVariables参数设定URL变量。
 
 以下例程1的TestController类通过RestTemplate类来访问CustomerController类的各种请求处理方法。
 
 例程1 TestController.java
 | @Controller public class TestController {
 @Autowired
 private RestTemplate restTemplate;
 private String SERVICE_URL =  "http://localhost:8080/helloapp/customer";
 
 @RequestMapping("/insert")
 publicString insert() {
 Customercustomer=new Customer();
 customer.setId(null);
 customer.setName("Linda");
 customer.setAge(18);
 
 // 发送POST请求
 StringResult result=restTemplate.postForObject(
 SERVICE_URL ,customer,StringResult.class);
 
 System.out.println(result);
 return"result";
 }
 
 @RequestMapping("/update")
 publicString update() {
 Customercustomer=new Customer();
 customer.setId(Long.valueOf(1L));
 customer.setName("Linda");
 customer.setAge(18);
 
 // 发送PUT请求
 restTemplate.put(SERVICE_URL+"/1" , customer);
 System.out.println("更新完毕");
 return"result";
 }
 
 @RequestMapping("/delete")
 publicString delete() {
 // 发送DELETE请求
 restTemplate.delete(SERVICE_URL+"/1");
 System.out.println("删除完毕");
 return"result";
 }
 
 @RequestMapping("/findone")
 publicString findById() {
 // 发送GET请求
 Customercustomer=restTemplate.getForObject(SERVICE_URL+"/1",
 Customer.class);
 if(customer!=null)
 System.out.println(customer.getId()+","
 +customer.getName()+","+customer.getAge());
 return"result";
 }
 
 @RequestMapping("/findall")
 publicString findAll() {
 // 发送GET请求
 Customer[] customers=restTemplate
 .getForObject(SERVICE_URL,Customer[].class);
 System.out.println("查询到"+customers.length+"个Customer对象");
 
 for(Customer c : customers)
 System.out.println(c.getId()+","+c.getName()+","+c.getAge());
 
 return"result";
 }
 }
 | 
 TestController类的restTemplate实例变量由Spring框架提供,在Spring的配置文件applicationContext.xml中配置了restTemplate Bean组件:
 
 
 | <bean id="restTemplate" class= "org.springframework.web.client.RestTemplate" />
 | 
 通过浏览器访问以下URL:
 
 http://localhost:8080/helloapp/insert
 http://localhost:8080/helloapp/update
 http://localhost:8080/helloapp/findone
 http://localhost:8080/helloapp/findall
 http://localhost:8080/helloapp/delete
 
 以上URL会访问TestController类的相关方法,而这些方法又会通过RestTemplate类发出RESTFul风格的HTTP请求,请求访问CustomerController类的相关方法。
 
 
 程序猿的技术大观园:www.javathinker.net
 |  |