1.项目所需JAR包,我是用Maven管理项目的,直接贴出依赖
<!-- CXF发布RESTful Web服务依赖包 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.7.11</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- JSON序列化和反序列化需要用到的依赖包 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 为了测试@Context注解而引入的Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
2.例子中用到的Department实体
package cn.cjc.domain;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Department {
private int deptId;
private String deptName;
private String deptLocation;
public Department() {
}
public Department(int deptId, String deptName, String deptLocation) {
this.deptId = deptId;
this.deptName = deptName;
this.deptLocation = deptLocation;
}
// 省略Getter和Setter
}
3.接口
package cn.cjc.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import cn.cjc.domain.Department;
@Path("/dept")
public interface IDepartmentService {
@GET
@Path("/test_path_param/{deptId}")
@Produces(MediaType.APPLICATION_JSON)//表示产生JSON格式的字符串输出
Department findByDeptId(@PathParam("deptId") int deptId);// 方法一:PathParam路径参数
@GET
@Path("/test_query_param")
@Produces(MediaType.APPLICATION_XML)//表示产生XML格式的字符串输出(默认输出格式)
Department findByDeptName(@QueryParam("deptName") String deptName);// 方法二:QueryParam查询参数
@POST
@Path("/test_form_param")
@Produces(MediaType.TEXT_PLAIN)
String findByDeptLocation(@FormParam("deptLocation") String deptLocation);// 方法三:FormParam表单参数
@POST
@Path("/push")
@Produces(MediaType.APPLICATION_JSON)//生产JSON字符串,不配置的话默认产生XML字符串
@Consumes(MediaType.APPLICATION_XML)//消费XML字符串,不配置的话默认只能接收XML字符串
Department pushDept(Department dept);// 方法四
@GET
@Path("/test_context")
String testContext(@Context HttpServletRequest request, @Context HttpServletResponse response);// 方法五:@Context注解能直接拦截到Request、Response等域对象
}
4.实现类
package cn.cjc.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.cjc.domain.Department;
public class DepartmentServiceImpl implements IDepartmentService {
@Override
public Department findByDeptId(int deptId) {
Department dept = new Department(deptId, "眼科", "二楼西南角");
return dept;
}
@Override
public Department findByDeptName(String deptName) {
Department dept = new Department(67000076, deptName, "四楼正南");
return dept;
}
@Override
public String findByDeptLocation(String deptLocation) {
return "对不起,您要查找的位置" + deptLocation + "无科室!";
}
@Override
public Department pushDept(Department dept) {
dept.setDeptName(dept.getDeptName() + "服务器返回的");
dept.setDeptLocation(dept.getDeptLocation() + "服务器返回的");
return dept;
}
@Override
public String testContext(HttpServletRequest request, HttpServletResponse response) {
return "request.getContextPath()=" + request.getContextPath() + "\nresponse.getCharacterEncoding()=" + response.getCharacterEncoding();
}
}
5.Spring配置文件beans.xml
<!-- 在原有的Spring配置文件内引入CXF的jaxrs命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<!-- 引入CXF默认配置文件 -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<bean id="departmentService" class="cn.cjc.service.DepartmentServiceImpl"/>
<!-- 发布RESTful WS服务 -->
<jaxrs:server address="/">
<jaxrs:serviceBeans>
<ref bean="departmentService" />
</jaxrs:serviceBeans>
<!-- 序列化和反序列化JSON -->
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
<!-- <jaxrs:extensionMappings>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="feed" value="application/atom+xml"/>
</jaxrs:extensionMappings> -->
</jaxrs:server>
</beans>
6.web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CXF相关配置 -->
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
7.启动WEB服务器即发布WS服务,为了测试调用,我用到了org.apache.commons.httpclient.HttpClient来模拟HTTP的GET和POST请求,引入此工具类需要配置以下Maven依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
下面从方法一~方法五依次测试
1)方法一测试
public static void main(String[] args) throws Exception {
GetMethod get = new GetMethod("http://localhost:8082/cxfspring/rest/dept/test_path_param/200836");
get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
try {
HttpClient client = new HttpClient();
client.executeMethod(get);
String result = get.getResponseBodyAsString();
System.out.println(result);
} finally {
get.releaseConnection();
}
}
输出结果:{"deptId":200836,"deptName":"眼科","deptLocation":"二楼西南角"}
2)方法二测试
public static void main(String[] args) throws Exception {
String deptName = URLEncoder.encode("耳鼻喉科", "utf-8");
GetMethod get = new GetMethod("http://localhost:8082/cxfspring/rest/dept/test_query_param?deptName=" + deptName);
get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
try {
HttpClient client = new HttpClient();
client.executeMethod(get);
String result = get.getResponseBodyAsString();
System.out.println(result);
} finally {
get.releaseConnection();
}
}
输出结果:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><department><deptId>67000076</deptId><deptName>耳鼻喉科</deptName><deptLocation>四楼正南</deptLocation></department>
3)方法三测试
public static void main(String[] args) throws Exception {
PostMethod post = new PostMethod("http://localhost:8082/cxfspring/rest/dept/test_form_param");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
post.setParameter("deptLocation", "一楼左转方向");
try {
HttpClient client = new HttpClient();
client.executeMethod(post);
String result = post.getResponseBodyAsString();
System.out.println(result);
} finally {
post.releaseConnection();
}
}
输出结果:对不起,您要查找的位置一楼左转方向无科室!
4)方法四测试
public static void main(String[] args) throws Exception {
PostMethod post = new PostMethod("http://localhost:8082/cxfspring/rest/dept/push");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
String requestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><department><deptId>5156523</deptId><deptName>胸科</deptName><deptLocation>三楼东北角</deptLocation></department>";
RequestEntity requestEntity = new StringRequestEntity(requestXml, "application/xml", "utf-8");
post.setRequestEntity(requestEntity);
try {
HttpClient client = new HttpClient();
client.executeMethod(post);
String result = post.getResponseBodyAsString();
System.out.println(result);
} finally {
post.releaseConnection();
}
}
输出结果:{"deptId":5156523,"deptName":"胸科服务器返回的","deptLocation":"三楼东北角服务器返回的"}
5)方法五测试
public static void main(String[] args) throws Exception {
GetMethod get = new GetMethod("http://localhost:8082/cxfspring/rest/dept/test_context");
try {
HttpClient client = new HttpClient();
client.executeMethod(get);
String result = get.getResponseBodyAsString();
System.out.println(result);
} finally {
get.releaseConnection();
}
}
输出结果:
request.getContextPath()=/cxfspring
response.getCharacterEncoding()=ISO-8859-1