apache cxf 基于jax-rs规范实现的webservice(RESTFUL)

2024-05-29 08:58

本文主要是介绍apache cxf 基于jax-rs规范实现的webservice(RESTFUL),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.restful

基于jax-rs规范发布服务使用restful风格的webservice,请求使用的是http协议,可以传递xml/json数据。

REST(英文:Representational State Transfer,简称REST)描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之一。在目前主流的三种Web服务交互方案中,REST相比于SOAP(Simple Object Access protocol,简单对象访问协议)以及XML-RPC更加简单明了,无论是对URL的处理还是对Payload的编码,REST都倾向于用更加简单轻量的方法设计和实现。值得注意的是REST并没有一个明确的标准,而更像是一种设计的风格。

1.restful与非restful

在Restful之前的操作:
http://127.0.0.1/user/query/1 GET  根据用户id查询用户数据
http://127.0.0.1/user/save POST 新增用户
http://127.0.0.1/user/update POST 修改用户信息
http://127.0.0.1/user/delete GET/POST 删除用户信息

RESTful用法:
http://127.0.0.1/user/1 GET  根据用户id查询用户数据
http://127.0.0.1/user  POST 新增用户
http://127.0.0.1/user  PUT 修改用户信息
http://127.0.0.1/user  DELETE 删除用户信息

之前的操作是没有问题的,大神认为是有问题的,有什么问题呢?你每次请求的接口或者地址,都在做描述,例如查询的时候用了query,新增的时候用了save,其实完全没有这个必要,我使用了get请求,就是查询.使用post请求,就是新增的请求,我的意图很明显,完全没有必要做描述,这就是为什么有了restful.

2.状态转化

访问一个网站,就代表了客户端和服务器的一个互动过程。在这个过程中,势必涉及到数据和状态的变化。互联网通信协议HTTP协议,是一个无状态协议。这意味着,所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生"状态转化"(StateTransfer)。而这种转化是建立在表现层之上的,所以就是"表现层状态转化"。客户端用到的手段,只能是HTTP协议。具体来说,就是HTTP协议里面四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:

GET用来获取资源,

POST用来新建资源,

PUT用来更新资源,

DELETE用来删除资源。

访问服务器资源,通过不同的http请求方式,服务器就知道对CRUD的哪个操作

JAX-RS 发布服务就是使用RESTFUL风格。

二.apache cxf 基于jax-rs规范实现的webservice-服务端

基于jax-rs规范发布服务使用restful风格的webservice,请求使用的是http协议,可以传递xml/json数据。

新建项目:jars-ws-server

1.新建pom文件

<?xml version="1.0" encoding="UTF-8"?><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"><parent><artifactId>web-service-demo</artifactId><groupId>com.meboth.bonc.ljf</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><groupId>com.meboth.bonc.ljf.jars.ws</groupId><artifactId>jars-ws-server</artifactId><version>1.0-SNAPSHOT</version><name>jars-ws-server</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- jaxrs 支持包 --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxrs</artifactId><version>3.0.1</version></dependency><!-- 内置的jetty服务器 --><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><!-- 客户端调用时候使用的包(WebClient工具类调用服务端) --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-rs-client</artifactId><version>3.0.1</version></dependency><!-- 基于restful风格的webservice,客户端与服务端之间可以传递json,这个就是json支持相关包 --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-rs-extension-providers</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.codehaus.jettison</groupId><artifactId>jettison</artifactId><version>1.3.7</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency></dependencies><build><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding><showWarnings>true</showWarnings></configuration></plugin></plugins></pluginManagement></build>
</project>

2.定义实体类

