项目中要用到Rest的web service,提前做了一个Demo,做下笔记。
Demo 分2个项目,一个是restServer 一个是restClient, 都是Spring MVC架构。主要看代码:
Pojos:
package com.pojo; import java.io.Serializable; public class Phone implements Serializable{ private static final long serialVersionUID = 1L; private String phoneNumber="1"; private String phoneType="1"; public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneType() { return phoneType; } public void setPhoneType(String phoneType) { this.phoneType = phoneType; } }
package com.pojo; import java.io.Serializable; public class PhoneResult implements Serializable { private static final long serialVersionUID = 1L; protected String rawPhoneNumber; protected String result; public String getRawPhoneNumber() { return rawPhoneNumber; } public void setRawPhoneNumber(String rawPhoneNumber) { this.rawPhoneNumber = rawPhoneNumber; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
restServer controller:
package com.acxiom.rest.controller; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.pojo.Phone; import com.pojo.PhoneResult; @Controller @RequestMapping({ "/helloworld" }) public class HelloWorldController { @RequestMapping(value = { "/hi/{userName}" }, method = {RequestMethod.GET }) @ResponseBody public String hi(@PathVariable("userName") String userName) { return "Hi, " + userName; } @RequestMapping(value = { "/hello" }, method = {RequestMethod.GET }) @ResponseBody public String process(String userName) { return "Hello, " + userName; } @RequestMapping(value = { "/hiPost/{userName}" }, method = {RequestMethod.POST }) @ResponseBody public String hiPost(@PathVariable("userName") String userName) { return "Hi, " + userName; } @RequestMapping(value = { "/hello" }, method = {RequestMethod.POST }) @ResponseBody public String helloPost(String userName) { return "Hello, " + userName; } @RequestMapping(value = { "/hygiene/{phone}" }, method = {RequestMethod.POST },produces="application/json") @ResponseBody public PhoneResult hygiene(@PathVariable("phone")String phoneObject) { PhoneResult result = new PhoneResult(); try { ObjectMapper mapper = new ObjectMapper(); Phone phone = mapper.readValue(phoneObject, Phone[].class)[0]; result.setRawPhoneNumber(phone.getPhoneNumber().toUpperCase()); result.setResult("SUCCESS"); }catch (Exception e) { e.printStackTrace(); result.setResult("ERROR, " + e.getMessage()); } return result; } }
restClient controller:
package com.acxiom.rest.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import com.pojo.Phone; import com.pojo.PhoneResult; import com.util.JsonUtil; @Controller public class HomeController { @Autowired private RestTemplate restTemplate; @RequestMapping(value = { "/home" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }) public String home(ModelMap model) throws Exception { //test get hi method 1 String url = "http://localhost:8080/restServer/helloworld/hi/{userName}.spring"; Map<String, String> map = new HashMap<String, String>(); map.put("userName", "TOMMY"); model.addAttribute("HiResponse", getResponseMessage(url, map)); //test get hi method 2 model.addAttribute("HiResponse2", this.restTemplate.getForEntity(url, String.class, "TOMMY2").getBody()); //test get hello method url = "http://localhost:8080/restServer/helloworld/hello.spring?userName=seaboy"; model.addAttribute("HelloResponse", getResponseMessage(url, null)); //test post hello method model.addAttribute("HelloPostResponse", this.restTemplate.postForEntity("http://localhost:8080/restServer/helloworld/hello.spring?userName=seaboyPost", null, String.class).getBody()); //test post hygiene method MultiValueMap<String,Object> dataMap2 = new LinkedMultiValueMap<String, Object>(); Phone p = new Phone(); p.setPhoneNumber("0513 1111"); dataMap2.add("phone", JsonUtil.javaToJson(p)); HttpEntity<Object> entity2 = new HttpEntity<Object>(dataMap2); model.addAttribute("PhoneResponse", this.restTemplate.postForObject("http://localhost:8080/restServer/helloworld/hygiene/{phone}.spring", entity2, PhoneResult.class, dataMap2)); return "home"; } private String getResponseMessage(String url, Map<String, String> paras) { if (paras != null) { return this.restTemplate.getForEntity(url, String.class, paras).getBody(); } else { return this.restTemplate.getForEntity(url, String.class).getBody(); } } }
JsonUtil:
package com.util; import java.io.StringWriter; import org.codehaus.jackson.map.ObjectMapper; public class JsonUtil { public static String javaToJson(Object o) throws Exception{ StringWriter writer = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, o); String json=writer.toString(); return json; } }
home.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>HOME PAGE</title> </head> <body> <div id="main"> <div id="top"> Hi Response: ${HiResponse} <br> Hi2 Response: ${HiResponse2} </div> <div id="buttom"> Hello Response: ${HelloResponse} <br> Hello Post Response: ${HelloPostResponse}<br> Phone Response: ${PhoneResponse.result} </div> </div> </body> </html>
测试结果:
Hi Response: Hi, TOMMY Hi2 Response: Hi, TOMMY2 Hello Response: Hello, seaboy Hello Post Response: Hello, seaboyPost Phone Response: 86 0513 11112222