1、使用CXF发布restful服务
RESTful方式,基于http的方式,不是基于soap的方式
2、关于实体类User.java需要加上@XmlRootElement(name="user) //user信息转成xml的标签名称
@XmlRootElement(name = "user")
public class User implements Serializable {
private int id;
private String name;
private int age;
public User() {
}
}
3、 编写Service接口
@WebService(targetNamespace = "http://user.namager.cn", name = "IUserServiceSoap", portName = "IUserServicePort", serviceName = "IUserService")
public interface IUserService {
// 用于分页查询用户,GET方式
// 目标要实现rest风格url:http://localhost:8080/area/parentid/start/end
@GET
// 表示这个方法只允许get请求
@Path("/user/{start}/{end}")
// {}表示一个占位符{}中的parentid就是占位符号的名称,将占位符上的值传给形参
@Produces({ "application/json;charset=utf-8", MediaType.APPLICATION_XML })
// 通过@Produces设置生产内容的格式,json(使用utf-8编码)和xml
// @PathParam("start")从url的占位符中取值设置给形参
public List<User> findUserByStartAndEnd(@PathParam("start") int start,
@PathParam("end") int end);
// 用于分页查询用户,GET方式
// 目标要实现rest风格url:http://localhost:8080/area/parentid/start/end
@POST
// 表示这个方法只允许get请求
@Path("/user")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
// {}表示一个占位符{}中的parentid就是占位符号的名称,将占位符上的值传给形参
@Produces({ "application/json;charset=utf-8", MediaType.APPLICATION_XML })
// 通过@Produces设置生产内容的格式,json(使用utf-8编码)和xml
// @PathParam("start")从url的占位符中取值设置给形参
public User findUserById(@FormParam("id") int id);
}
4、发布服务
1、applicationContext-service.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- dao -->
<bean id="userDaoImpl" class="com.cxfwebservice.daoimpl.UserDaoImpl"></bean>
<!-- service,配置的是portType的实现类 -->
<bean id="userServiceImpl" class="com.cxfwebservice.serviceimpl.UserServiceImpl">
<!-- 注入dao -->
<property name="userDao" ref="userDaoImpl"></property>
</bean>
</beans>
2、applicationContext-cxf.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
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
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<!--在portType的接口上加@WebService注解 -->
<!-- 发布rest风格的web服务 -->
<jaxrs:server address="/rest">
<jaxrs:serviceBeans>
<!-- 配置的是portType的实现类:表示spring容器中portType的实现类这个bean的id -->
<ref bean="userServiceImpl" />
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>
3、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>webservice011_cxf_rest_server0823</display-name>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 注意这里采用通配符配置方式,实际使用注意配置文件地址的正确性 -->
<param-value>/WEB-INF/classes/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置cxf servlet -->
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<!-- 请求以/ws/开头的都cxf解析 -->
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
5、部署项目到tomcat,并访问
1、xml的形式
2、json的形式
6、在客户端利用httpclient访问
1、利用httpclient的get方式访问
public class HttpclientGet {
public static void main(String[] args) throws URISyntaxException {
// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 定义一个uri对象,可以通过uri对象进行get传参
URI uri = new URIBuilder(
"http://localhost:8080/UserCXFSpringRestfulService/ws/rest/user/1/4")
.addParameter("_type", "xml")// 获取xml
// .addParameter("_type", "json")// 获取json
.build();
// 创建httpget请求对象
HttpGet httpGet = new HttpGet(uri);
// 定义一个响应结果对象
CloseableHttpResponse response = null;
try {
// 进行http的get请求,获取响应结果
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {// 响应成功
// 获取响应的结果,进行utf-8编码
String responseString = EntityUtils.toString(
response.getEntity(), "utf-8");
System.out.println(responseString);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、利用httpclient的post方式访问
post的参数是通过表单数据提交
public class HttpclientPost {
public static void main(String[] args) throws URISyntaxException,
UnsupportedEncodingException {
// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 定义一个uri对象,可以通过uri对象进行get传参
URI uri = new URIBuilder(
"http://localhost:8080/UserCXFSpringRestfulService/ws/rest/user")
.addParameter("_type", "xml")// 获取xml
// .addParameter("_type", "json")// 获取json
.build();
// 创建httppost请求对象
HttpPost httpPost = new HttpPost(uri);
// 定义一个响应结果对象
CloseableHttpResponse response = null;
// 构造 一个表单的参数,原来在jsp页面定义form表单,现在通过httpclient的api构造 一个表单
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
// 构造 表单的参数
// 原来在jsp中定义一个input的输入框,在这里使用BasicNameValuePair对象构造一个表单的参数
parameters.add(new BasicNameValuePair("id", "1"));
// 构造 一个表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
parameters);
// 进行表单的请求之间,将表单对象设置到httpPost对象中
httpPost.setEntity(urlEncodedFormEntity);
try {
// 进行http的post请求,获取响应结果
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {// 响应成功
// 获取响应的结果,进行utf-8编码
String responseString = EntityUtils.toString(
response.getEntity(), "utf-8");
System.out.println(responseString);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
7、上面测试的源码下载