package com.meboth.bonc.ljf.jars.ws.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "myBike")
public class Bike {private int id;private String carName;private float price;public Bike() {}public Bike(int id, String carName, float price) {this.id = id;this.carName = carName;this.price = price;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getCarName() {return carName;}public void setCarName(String carName) {this.carName = carName;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}
}package com.meboth.bonc.ljf.jars.ws.model;import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "myPeople")
public class People {private int id;private String userName;private List<Bike> bikeList=new ArrayList<Bike>();public People() {}public People(int id, String userName, List<Bike> bikeList) {this.id = id;this.userName = userName;this.bikeList = bikeList;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public List<Bike> getBikeList() {return bikeList;}public void setBikeList(List<Bike> bikeList) {this.bikeList = bikeList;}
}

3.定义实现类

package com.meboth.bonc.ljf.jars.ws.service;import com.meboth.bonc.ljf.jars.ws.model.People;import javax.ws.rs.*;
import java.util.List;@Path("/tjService")  // 路径;访问当前服务接口时候的路径。
@Produces("*/*")
public interface TianJingService {@POST@Path("/tjUser")	  // 路径; 访问当前服务接口的方法路径// @Consumes 服务端支持的请求的数据格式(xml、json)@Consumes({ "application/xml", "application/json" })public void saveUser(People user);@PUT@Path("/tjUser")@Consumes({ "application/xml", "application/json" })public void updateUser(People user);@GET@Path("/tjUser")// @Produces 服务端支持的响应的数据格式@Produces({ "application/xml", "application/json" })public List<People> findAllUsers();@GET@Path("/tjUser/{id}")@Consumes("application/xml")@Produces({ "application/xml", "application/json" })public People finUserById(@PathParam("id") Integer id);@DELETE@Path("/tjUser/{id}")@Consumes({"application/xml", "application/json"})public void deleteUser(@PathParam("id") Integer id);
}package com.meboth.bonc.ljf.jars.ws.service;import com.meboth.bonc.ljf.jars.ws.model.Bike;
import com.meboth.bonc.ljf.jars.ws.model.People;import java.util.ArrayList;
import java.util.List;public class TianJingServiceImpl implements TianJingService {public void saveUser(People user) {System.out.println("save user:" + user.getUserName());}public void updateUser(People user) {System.out.println("update user:" + user);}public List<People> findAllUsers() {List<People> users = new ArrayList<People>();// 汽车List<Bike> carList1 = new ArrayList<Bike>();Bike car1 = new Bike(101,"保时捷",1000000f);Bike car2 = new Bike(102,"林肯",400000f);carList1.add(car1);carList1.add(car2);// 用户People user1 = new People(1,"小明",carList1);People user2 = new People(2,"小丽",carList1);// 用户集合users.add(user1);users.add(user2);return users;}public People finUserById(Integer id) {if (id == 1) {Bike bike=   new Bike(101,"保时捷",1000000f);List<Bike> bList=   new ArrayList<Bike>();bList.add(bike);return new People(1,"小明",bList);}return null;}public void deleteUser(Integer id) {System.out.println("delete user id :" + id);}
}

 

使用的注解:

@XmlRootElement

指定根元素,

作用:客户端与服务端传递对象数据时候,序列化为xml或json的根元素的名称

@Path("/userService")

路径;访问当前服务接口时候的路径、接口方法的路径。

@POST insert操作

@PUT update操作

@GET select 查询操作

@DELETE delete删除操作

@Consumes 服务端支持的请求的数据格式(xml、json)

@Produces 服务端支持的响应的数据格式

4.资源配置类:

log4j.rootLogger=INFO,console,FILE
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.threshold=INFO
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}[%5p]-%c(%L)-%m%n
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.Append=true
log4j.appender.FILE.File=./web-service.log
log4j.appender.FILE.Threshold=INFO
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss}[%5p]-%c(%L)-%m%n
log4j.appender.FILE.MaxFileSize=30MB

 

5.启动类

