Spring整合CXF webservice restful 例項
webservice restful介面跟soap協議的介面實現大同小異,只是在提供服務的類/介面的註解上存在差異,具體看下面的程式碼,然後自己對比下就可以了。
用到的基礎類
User.java
[原始碼]- @XmlRootElement(name="User")
- publicclass User {
- private String userName;
- private String sex;
- private int age;
-
public User(String userName, String sex, int age) {
- super();
- this.userName = userName;
- this.sex = sex;
- this.age = age;
- }
- public User() {
- super();
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
-
this.userName = userName;
- }
- public String getSex() {
- return sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
-
publicstatic
- System.setProperty("http.proxySet", "true");
- System.setProperty("http.proxyHost", "192.168.1.20");
- System.setProperty("http.proxyPort", "8080");
- URL url = new URL("http://www.baidu.com");
- URLConnection con =url.openConnection();
- System.out.println(con);
- }
- }
接下來是服務提供類,PhopuRestfulService.java
[原始碼]- @Path("/phopuService")
- publicclass PhopuRestfulService {
- Logger logger = Logger.getLogger(PhopuRestfulServiceImpl.class);
- @GET
- @Produces(MediaType.APPLICATION_JSON) //指定返回資料的型別 json字串
- //@Consumes(MediaType.TEXT_PLAIN) //指定請求資料的型別 文字字串
- @Path("/getUser/{userId}")
- public User getUser(@PathParam("userId")String userId) {
- this.logger.info("Call getUser() method...."+userId);
- User user = new User();
- user.setUserName("中文");
- user.setAge(26);
- user.setSex("m");
- return user;
- }
- @POST
- @Produces(MediaType.APPLICATION_JSON) //指定返回資料的型別 json字串
- //@Consumes(MediaType.TEXT_PLAIN) //指定請求資料的型別 文字字串
- @Path("/getUserPost")
- public User getUserPost(String userId) {
- this.logger.info("Call getUserPost() method...."+userId);
- User user = new User();
- user.setUserName("中文");
- user.setAge(26);
- user.setSex("m");
- return user;
- }
- }
web.xml配置,跟soap協議的介面一樣
[原始碼]- <!-- CXF webservice 配置 -->
- <servlet>
- <servlet-name>cxf-phopu</servlet-name>
- <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>cxf-phopu</servlet-name>
- <url-pattern>/services/*</url-pattern>
- </servlet-mapping>
Spring整合配置
[原始碼]- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:jaxws="http://cxf.apache.org/jaxws"
- xmlns:jaxrs="http://cxf.apache.org/jaxrs"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
- http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
- <import resource="classpath:/META-INF/cxf/cxf.xml" />
- <import resource="classpath:/META-INF/cxf/cxf-servlet.xml" />
- <import resource="classpath:/META-INF/cxf/cxf-extension-soap.xml" />
- <!-- 配置restful json 解析器 , 用CXF自帶的JSONProvider需要注意以下幾點
- -1、dropRootElement 預設為false,則Json格式會將類名作為第一個節點,如{Customer:{"id":123,"name":"John"}},如果配置為true,則Json格式為{"id":123,"name":"John"}。
- -2、dropCollectionWrapperElement屬性預設為false,則當遇到Collection時,Json會在集合中將容器中類名作為一個節點,比如{"Customer":{{"id":123,"name":"John"}}},而設定為false,則JSon格式為{{"id":123,"name":"John"}}
- -3、serializeAsArray屬性預設為false,則當遇到Collecion時,格式為{{"id":123,"name":"John"}},如果設定為true,則格式為[{"id":123,"name":"john"}],而Gson等解析為後者
- <bean id="jsonProviders"class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
- <property name="dropRootElement" value="true" />
- <property name="dropCollectionWrapperElement" value="true" />
- <property name="serializeAsArray" value="true" />
- </bean>
- -->
- <!-- 服務類 -->
- <bean id="phopuService"class="com.phopu.service.PhopuRestfulService" />
- <jaxrs:server id="service" address="/">
- <jaxrs:inInterceptors>
- <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
- </jaxrs:inInterceptors>
- <!--serviceBeans:暴露的WebService服務類-->
- <jaxrs:serviceBeans>
- <ref bean="phopuService" />
- </jaxrs:serviceBeans>
- <!--支援的協議-->
- <jaxrs:extensionMappings>
- <entry key="json" value="application/json"/>
- <entry key="xml" value="application/xml" />
- <entry key="text" value="text/plain" />
- </jaxrs:extensionMappings>
- <!--物件轉換-->
- <jaxrs:providers>
- <!-- <ref bean="jsonProviders" /> 這個地方直接用CXF的物件轉換器會存在問題,當介面釋出,第一次訪問沒問題,但是在訪問服務就會報錯,等後續在研究下 -->
- <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
- </jaxrs:providers>
- </jaxrs:server>
- </beans>
客戶端呼叫示例:
對於get方式的服務,直接在瀏覽器中輸入 http://localhost:8080/phopu/services/phopuService/getUser/101010500 就可以直接看到返回的json字串
[原始碼]- {"userName":"中文","sex":"m","age":26}
客戶端呼叫程式碼如下:
[原始碼]- publicstatic void getWeatherPostTest() throws Exception{
- String url = "http://localhost:8080/phopu/services/phopuService/getUserPost";
- HttpClient httpClient = HttpClients.createSystem();
- //HttpGet httpGet = new HttpGet(url); //介面get請求,post not allowed
- HttpPost httpPost = new HttpPost(url);
- httpPost.addHeader(CONTENT_TYPE_NAME, "text/plain");
- StringEntity se = new StringEntity("101010500");
- se.setContentType("text/plain");
- httpPost.setEntity(se);
- HttpResponse response = httpClient.execute(httpPost);
- int status = response.getStatusLine().getStatusCode();
- log.info("[介面返回狀態嗎] : " + status);
- String weatherInfo = ClientUtil.getReturnStr(response);
- log.info("[介面返回資訊] : " + weatherInfo);
- }
客戶端呼叫返回資訊如下:
ClientUtil類是我自己封裝的一個讀取response返回資訊的類,encoding是UTF-8
[原始碼]- publicstatic String getReturnStr(HttpResponse response) throws Exception {
- String result = null;
- BufferedInputStream buffer = new BufferedInputStream(response.getEntity().getContent());
- byte[] bytes = new byte[1024];
- int line = 0;
- StringBuilder builder = new StringBuilder();
- while ((line = buffer.read(bytes)) != -1) {
- builder.append(new String(bytes, 0, line, HTTP_SERVER_ENCODING));
- }
- result = builder.toString();
- return result;
- }
相關推薦
Spring整合CXF webservice restful 例項
webservice restful介面跟soap協議的介面實現大同小異,只是在提供服務的類/介面的註解上存在差異,具體看下面的程式碼,然後自己對比下就可以了。 用到的基礎類 User.java [原始碼] @XmlRootElement(name="U
Spring整合cxf搭建webservice【一、服務端】
1、匯入jar包(普通web專案) 引入依賴(maven專案) <!-- webservice依賴框架CXF --> <dependency> <groupId>org.apache.cxf</groupId>
maven整合CXF WebService+Spring @Resource無法注入問題解決方法
筆者是一個出道不長的小碼農.工作中需要用的maven 結合jetty容器進行開發的前提背景下 廢話不多說直接上程式碼 更改前的web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=
在java中使用spring整合cxf實現webservice
在java中實現webservice有兩種常用的方式,一種是cxf,另一種是axis。這兩種方式的區別大家可以自己在網上找找參考一下。cxf可以與spring進行整合,是一款不錯的webservice產品。今天給大家講解一下使用spring整合cxf實現we
Spring boot 整合CXF webservice遇到的一些問題及解決,
在spring boot整合CXF開發是遇到的一些問題 以及整合方式整合過程 網上資料引入cxf-spring-boot-starter-jaxws依賴即可<dependency> <groupId>org.apache.cxf&l
axis2+spring整合釋出webservice服務
1.環境搭建,準備相應環境jar包 axis2-1.6.0.0下載地址: http://axis.apache.org/axis2/java/core/download.cgi spring相關jar包下載地址
Spring 整合CXF需要的配置及處理步驟
CXF配置 1.web.xml 配置 <!--Spring MVC是通過DispatcherServlet來載入Spring配置檔案的,因此不需要在web.xml中配置ContextLoaderListener。 但是CXF卻需要通過ContextLoaderLis
activiti自定義流程之Spring整合activiti-modeler5.16例項(六):啟動流程
1.啟動流程並分配任務是單個流程的正式開始,因此要使用到runtimeService介面,以及相關的啟動流程的方法。我習慣於用流程定義的key啟動,因為有多個版本的流程定義時,用key啟動預設會使用最新版本。同時,因為啟動中查詢了流程部署時xml檔案中流程節點的資訊,也用
spring 整合CXF框架拋異常
Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListenerorg.springframework.beans.fa
activiti自定義流程之Spring整合activiti-modeler5.16例項(二):建立流程模型
1.maven導包,這裡就沒有什麼多的好說了,直接程式碼: <dependencies> <dependency> <groupId>junit</groupId> <artifact
Spring整合CXF 客戶端及服務端
伺服器端: 1.新建Web專案,例如webws,匯入cxf-2.0.7/lib下的jar包和spring2.5的包,因為cxf支援spring,因此它自帶有sping的一些核心包,為了以後擴充套件,保險起見都一起匯入吧。。 2.新建一個服務介面IHelloWorld.java
spring整合cxf之SOAP方式
簡介 Apache CXF 是一個開源的 Services 框架,CXF 幫助您利用 Frontend 程式設計 API 來構建和開發 Services , 像 JAX-WS 。比如:HTTP
WebService學習之旅(三)JAX-WS與Spring整合釋出WebService
Spring本身就提供了對JAX-WS的支援,有興趣的讀者可以研究下Spring的Spring-WS專案,專案地址: http://docs.spring.io/spring-ws/sites/1.5/downloads/releases.html 基於Sp
activiti自定義流程之Spring整合activiti-modeler5.16例項(五):流程定義列表
1.流程定義依舊屬於流程資源,因此查詢流程定義也還是使用repositoryService進行操作 2.後臺業務程式碼, (1)自定義的流程定義實體類:package model; pub
activiti自定義流程之Spring整合activiti-modeler5.16例項(一):環境搭建
專案中需要整合activiti-modeler自定義流程,找了很多資料後,終於成功的跳轉到activiti-modeler流程設計介面,以下是記錄: 一、整合基礎:eclipse4.4.1、tomcat7、jdk1.7、mysql5.6.25、maven3.2.5、acti
spring 整合cxf 第二彈(經過測試)以xml格式進行資料互動
為方便打大家學習以及應用,還是從配置檔案、jar、bean開始扯起。。。。。。 1,web.xml 配置檔案基本配置 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi=
使用CXF與Spring整合實現RESTFul WebService
以下引用與網路中!!! 一種軟體架構風格,設計風格而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和伺服器互動類的軟體。基於這個風格設計的軟體可以更簡潔,更有層次,更易於實現快取等機制。 &nbs
WebService Spring整合Jax-rs規範 使用CXF框架Restful的程式設計風格 編寫服務端
前提是專案SSM框架搭建好。 搭建cxf框架, 一、首先,將框架所需要的jar匯入,pom.xml檔案中 <!-- cxf 進行rs開發 必須匯入 --> <dependency> <groupId>org.apache.cx
一個CXF整合SPRING的WEBSERVICE完整例項
1 首先準備以下JAR包activation.jarcommons-logging-1.1.1.jarcxf-2.5.6.jarjaxb-api-2.2.1.jarjaxb-impl-2.1.3.jarjaxws-api-2.2.8.jarneethi-3.0.2.jarow2
CXF WebService整合Spring
部分 控制 utf 內容 使用 mes classpath html row 首先,CXF和spring整合需要準備如下jar包文件: 這邊我是用Spring的jar包是Spring官方提供的,並沒有使用CXF中的Spring的jar文件。 添加這麽多文件後,首先在web