一. RestFul WebService的创建:
本例使用SpringMVC来写RestFul Web Service。
1.创建【Dynamic Web Prject】
2.添加代码:
RestFul.java:
package com.webservice;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
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.RequestParam;
@Controller
@RequestMapping(value = "/getData")
public class RestFul {
// http://localhost:8080/RestWebService/getData?userName=sun 方式的调用
@RequestMapping
public void printData1(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="userName", defaultValue="User") String name) {
String msg = "Welcome "+ name;
printData(response, msg);
}
// http://localhost:8080/RestWebService/getData/Sun/Royi 方式的调用
@RequestMapping(value = "/{firstName}/{lastName}")
public void printData2(HttpServletRequest request, HttpServletResponse response,
@PathVariable String firstName, @PathVariable String lastName) {
String msg = "Welcome "+ firstName + " " + lastName;
printData(response, msg);
}
// 转换成HTML形式返回
private void printData(HttpServletResponse response, String msg) {
try {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.println(msg);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// http://localhost:8080/RestWebService/getData/json?item=0 方式的调用
@RequestMapping(value = "/json")
public void printData3(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="item", defaultValue="0") String item) {
printDataJason(response, item);
}
// http://localhost:8080/RestWebService/getData/json/1 方式的调用
@RequestMapping(value = "/json/{item}")
public void printData4(HttpServletRequest request, HttpServletResponse response,
@PathVariable String item) {
printDataJason(response, item);
}
// JSON格式化
private void printDataJason(HttpServletResponse response, String item) {
try {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
List uiList = new ArrayList();
for (int i=0; i<3; i++)
{
UserInfo ui = new UserInfo();
ui.ID = i;
ui.Name = "SUN" + i;
ui.Position = "Position" + i;
uiList.add(ui);
if (!item.equals("0")){
JSONArray jsonArr = JSONArray.fromObject(uiList.get(0));
out.println(jsonArr);
}
else{
JSONArray jsonArr = JSONArray.fromObject(uiList);
out.println(jsonArr);
//out.println(uiList);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.webservice;
public class UserInfo{
Integer ID;
String Name;
String Position;
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPosition() {
return Position;
}
public void setPosition(String position) {
Position = position;
}
}
RestWebService
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/springmvc-servlet.xml
2
springMVC
/
springmvc-servlet.xml:
text/plain;charset=UTF-8
rest-servlet.xml
commons-beanutils-1.8.0.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
commons-logging-1.1.3.jar
ezmorph-1.0.6.jar
jackson-all-1.9.0.jar
jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-core-asl-1.7.1.jar
jackson-core-asl-1.8.8.jar
jackson-databind-2.2.1.jar
jackson-jaxrs-1.7.1.jar
jackson-mapper-asl-1.7.1.jar
jackson-mapper-asl-1.8.8.jar
jackson-module-jaxb-annotations-2.2.1.jar
json-lib-2.4-jdk15.jar
jstl-1.2.jar
servlet-api-2.5.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-jdbc-3.2.4.RELEASE.jar
spring-orm-3.2.4.RELEASE.jar
spring-test-3.2.4.RELEASE.jar
spring-tx-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar
spring-webmvc-3.2.4.RELEASE.jar
(部署方法略)
二. RestFul WebService的调用:
方法1:用HttpClient调用:
1.创建【Java Project】:
Rest.java:
package com.httpclientforrest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Rest{
public static void main(String[] args){
List params = new ArrayList();
params.add(new BasicNameValuePair("userName", "Sun"));
String url = "http://localhost:8080/RestWebService/getData";
System.out.println(getRest(url, params));
}
public static String getRest(String url,List params){
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
UrlEncodedFormEntity uefEntity;
try{
uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String json= EntityUtils.toString(entity, "UTF-8");
int code= response.getStatusLine().getStatusCode();
if(code==200 ||code ==204){
return json;
}
}catch (Exception e){
e.printStackTrace();
}
return "";
}
}
Welcome Sun
方法2:在JSP页面用JQuery调用:
1.创建【Dynamic Web Prject】
相关配置文件和创建RestFulWebService相同。
2.建一个JSP页面:
rest.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Restfil WebService
Welcome Sun
PrintDataWithParam:
Welcome Sun Royi
json:
[object Object],[object Object],[object Object]
Changed:
ID:0
Name:SUN0
position:Position0
-------------------------------
ID:1
Name:SUN1
position:Position1
-------------------------------
ID:2
Name:SUN2
position:Position2
-------------------------------
JsonWithParam:
[{"ID":0,"name":"SUN0","position":"Position0"}]
相关文章:
WSDL WebService和RestFul WebService的个人理解:
http://blog.csdn.net/sunroyi666/article/details/51939802
http://blog.csdn.net/sunroyi666/article/details/51917991