webService是一种技术 实现多系统之间的通讯
CXF框架是webService的具体实现
CXF分为 JAX-WS JAX-RS
JAX-WS是基于xml格式传输数据 基于soap协议
JAX-RS是基于xml和json格式传输数据 基于HTTP协议
【JAX-WS独立使用】(了解)
1 建立maven的java项目(jar包)
2 导入cxfjar包的支持
<!-- 要进行jaxws 服务开发 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 内置jetty web服务器 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 日志实现 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
3 实现domian和service层代码
service层添加注解 在接口类上添加@WebService
在接口类的方法上添加@WebMethod
在实现类上@WebService(endpointInterface = "cn.itcast.cxf.service.IUserService", serviceName = "userService")
4 实现服务端的代码 将方法注册到网络
// 1 、 服务实现对象
IUserService userService = new UserServiceImpl();
// 2、 发布服务地址
String address = "http://localhost:9999/userService";
// 3、 发布服务
Endpoint.publish(address, userService);
5 实现客户端的代码
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setServiceClass(IUserService.class);
jaxWsProxyFactoryBean.setAddress("http://localhost:9999/userService");
//设置监控 输入输出日志
jaxWsProxyFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
jaxWsProxyFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
// 创建调用远程服务代理对象
IUserService proxy = (IUserService) jaxWsProxyFactoryBean.create();
// 调用代理对象 任何一个方法,都将通过网络 调用web服务
System.out.println(proxy.sayHello("传智播客"));
【JAX-WS和spring整合开发】
1 建立maven工程(war包)
2 导入坐标
<!-- cxf ws 开发-->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!--spring开发 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring开发-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring整合测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3 web.xml编写
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CXF 基于 web 访问 -->
<servlet>
<servlet-name>CXFService</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFService</servlet-name>
<url-pattern>/services/*</url-pattern>
*/ </servlet-mapping>
4 applicationContext.xml编写
引入名称空间
xmlns:jaxws="http://cxf.apache.org/jaxws"
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
<!--
address 客户端访问服务路径 serviceClass 配置接口 serviceBean 配置实现类
-->
<jaxws:server id="userService" address="/userService"
serviceClass="cn.itcast.cxf.service.IUserService">
<jaxws:serviceBean>
<bean class="cn.itcast.cxf.service.UserServiceImpl" />
</jaxws:serviceBean>
</jaxws:server>
5 访问路径
基础路径+web中配置的路径+applicationContext中配置的路径
http://localhost:9998/cxf_ws_spring/services/userService?wsdl
6 客户端applicationContext配置(web.xml配置同上)
<!--
serviceClass 服务接口 address 服务访问地址
-->
<jaxws:client id="userServiceClient"
serviceClass="cn.itcast.cxf.service.IUserService"
address="http://localhost:9998/cxf_ws_spring/services/userService" >
<!-- 来源消息拦截器 -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:inInterceptors>
<!-- 输出消息拦截器 -->
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxws:outInterceptors>
</jaxws:client>
【restful风格】*****
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。
restful好处
基于这种风格架构,软件编写可以更简洁
基于 HTTP 协议, 支持多种消息格式,比如 XML 、JSON
更易于实现缓存机制 (第一次访问资源 缓存,第二次访问资源,返回 304 客户端调用本地)
POST 请求方式访问 保存操作
PUT 请求方式访问 修改操作
GET 请求方式访问 查询操作
DELETE 请求方式访问 删除操作
【JAX-rs独立使用】(了解)
1 建立maven的java项目(jar包)
2 导入坐标
<!-- 使用CXF RS开发 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 内置jetty web服务器 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 使用log4j日志实现 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
3 实体类和service创建
实体类类名上写注解 @XmlRootElement(name="user") 指定序列化 转换成xml或json时使用的名字
如果 WebService CXF 返回带有泛型的集合 ,解决需要在使用带有泛型的集合类型上面@XmlSeeAlso(类名.class) 注解
service层
@Path("/userService")
public interface IUserService {
@POST
@Path("/user")
@Consumes({ "application/xml", "application/json" })
public void saveUser(User user);
@PUT
@Path("/user")
@Consumes({ "application/xml", "application/json" })
public void updateUser(User user);
@GET
@Path("/user")
@Produces({ "application/xml", "application/json" })
public List<User> findAllUsers();
@GET
@Path("/user/{id}")
@Consumes("application/xml")
@Produces({ "application/xml", "application/json" })
public User finUserById(@PathParam("id") Integer id);
@DELETE
@Path("/user/{id}")
@Consumes("application/xml")
public void deleteUser(@PathParam("id") Integer id);
}
@path 服务访问资源路径
@producers 传送给客户端的数据格式
@consumers 处理客户端传递过来的数据格式
4 服务器端实现
// 创建业务接口 实现类对象
IUserService userService = new UserServiceImpl();
// 服务器FactoryBean 创建服务
JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
jaxrsServerFactoryBean.setResourceClasses(User.class, Car.class); // 将哪些实体数据转换xml、json发送
jaxrsServerFactoryBean.setServiceBean(userService);
jaxrsServerFactoryBean.setAddress("http://localhost:9997");
// 发布服务
jaxrsServerFactoryBean.create();
5 访问路径
基础路径+类名上的@path+方法上的@path http://localhost:9997/userService/user
6 客户端实现
基于服务端的基础上再倒入一些jar包
<!-- 使用rs客户端 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
// create 建立与调用 服务资源路径 连接
// type 发送给服务器数据格式 --- @Consumes
// accept 接收服务器传输数据格式 ---- @Produces
// 采用HTTP协议哪种方式访问服务器
Collection<? extends User> collection = WebClient
.create("http://localhost:9997/userService/user")
.accept(MediaType.APPLICATION_XML).getCollection(User.class);
WebClient.create("http://localhost:9997/userService/user")
.type(MediaType.APPLICATION_JSON).post(user);
User resultUser = WebClient
.create("http://localhost:9997/userService/user/1")
.accept(MediaType.APPLICATION_JSON).get(User.class);
7 如果指定转换json格式的数据需要另外导入jar包
<!-- 在CXF扩展提供者,提供转换json接口 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<!-- cxf 扩展提供者 转换json 默认需求一个工具包 -->
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
【JAX-RS和Spring整合开发】******
1 建立maven web项目(war包)
2 导入坐标
<!-- cxf 进行rs开发 必须导入 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 日志引入 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!-- 客户端 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 扩展json提供者 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 转换json工具包,被extension providers 依赖 -->
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
<!-- spring 核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring web集成 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring 整合junit -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- junit 开发包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3 web.xml配置
<!-- spring配置文件位置 --> <!-- spring核心监听器 --> ..........
<servlet>
<servlet-name>CXFService</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFService</servlet-name>
<url-pattern>/services/*</url-pattern>
*/ </servlet-mapping>
4 applicationContext配置
引入名称空间 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
<jaxrs:server id="userService" address="/userService" >
<jaxrs:serviceBeans>
<bean class="cn.itcast.cxf.service.UserServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxrs:outInterceptors>
</jaxrs:server>
5 最终访问资源服务路径
服务器根目录地址 + web.xml 配置 + applicationContext.xml address 配置 + 类 @Path +方法 @Path
6 客户端代码
Collection<? extends User> collection = WebClient
.create("http://localhost:9997/services/userService/user")
.accept(MediaType.APPLICATION_XML).getCollection(User.class);//查询所有数据
WebClient.create("http://localhost:9997/services/userService/user")
.type(MediaType.APPLICATION_JSON).post(user);//保存user
User resultUser = WebClient
.create("http://localhost:9997/services/userService/user/1")
.accept(MediaType.APPLICATION_JSON).get(User.class);//查询id是1的user
【客户与定区关联案例】
1 引入jar包 bos系统中引入对crm_domain的依赖
crm系统中配置web.xml 配置applicationContext.xml 实体类加@XmlRootElement注解
2 crm的service层接口实现
//查询未关联的客户信息
@Path("/noassociationcustomers")
@GET
@Produces({"application/xml","application/json"})
public List<Customer> findNoAssociationCustomers();
//已经关联的客户信息
@Path("/associationfixedareacustomers/{fixedareaid}")
@GET
@Produces({"application/xml","application/json"})
public List<Customer> findHasAssociationFixedAreaCustomers(
@PathParam("fixedareaid") String FixedAreaId);
//将客户关联到定区,将所有的客户id连接成字符串 1,2,3
@PUT
@Path("/associationcustomerstofixedarea")
public void associationCustomersToFixedArea(
@QueryParam("customerIdStr") String customerIdStr,
@QueryParam("fixedAreaId") String fixedAreaId);
3 crm的service层实现类
public List<Customer> findNoAssociationCustomers() {
return customerRepository.findByFixedAreaIdIsNull();
}
public List<Customer> findHasAssociationFixedAreaCustomers(String FixedAreaId) {
return customerRepository.findByFixedAreaId(FixedAreaId);
}
public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
//解除关联
customerRepository.clearFixedAreaId(fixedAreaId);
//避免空指针异常
if(StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)){
return;
}
//切割字符串
String[] split = customerIdStr.split(",");
for (String idstr : split) {
Integer id=Integer.parseInt(idstr);
customerRepository.updateFixedArea(fixedAreaId,id);
}
}
3 crm的dao层实现
public List<Customer> findByFixedAreaIdIsNull();
public List<Customer> findByFixedAreaId(String fixedAreaId);
@Query("update Customer set fixedAreaId=? where id=?")
@Modifying
public void updateFixedArea(String fixedAreaId,Integer id);
@Query("update Customer set fixedAreaId=null where fixedAreaId=?")
@Modifying
public void clearFixedAreaId(String fixedAreaId);
4 页面实现
点击关联客户
function doAssociations(){
var rows=$("#grid").datagrid('getSelections');
if(rows.length==1){
//将选中的定区id 设置到隐藏域中
$("#customerFixedAreaId").val(rows[0].id);
//显示进度条
$.messager.progress({
interval :500
});
//清空列表
$("#noassociationSelect").empty();
$("#associationSelect").empty();
//发起ajax请求
$.post("../../fixedArea_findNoAssociationCustomers.action",function(data){
$(data).each(function(){
var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
$("#noassociationSelect").append(option);
});
//请求结束后关闭进度条
$.messager.progress('close');
//弹出关联窗口
$('#customerWindow').window('open');
});
$.post("../../fixedArea_findHasAssociationFixedAreaCustomers.action",{"id":rows[0].id},function(data){
$(data).each(function(){
var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
$("#associationSelect").append(option);
});
//弹出关联窗口
$('#customerWindow').window('open');
})
}else{
$.messager.alert("警告","只能选择一条数据","warning");
}
}
关联客户实现
//向右移动按钮
$("#toRight").click(function(){
$("#associationSelect").append($("#noassociationSelect option:selected"));
})
//向左移动按钮
$("#toLeft").click(function(){
$("#noassociationSelect").append($("#associationSelect option:selected"));
});
//关联客户按钮添加事件
$("#associationBtn").click(function(){
//右侧列表 设置全选
$("#associationSelect option").attr("selected","selected");
//提交
$("#customerForm").submit();
});
5 bos系统的action层
@Action(value="fixedArea_findNoAssociationCustomers",results={
@Result(name="success",type="json")
})
public String findNoAssociationCustomers(){
Collection<? extends Customer> collection=WebClient.create
("http://localhost:9002/crm_management/services/customerService/noassociationcustomers")
.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
ActionContext.getContext().getValueStack().push(collection);
return SUCCESS;
}
@Action(value="fixedArea_findHasAssociationFixedAreaCustomers",results={
@Result(name="success",type="json")
})
public String findHasAssociationFixedAreaCustomers(){
Collection<? extends Customer> collection=WebClient.create
("http://localhost:9002/crm_management/services/customerService/associationfixedareacustomers/"+model.getId())
.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
.getCollection(Customer.class);
ActionContext.getContext().getValueStack().push(collection);
return SUCCESS;
}
@Action(value="fixedArea_associationCustomerToFixedArea",results=
{@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
public String associationCustomerToFixedArea(){
String customerIdStr = StringUtils.join(customerIds, ",");
WebClient.create("http://localhost:9002/crm_management/"
+ "services/customerService/associationcustomerstofixedarea"
+ "?customerIdStr="+customerIdStr+"&fixedAreaId="+model.getId()).put(null);
return SUCCESS;
}
CXF框架是webService的具体实现
CXF分为 JAX-WS JAX-RS
JAX-WS是基于xml格式传输数据 基于soap协议
JAX-RS是基于xml和json格式传输数据 基于HTTP协议
【JAX-WS独立使用】(了解)
1 建立maven的java项目(jar包)
2 导入cxfjar包的支持
<!-- 要进行jaxws 服务开发 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 内置jetty web服务器 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 日志实现 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
3 实现domian和service层代码
service层添加注解 在接口类上添加@WebService
在接口类的方法上添加@WebMethod
在实现类上@WebService(endpointInterface = "cn.itcast.cxf.service.IUserService", serviceName = "userService")
4 实现服务端的代码 将方法注册到网络
// 1 、 服务实现对象
IUserService userService = new UserServiceImpl();
// 2、 发布服务地址
String address = "http://localhost:9999/userService";
// 3、 发布服务
Endpoint.publish(address, userService);
5 实现客户端的代码
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setServiceClass(IUserService.class);
jaxWsProxyFactoryBean.setAddress("http://localhost:9999/userService");
//设置监控 输入输出日志
jaxWsProxyFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
jaxWsProxyFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
// 创建调用远程服务代理对象
IUserService proxy = (IUserService) jaxWsProxyFactoryBean.create();
// 调用代理对象 任何一个方法,都将通过网络 调用web服务
System.out.println(proxy.sayHello("传智播客"));
【JAX-WS和spring整合开发】
1 建立maven工程(war包)
2 导入坐标
<!-- cxf ws 开发-->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!--spring开发 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring开发-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring整合测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3 web.xml编写
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CXF 基于 web 访问 -->
<servlet>
<servlet-name>CXFService</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFService</servlet-name>
<url-pattern>/services/*</url-pattern>
*/ </servlet-mapping>
4 applicationContext.xml编写
引入名称空间
xmlns:jaxws="http://cxf.apache.org/jaxws"
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
<!--
address 客户端访问服务路径 serviceClass 配置接口 serviceBean 配置实现类
-->
<jaxws:server id="userService" address="/userService"
serviceClass="cn.itcast.cxf.service.IUserService">
<jaxws:serviceBean>
<bean class="cn.itcast.cxf.service.UserServiceImpl" />
</jaxws:serviceBean>
</jaxws:server>
5 访问路径
基础路径+web中配置的路径+applicationContext中配置的路径
http://localhost:9998/cxf_ws_spring/services/userService?wsdl
6 客户端applicationContext配置(web.xml配置同上)
<!--
serviceClass 服务接口 address 服务访问地址
-->
<jaxws:client id="userServiceClient"
serviceClass="cn.itcast.cxf.service.IUserService"
address="http://localhost:9998/cxf_ws_spring/services/userService" >
<!-- 来源消息拦截器 -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:inInterceptors>
<!-- 输出消息拦截器 -->
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxws:outInterceptors>
</jaxws:client>
【restful风格】*****
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。
restful好处
基于这种风格架构,软件编写可以更简洁
基于 HTTP 协议, 支持多种消息格式,比如 XML 、JSON
更易于实现缓存机制 (第一次访问资源 缓存,第二次访问资源,返回 304 客户端调用本地)
POST 请求方式访问 保存操作
PUT 请求方式访问 修改操作
GET 请求方式访问 查询操作
DELETE 请求方式访问 删除操作
【JAX-rs独立使用】(了解)
1 建立maven的java项目(jar包)
2 导入坐标
<!-- 使用CXF RS开发 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 内置jetty web服务器 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 使用log4j日志实现 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
3 实体类和service创建
实体类类名上写注解 @XmlRootElement(name="user") 指定序列化 转换成xml或json时使用的名字
如果 WebService CXF 返回带有泛型的集合 ,解决需要在使用带有泛型的集合类型上面@XmlSeeAlso(类名.class) 注解
service层
@Path("/userService")
public interface IUserService {
@POST
@Path("/user")
@Consumes({ "application/xml", "application/json" })
public void saveUser(User user);
@PUT
@Path("/user")
@Consumes({ "application/xml", "application/json" })
public void updateUser(User user);
@GET
@Path("/user")
@Produces({ "application/xml", "application/json" })
public List<User> findAllUsers();
@GET
@Path("/user/{id}")
@Consumes("application/xml")
@Produces({ "application/xml", "application/json" })
public User finUserById(@PathParam("id") Integer id);
@DELETE
@Path("/user/{id}")
@Consumes("application/xml")
public void deleteUser(@PathParam("id") Integer id);
}
@path 服务访问资源路径
@producers 传送给客户端的数据格式
@consumers 处理客户端传递过来的数据格式
4 服务器端实现
// 创建业务接口 实现类对象
IUserService userService = new UserServiceImpl();
// 服务器FactoryBean 创建服务
JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
jaxrsServerFactoryBean.setResourceClasses(User.class, Car.class); // 将哪些实体数据转换xml、json发送
jaxrsServerFactoryBean.setServiceBean(userService);
jaxrsServerFactoryBean.setAddress("http://localhost:9997");
// 发布服务
jaxrsServerFactoryBean.create();
5 访问路径
基础路径+类名上的@path+方法上的@path http://localhost:9997/userService/user
6 客户端实现
基于服务端的基础上再倒入一些jar包
<!-- 使用rs客户端 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
// create 建立与调用 服务资源路径 连接
// type 发送给服务器数据格式 --- @Consumes
// accept 接收服务器传输数据格式 ---- @Produces
// 采用HTTP协议哪种方式访问服务器
Collection<? extends User> collection = WebClient
.create("http://localhost:9997/userService/user")
.accept(MediaType.APPLICATION_XML).getCollection(User.class);
WebClient.create("http://localhost:9997/userService/user")
.type(MediaType.APPLICATION_JSON).post(user);
User resultUser = WebClient
.create("http://localhost:9997/userService/user/1")
.accept(MediaType.APPLICATION_JSON).get(User.class);
7 如果指定转换json格式的数据需要另外导入jar包
<!-- 在CXF扩展提供者,提供转换json接口 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<!-- cxf 扩展提供者 转换json 默认需求一个工具包 -->
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
【JAX-RS和Spring整合开发】******
1 建立maven web项目(war包)
2 导入坐标
<!-- cxf 进行rs开发 必须导入 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 日志引入 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!-- 客户端 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 扩展json提供者 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<!-- 转换json工具包,被extension providers 依赖 -->
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
<!-- spring 核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring web集成 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- spring 整合junit -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- junit 开发包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3 web.xml配置
<!-- spring配置文件位置 --> <!-- spring核心监听器 --> ..........
<servlet>
<servlet-name>CXFService</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFService</servlet-name>
<url-pattern>/services/*</url-pattern>
*/ </servlet-mapping>
4 applicationContext配置
引入名称空间 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
<jaxrs:server id="userService" address="/userService" >
<jaxrs:serviceBeans>
<bean class="cn.itcast.cxf.service.UserServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxrs:outInterceptors>
</jaxrs:server>
5 最终访问资源服务路径
服务器根目录地址 + web.xml 配置 + applicationContext.xml address 配置 + 类 @Path +方法 @Path
6 客户端代码
Collection<? extends User> collection = WebClient
.create("http://localhost:9997/services/userService/user")
.accept(MediaType.APPLICATION_XML).getCollection(User.class);//查询所有数据
WebClient.create("http://localhost:9997/services/userService/user")
.type(MediaType.APPLICATION_JSON).post(user);//保存user
User resultUser = WebClient
.create("http://localhost:9997/services/userService/user/1")
.accept(MediaType.APPLICATION_JSON).get(User.class);//查询id是1的user
【客户与定区关联案例】
1 引入jar包 bos系统中引入对crm_domain的依赖
crm系统中配置web.xml 配置applicationContext.xml 实体类加@XmlRootElement注解
2 crm的service层接口实现
//查询未关联的客户信息
@Path("/noassociationcustomers")
@GET
@Produces({"application/xml","application/json"})
public List<Customer> findNoAssociationCustomers();
//已经关联的客户信息
@Path("/associationfixedareacustomers/{fixedareaid}")
@GET
@Produces({"application/xml","application/json"})
public List<Customer> findHasAssociationFixedAreaCustomers(
@PathParam("fixedareaid") String FixedAreaId);
//将客户关联到定区,将所有的客户id连接成字符串 1,2,3
@PUT
@Path("/associationcustomerstofixedarea")
public void associationCustomersToFixedArea(
@QueryParam("customerIdStr") String customerIdStr,
@QueryParam("fixedAreaId") String fixedAreaId);
3 crm的service层实现类
public List<Customer> findNoAssociationCustomers() {
return customerRepository.findByFixedAreaIdIsNull();
}
public List<Customer> findHasAssociationFixedAreaCustomers(String FixedAreaId) {
return customerRepository.findByFixedAreaId(FixedAreaId);
}
public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
//解除关联
customerRepository.clearFixedAreaId(fixedAreaId);
//避免空指针异常
if(StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)){
return;
}
//切割字符串
String[] split = customerIdStr.split(",");
for (String idstr : split) {
Integer id=Integer.parseInt(idstr);
customerRepository.updateFixedArea(fixedAreaId,id);
}
}
3 crm的dao层实现
public List<Customer> findByFixedAreaIdIsNull();
public List<Customer> findByFixedAreaId(String fixedAreaId);
@Query("update Customer set fixedAreaId=? where id=?")
@Modifying
public void updateFixedArea(String fixedAreaId,Integer id);
@Query("update Customer set fixedAreaId=null where fixedAreaId=?")
@Modifying
public void clearFixedAreaId(String fixedAreaId);
4 页面实现
点击关联客户
function doAssociations(){
var rows=$("#grid").datagrid('getSelections');
if(rows.length==1){
//将选中的定区id 设置到隐藏域中
$("#customerFixedAreaId").val(rows[0].id);
//显示进度条
$.messager.progress({
interval :500
});
//清空列表
$("#noassociationSelect").empty();
$("#associationSelect").empty();
//发起ajax请求
$.post("../../fixedArea_findNoAssociationCustomers.action",function(data){
$(data).each(function(){
var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
$("#noassociationSelect").append(option);
});
//请求结束后关闭进度条
$.messager.progress('close');
//弹出关联窗口
$('#customerWindow').window('open');
});
$.post("../../fixedArea_findHasAssociationFixedAreaCustomers.action",{"id":rows[0].id},function(data){
$(data).each(function(){
var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
$("#associationSelect").append(option);
});
//弹出关联窗口
$('#customerWindow').window('open');
})
}else{
$.messager.alert("警告","只能选择一条数据","warning");
}
}
关联客户实现
//向右移动按钮
$("#toRight").click(function(){
$("#associationSelect").append($("#noassociationSelect option:selected"));
})
//向左移动按钮
$("#toLeft").click(function(){
$("#noassociationSelect").append($("#associationSelect option:selected"));
});
//关联客户按钮添加事件
$("#associationBtn").click(function(){
//右侧列表 设置全选
$("#associationSelect option").attr("selected","selected");
//提交
$("#customerForm").submit();
});
5 bos系统的action层
@Action(value="fixedArea_findNoAssociationCustomers",results={
@Result(name="success",type="json")
})
public String findNoAssociationCustomers(){
Collection<? extends Customer> collection=WebClient.create
("http://localhost:9002/crm_management/services/customerService/noassociationcustomers")
.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
ActionContext.getContext().getValueStack().push(collection);
return SUCCESS;
}
@Action(value="fixedArea_findHasAssociationFixedAreaCustomers",results={
@Result(name="success",type="json")
})
public String findHasAssociationFixedAreaCustomers(){
Collection<? extends Customer> collection=WebClient.create
("http://localhost:9002/crm_management/services/customerService/associationfixedareacustomers/"+model.getId())
.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
.getCollection(Customer.class);
ActionContext.getContext().getValueStack().push(collection);
return SUCCESS;
}
@Action(value="fixedArea_associationCustomerToFixedArea",results=
{@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
public String associationCustomerToFixedArea(){
String customerIdStr = StringUtils.join(customerIds, ",");
WebClient.create("http://localhost:9002/crm_management/"
+ "services/customerService/associationcustomerstofixedarea"
+ "?customerIdStr="+customerIdStr+"&fixedAreaId="+model.getId()).put(null);
return SUCCESS;
}