WebService 的CXF框架 RS方式Spring开发
WebService:不同系统不同语言的数据交互, CXF 是目前最主流 WebService 开发框架 ,由 Apache 提供
CXF框架主要分为两种服务方式:
1 )JAX-WS:传输数据, xml格式,基于SOAP协议(规范:规定了xml传递数据的编码规范) ;
2 )JAX-RS:传输数据,xml或json格式.基于HTTP协议.(风格).
最终访问资源服务路径:服务器根目录地址 + web.xml 配置 + applicationContext.xml address 配置 + 类 @Path +方法 @Path
1.建立Maven web项目
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <groupId>cn.itcast.maven</groupId>
4 <artifactId>cxf_rs_spring</artifactId>
5 <version>0.0.1-SNAPSHOT</version>
6 <packaging>war</packaging>
7 <name>cxf_rs_spring</name>
8 <description>CXF的rs服务发布与spring整合</description>
9
10 <dependencies>
11 <!-- cxf 进行rs开发 必须导入 -->
12 <dependency>
13 <groupId>org.apache.cxf</groupId>
14 <artifactId>cxf-rt-frontend-jaxrs</artifactId>
15 <version>3.0.1</version>
16 </dependency>
17
18 <!-- 日志引入 -->
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-log4j12</artifactId>
22 <version>1.7.12</version>
23 </dependency>
24
25 <!-- 客户端 -->
26 <dependency>
27 <groupId>org.apache.cxf</groupId>
28 <artifactId>cxf-rt-rs-client</artifactId>
29 <version>3.0.1</version>
30 </dependency>
31
32 <!-- 扩展json提供者 -->
33 <dependency>
34 <groupId>org.apache.cxf</groupId>
35 <artifactId>cxf-rt-rs-extension-providers</artifactId>
36 <version>3.0.1</version>
37 </dependency>
38
39 <!-- 转换json工具包,被extension providers 依赖 -->
40 <dependency>
41 <groupId>org.codehaus.jettison</groupId>
42 <artifactId>jettison</artifactId>
43 <version>1.3.7</version>
44 </dependency>
45
46 <!-- spring 核心 -->
47 <dependency>
48 <groupId>org.springframework</groupId>
49 <artifactId>spring-context</artifactId>
50 <version>4.1.7.RELEASE</version>
51 </dependency>
52
53 <!-- spring web集成 -->
54 <dependency>
55 <groupId>org.springframework</groupId>
56 <artifactId>spring-web</artifactId>
57 <version>4.1.7.RELEASE</version>
58 </dependency>
59
60 <!-- spring 整合junit -->
61 <dependency>
62 <groupId>org.springframework</groupId>
63 <artifactId>spring-test</artifactId>
64 <version>4.1.7.RELEASE</version>
65 </dependency>
66
67 <!-- junit 开发包 -->
68 <dependency>
69 <groupId>junit</groupId>
70 <artifactId>junit</artifactId>
71 <version>4.12</version>
72 </dependency>
73 </dependencies>
74 <build>
75 <plugins>
76 <plugin>
77 <groupId>org.codehaus.mojo</groupId>
78 <artifactId>tomcat-maven-plugin</artifactId>
79 <version>1.1</version>
80 <configuration>
81 <port>9996</port>
82 </configuration>
83 </plugin>
84 </plugins>
85 </build>
86 </project>
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
5 id="WebApp_ID" version="2.5">
6
7 <!-- spring配置文件位置 -->
8 <context-param>
9 <param-name>contextConfigLocation</param-name>
10 <param-value>classpath:applicationContext.xml</param-value>
11 </context-param>
12 <!-- spring核心监听器 -->
13 <listener>
14 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15 </listener>
16 <!-- 1为优先级,接收与响应数据-->
17 <servlet>
18 <servlet-name>CXFService</servlet-name>
19 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
20 <load-on-startup>1</load-on-startup>
21 </servlet>
22 <servlet-mapping>
23 <servlet-name>CXFService</servlet-name>
24 <url-pattern>/services/*</url-pattern>
25 </servlet-mapping>
26
27 <welcome-file-list>
28 <welcome-file>index.html</welcome-file>
29 <welcome-file>index.htm</welcome-file>
30 <welcome-file>index.jsp</welcome-file>
31 <welcome-file>default.html</welcome-file>
32 <welcome-file>default.htm</welcome-file>
33 <welcome-file>default.jsp</welcome-file>
34 </welcome-file-list>
35
36 </web-app>
1 ### direct log messages to stdout ###
2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
3 log4j.appender.stdout.Target=System.out
4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
6
7 ### direct messages to file mylog.log ###
8 log4j.appender.file=org.apache.log4j.FileAppender
9 log4j.appender.file.File=c:/mylog.log
10 log4j.appender.file.layout=org.apache.log4j.PatternLayout
11 log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
12
13 ### set log levels - for more verbose logging change 'info' to 'debug' ###
14
15 log4j.rootLogger=info, stdout
2.创建实体类和Service
1 package cn.itcast.cxf.domain;
2
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "Car")
6 public class Car {
7 private Integer id;
8 private String carName;
9 private Double price;
10
11 public Integer getId() {
12 return id;
13 }
14
15 public void setId(Integer id) {
16 this.id = id;
17 }
18
19 public String getCarName() {
20 return carName;
21 }
22
23 public void setCarName(String carName) {
24 this.carName = carName;
25 }
26
27 public Double getPrice() {
28 return price;
29 }
30
31 public void setPrice(Double price) {
32 this.price = price;
33 }
34
35 @Override
36 public String toString() {
37 return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
38 }
39
40 }
1 package cn.itcast.cxf.domain;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 @XmlRootElement(name = "User")
9 public class User {
10 private Integer id;
11 private String username;
12 private String city;
13
14 private List<Car> cars = new ArrayList<Car>();
15
16 public Integer getId() {
17 return id;
18 }
19
20 public void setId(Integer id) {
21 this.id = id;
22 }
23
24 public String getUsername() {
25 return username;
26 }
27
28 public void setUsername(String username) {
29 this.username = username;
30 }
31
32 public String getCity() {
33 return city;
34 }
35
36 public void setCity(String city) {
37 this.city = city;
38 }
39
40 public List<Car> getCars() {
41 return cars;
42 }
43
44 public void setCars(List<Car> cars) {
45 this.cars = cars;
46 }
47
48 @Override
49 public String toString() {
50 return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
51 }
52
53 }
1 package cn.itcast.cxf.service;
2
3 import java.util.List;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.DELETE;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.PUT;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13
14 import cn.itcast.cxf.domain.User;
15
16 // @Path("/userService")//由于applicationContext.xml的address 配置重复.
17 @Produces("*/*")//产生(可以省略,在具体方法中添加)
18 public interface IUserService {
19
20 @POST//保存操作
21 @Path("/user")
22 @Consumes({ "application/xml", "application/json" })//消耗(接受的数据格式,与accept对应)
23 public void saveUser(User user);
24
25 @PUT//修改操作
26 @Path("/user")//方法的路径
27 @Consumes({ "application/xml", "application/json" })
28 public void updateUser(User user);
29
30 @GET//查询操作
31 @Path("/user")
32 @Produces({ "application/xml", "application/json" })//产生(返回数据的格式,与type相对应)
33 public List<User> findAllUsers();
34
35 @GET
36 @Path("/user/{id}")//方法路径+id的值
37 @Consumes("application/xml")
38 @Produces({ "application/xml", "application/json" })
39 public User finUserById(@PathParam("id") Integer id);
40
41 @DELETE//删除操作
42 @Path("/user/{id}")
43 @Consumes("application/xml")
44 public void deleteUser(@PathParam("id") Integer id);
45 }
1 package cn.itcast.cxf.service;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import cn.itcast.cxf.domain.Car;
7 import cn.itcast.cxf.domain.User;
8
9 public class UserServiceImpl implements IUserService {
10
11 public void saveUser(User user) {
12 System.out.println("save user:" + user);
13 }
14
15 public void updateUser(User user) {
16 System.out.println("update user:" + user);
17 }
18
19 public List<User> findAllUsers() {
20 List<User> users = new ArrayList<User>();
21 User user1 = new User();
22 user1.setId(1);
23 user1.setUsername("小明");
24 user1.setCity("北京");
25
26 List<Car> carList1 = new ArrayList<Car>();
27 Car car1 = new Car();
28 car1.setId(101);
29 car1.setCarName("保时捷");
30 car1.setPrice(1000000d);
31 carList1.add(car1);
32 Car car2 = new Car();
33 car2.setId(102);
34 car2.setCarName("宝马");
35 car2.setPrice(400000d);
36 carList1.add(car2);
37 user1.setCars(carList1);
38
39 users.add(user1);
40
41 User user2 = new User();
42 user2.setId(2);
43 user2.setUsername("小丽");
44 user2.setCity("上海");
45 users.add(user2);
46
47 return users;
48 }
49
50 public User finUserById(Integer id) {
51 if (id == 1) {
52 User user1 = new User();
53 user1.setId(1);
54 user1.setUsername("小明");
55 user1.setCity("北京");
56 return user1;
57 }
58 return null;
59 }
60
61 public void deleteUser(Integer id) {
62 System.out.println("delete user id :" + id);
63 }
64
65 }
3.导入Spring配置,发布RS服务,
引入名称空间 xmlns:jaxrs="http://cxf.apache.org/jaxrs" http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
4 xsi:schemaLocation="
5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
6 http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
7
8 <!--
9 address 发布服务地址
10 servicesBeans 服务实现类
11
12 -->
13 <jaxrs:server id="userService" address="/userService" >
14 <jaxrs:serviceBeans>
15 <bean class="cn.itcast.cxf.service.UserServiceImpl" />
16 </jaxrs:serviceBeans>
17
18 <jaxrs:inInterceptors>
19 <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
20 </jaxrs:inInterceptors>
21 <jaxrs:outInterceptors>
22 <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
23 </jaxrs:outInterceptors>
24 </jaxrs:server>
25
26 </beans>
1 配置服务启动窗口(上面pom已添加)
2 <build>
3 2 <plugins>
4 3 <plugin>
5 4 <groupId>org.codehaus.mojo</groupId>
6 5 <artifactId>tomcat-maven-plugin</artifactId>
7 6 <version>1.1</version>
8 7 <configuration>
9 8 <port>9996</port>
10 9 </configuration>
11 10 </plugin>
12 11 </plugins>
13 12 </build>
4.编写客户端代码
1 package cn.itcast.cxf.rs.client; 2 2 3 3 import java.util.Collection; 4 4 5 5 import javax.ws.rs.core.MediaType; 6 6 7 7 import org.apache.cxf.jaxrs.client.WebClient; 8 8 9 9 import cn.itcast.cxf.domain.User; 10 10 //create:建立与调用服务资源路径的连接 11 11 //type客户端发送给服务器的数据格式-------@consumes 12 12 //accept客户端接收服务器传输数据格式-----@Produces,这四个刚好走了一圈. 13 13 public class RS_Client { 14 14 public static void main(String[] args) { 15 15 User user = new User(); 16 16 user.setId(3); 17 17 user.setUsername("小美"); 18 18 user.setCity("深圳"); 19 19 20 20 // 根据id查询 21 21 WebClient client = WebClient.create("http://localhost:9999/"); 22 22 User responseUser = client.path("userService/user/1").accept(MediaType.APPLICATION_XML).get(User.class); 23 23 System.out.println(responseUser); 24 24 25 25 // 增加 26 26 WebClient.create("http://localhost:9999/services/userService/user").accept(MediaType.APPLICATION_XML) 27 27 .post(user); 28 28 29 29 // 修改 30 30 WebClient.create("http://localhost:9999/services/userService/user").type(MediaType.APPLICATION_JSON).put(user); 31 31 32 32 // 删除 33 33 WebClient.create("http://localhost:9999/").path("userService/user/1").accept(MediaType.APPLICATION_XML) 34 34 .delete(); 35 35 36 36 // 查询所有用户 37 37 Collection<? extends User> users = WebClient.create("http://localhost:9999/").path("userService/user") 38 38 .accept(MediaType.APPLICATION_JSON).getCollection(User.class); 39 39 System.out.println(users); 40 40 } 41 41 }
客户端 --------------- 服务器端
type >>>>>>>>>>Consumes(接收数据格式)
accept<<<<<<<<<<Produces(返回数据格式)
@Path | 服务器访问资源路径 |
@Produces | 指定生成那种格式的额数据格式返回给客户端 |
@Consumes | 指定接收的数据格式 |
@POST | 指定该方法为保存(保存) |
@DELETE | 指定该方法为删除 |
@PUT | 指定该方法为修改 |
@GET | 指定该方法为查询 |