package com.meboth.bonc.ljf.jars.ws;import com.meboth.bonc.ljf.jars.ws.service.TianJingServiceImpl;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;/*** Hello world!**/
public class JaxRsServer
{/*** 发布restful风格的webservice的服务*/public static void main( String[] args ) {//1.创建服务工厂JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();//2.设置服务地址、factory.setAddress("http://localhost:8001/rs");//3.实例化服务类、factory.setServiceBean(new TianJingServiceImpl());// 添加日志拦截器factory.getInInterceptors().add(new LoggingInInterceptor());factory.getOutInterceptors().add(new LoggingOutInterceptor());//4.创建服务factory.create();System.out.println("发布服务成功.......端口:8001");}
}

6.启动服务

 

三.apache cxf 基于jax-rs规范实现的webservice-客户端

新建项目:jars-ws-client

1.pom文件

<?xml version="1.0" encoding="UTF-8"?><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"><parent><artifactId>web-service-demo</artifactId><groupId>com.meboth.bonc.ljf</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><groupId>com.meboth.bonc.ljf.jars.ws.client</groupId><artifactId>jars-ws-client</artifactId><version>1.0-SNAPSHOT</version><name>jars-ws-client</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><!-- jaxrs 支持包 --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxrs</artifactId><version>3.0.1</version></dependency><!-- 内置的jetty服务器 --><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><!-- 客户端调用时候使用的包(WebClient工具类调用服务端) --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-rs-client</artifactId><version>3.0.1</version></dependency><!-- 基于restful风格的webservice,客户端与服务端之间可以传递json,这个就是json支持相关包 --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-rs-extension-providers</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.codehaus.jettison</groupId><artifactId>jettison</artifactId><version>1.3.7</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency></dependencies><build><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><!-- maven的jdk编译插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding><showWarnings>true</showWarnings></configuration></plugin></plugins></pluginManagement></build>
</project>

2.实体类:

package com.meboth.bonc.ljf.jars.ws.client.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "myBike")
public class Bike {private int id;private String carName;private float price;public Bike() {}public Bike(int id, String carName, float price) {this.id = id;this.carName = carName;this.price = price;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getCarName() {return carName;}public void setCarName(String carName) {this.carName = carName;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}
}package com.meboth.bonc.ljf.jars.ws.client.model;import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;@XmlRootElement(name = "myPeople")
public class People {private int id;private String userName;private List<Bike> bikeList=new ArrayList<Bike>();public People() {}public People(int id, String userName, List<Bike> bikeList) {this.id = id;this.userName = userName;this.bikeList = bikeList;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public List<Bike> getBikeList() {return bikeList;}public void setBikeList(List<Bike> bikeList) {this.bikeList = bikeList;}
}

3.启动类:

package com.meboth.bonc.ljf.jars.ws.client;import com.meboth.bonc.ljf.jars.ws.client.model.Bike;
import com.meboth.bonc.ljf.jars.ws.client.model.People;
import org.apache.cxf.jaxrs.client.WebClient;import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;public class JarWsClient {/***  .create()     指定服务端地址.type()      指定请求数据格式(xml、json).accept()    指定响应数据格式.post()/put()/delete()/get()  指定请求类型*/public static void main(String args[])throws Exception{//save();//update();//findOne();findAll();}/*** 添加* @throws Exception*/public static  void save() throws Exception {// 基于restful风格的webservice开发的客户端调用,直接通过一个类:WebClient类完成Bike bike=   new Bike(101,"haval h6",1000000f);List<Bike> bList=   new ArrayList<Bike>();bList.add(bike);bList.add(new Bike(101,"linken",3000000f));WebClient.create("http://localhost:8001/rs/tjService/tjUser")  // 地址.type(MediaType.APPLICATION_JSON)                     // 请求数据格式是json.post(new People(100,"Kobe",bList));                  // 发送请求的类型}/*** 修改* @throws Exception*/public static  void update() throws Exception {WebClient.create("http://localhost:8001/rs/tjService/tjUser")  // 地址.type(MediaType.APPLICATION_JSON)                     // 请求数据格式是json.put(new People(100,"Kobe",null));                   // 发送请求的类型}/*** 通过id查找* @throws Exception*/public static void findOne() throws Exception {People user =WebClient.create("http://localhost:8001/rs/tjService/tjUser/1")  // 地址.accept(MediaType.APPLICATION_JSON)  // 响应的数据格式.get(People.class);System.out.println(user);}/*** 查询全部* @throws Exception*/public static void findAll() throws Exception {Collection<? extends People> list=WebClient.create("http://localhost:8001/rs/tjService/tjUser/").accept(MediaType.APPLICATION_JSON).getCollection(People.class);for(People p:list){System.out.println("p:"+p);}}
}

4.log4j日志:

log4j.rootLogger=INFO,console,FILE
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.threshold=INFO
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}[%5p]-%c(%L)-%m%n
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.Append=true
log4j.appender.FILE.File=./web-service.log
log4j.appender.FILE.Threshold=INFO
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss}[%5p]-%c(%L)-%m%n
log4j.appender.FILE.MaxFileSize=30MB

5.调试访问:

执行findAll()方法

public static void main(String args[])throws Exception{//save();//update();//findOne();findAll();
}

 

客户端: 

 

这篇关于apache cxf 基于jax-rs规范实现的webservice(RESTFUL)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1013220

相关文章

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

基于Go语言实现Base62编码的三种方式以及对比分析

《基于Go语言实现Base62编码的三种方式以及对比分析》Base62编码是一种在字符编码中使用62个字符的编码方式,在计算机科学中,,Go语言是一种静态类型、编译型语言,它由Google开发并开源,... 目录一、标准库现状与解决方案1. 标准库对比表2. 解决方案完整实现代码(含边界处理)二、关键实现细

python通过curl实现访问deepseek的API

《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... API申请和充值下面是deepeek的API网站https://platform.deepsee

SpringBoot实现二维码生成的详细步骤与完整代码

《SpringBoot实现二维码生成的详细步骤与完整代码》如今,二维码的应用场景非常广泛,从支付到信息分享,二维码都扮演着重要角色,SpringBoot是一个非常流行的Java基于Spring框架的微... 目录一、环境搭建二、创建 Spring Boot 项目三、引入二维码生成依赖四、编写二维码生成代码五

MyBatisX逆向工程的实现示例

《MyBatisX逆向工程的实现示例》本文主要介绍了MyBatisX逆向工程的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录逆向工程准备好数据库、表安装MyBATisX插件项目连接数据库引入依赖pom.XML生成实体类、

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

Java实现MinIO文件上传的加解密操作

《Java实现MinIO文件上传的加解密操作》在云存储场景中,数据安全是核心需求之一,MinIO作为高性能对象存储服务,支持通过客户端加密(CSE)在数据上传前完成加密,下面我们来看看如何通过Java... 目录一、背景与需求二、技术选型与原理1. 加密方案对比2. 核心算法选择三、完整代码实现1. 加密上

Java使用WebView实现桌面程序的技术指南

《Java使用WebView实现桌面程序的技术指南》在现代软件开发中,许多应用需要在桌面程序中嵌入Web页面,例如,你可能需要在Java桌面应用中嵌入一部分Web前端,或者加载一个HTML5界面以增强... 目录1、简述2、WebView 特点3、搭建 WebView 示例3.1 添加 JavaFX 依赖3