Java Web Service-CXF -基于Restful的Web服务

Java Web Service-CXF

-基于Restful的Web服务

[email protected]

2015年11月13日

 

1 目标:简单的Web服务访问协议。

2 原理:将Http请求转化为Web服务。

3 流程:

3.1 创建DynamicWeb Project。

3.2 安装CXF库(自带Spring库):下载CXF,解压后将lib下所有内容copy到web-inf/lib下。将库加入ClassPath。

3.3 配置web.xml:指定Spring为Web监听类,设置CXF的Servlet。

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">

 <display-name>CXFDemo</display-name>

    <listener>

        <listener-class>

            org.springframework.web.context.ContextLoaderListener

        </listener-class>

    </listener>

     <servlet>

        <servlet-name>CXFServlet</servlet-name>

         <servlet-class>

             org.apache.cxf.transport.servlet.CXFServlet

         </servlet-class>

     </servlet>

     <servlet-mapping>

        <servlet-name>CXFServlet</servlet-name>

        <url-pattern>/services/*</url-pattern>

     </servlet-mapping>

</web-app>

3.4 配置Spring:添加jaxrs命名空间,设置服务Server。

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns:jaxrs="http://cxf.apache.org/jaxrs"

      xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd">

      <import resource="classpath:META-INF/cxf/cxf.xml"/>

      <importresource="classpath:META-INF/cxf/cxf-extension-soap.xml" />

      <importresource="classpath:META-INF/cxf/cxf-servlet.xml" />

      <jaxrs:serverid="rs1" address="/rs">

           <jaxrs:serviceBeans>

                 <beanclass="lee.HelloWorldImpl" />

           </jaxrs:serviceBeans>

      </jaxrs:server>

</beans>

3.5 创建WebService的服务Bean类:使用@Path标记路径,@GET标记请求类型,@PathParam标记参数。

//IHelloWorld.java

package lee;

 

public interface IHelloWorldextends java.rmi.Remote {

    public java.lang.String sayHello();

    public java.lang.String say(String arg0);

}

 

//HelloWorldImpl.java

package lee;

 

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

 

@Path("/")

public class HelloWorldImplimplements IHelloWorld {

 

      @Override

      @GET

      @Path("/say/{msg}")

      public String say(@PathParam("msg")String msg) {

           // TODO Auto-generated method stub

           return "Hello"+msg;

      }

 

      @Override

      @GET

      @Path("/sayhi")

      public String sayHello() {

           // TODO Auto-generated method stub

           return "Hello";

      }

 

}

3.6 调用WebService的服务:CXFServlet路径+server路径+服务路径+方法路径+参数路径

http://192.168.41.131:8080/CXFDemo/services/rs/sayhi

http://192.168.41.131:8080/CXFDemo/services/rs/say/xx

4 方法:Restful+JAX-RS。

4.1 REST:REprestation Status Transfor,表现对象状态转换。是一种网络设计理念。

将所有不同表现形式的资源、服务抽象为资源并分配URI。

简化Web服务协议(SOAP协议太过复杂,且只支持POST,无法使用GET获取)。

4.2 Http协议与Java的映射:JAX-RS:Restful的实现。

使用注释标记各种服务属性。

HTTP请求方式:@PUT,@GET,@POST,@DELETE。

HTTP请求的MIME类型:@Consumers

HTTP返回的MIME类型:@Produces

HTTP请求参数来源:@PathParam,@QueryParam,@HeaderParam,@CookieParam,@MatrixParam,@FormParam。

HTTP请求参数默认值:@DefaultValue。

参考:http://developer.51cto.com/art/200908/141825.htm

http://baike.baidu.com/link?url=Z5A9ifUJH9GLwJR_JwjbhOUW2LUpOImOvB9hIosMwojDmKWQ7-eQmio6kOIVXAB59We2xJFdvhPSKxZP9hRHWq

4.3 JAX-RS实现:CXF

CXF实现JAX-RS。

5 方法:基于Restful的Web服务客户端

5.1 目标:调用基于Restful的Web服务。

5.2 原理:将Http响应转化为Java对象。

5.3 流程:配置Web.xml,配置Spring,调用Web服务。

5.3.1配置Web.xml

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">

      <display-name>CXFClientDemo</display-name>

      <listener>

        <listener-class>

            org.springframework.web.context.ContextLoaderListener

        </listener-class>

      </listener>

      <servlet>

        <servlet-name>h</servlet-name>

         <servlet-class>

              lee.Client

         </servlet-class>

     </servlet>

     <servlet-mapping>

         <servlet-name>h</servlet-name>

        <url-pattern>/client/h</url-pattern>

     </servlet-mapping>

</web-app>

5.3.2配置Spring:如果无Bean配置,也需要applicationContext.xml文件。

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

5.3.3调用Web服务:使用WebClient转化为Java对象。

//Clent.java

package lee;

 

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.apache.cxf.jaxrs.client.WebClient;

import org.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public class Client extendsHttpServlet {

      public void service(HttpServletRequest reqest,HttpServletResponse response) {

           WebApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           WebClientclient=WebClient.create("http://192.168.41.131:8080/CXFDemo/services/rs/whosay/xx?msg=yy"); 

           String strResp=(String)client.accept("text/plain").get(String.class);    

        System.out.println(strResp);  

      }

}

5.4 方法:Client的使用

Client是Web服务的代理,指定服务的地址,然后使用get()得到服务的结果,转化为指定的结果类型。

5.4.1配置Client的SpringBean:目标是通过Spring管理Client。

5.4.1.1  增加JAX-RS命名空间:可以使用jaxrs:client标签。

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:jaxrs="http://cxf.apache.org/jaxrs"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd">

5.4.1.2  创建客户端Bean:指定客户端的地址,web服务类为org.apache.cxf.jaxrs.client.WebClient生成代理。

      <jaxrs:clientid="webClient"address="http://192.168.41.131:8080/CXFDemo/services/rs/whosay/xx?msg=yy"

           serviceClass="org.apache.cxf.jaxrs.client.WebClient">

           <jaxrs:headers>

                 <entrykey="Accept" value="text/plain" />

           </jaxrs:headers>

      </jaxrs:client>

5.4.1.3  调用客户端Bean:直接调用客户端Bean,使用get()得到结果并转换为指定类型。

      WebClientclient=ctx.getBean("webClient",WebClient.class);

            String strResp=client.get(String.class);

5.4.2创建客户端并调用:不使用Spring管理,手动创建客户端

           WebClientclient=WebClient.create("http://192.168.41.131:8080/CXFDemo/services/rs/whosay/xx?msg=yy"); 

           StringstrResp=(String)client.accept("text/plain").get(String.class);    

 

5.5 示例:使用SpringBean配置客户端

参考:http://cxf.apache.org/docs/jax-rs-client-api.html

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">

      <display-name>CXFClientDemo</display-name>

      <listener>

        <listener-class>

            org.springframework.web.context.ContextLoaderListener

        </listener-class>

      </listener>

      <servlet>

        <servlet-name>h</servlet-name>

         <servlet-class>

              lee.Client

         </servlet-class>

     </servlet>

     <servlet-mapping>

         <servlet-name>h</servlet-name>

        <url-pattern>/client/h</url-pattern>

     </servlet-mapping>

</web-app>

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:jaxrs="http://cxf.apache.org/jaxrs"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd">

      <jaxrs:clientid="webClient"address="http://192.168.41.131:8080/CXFDemo/services/rs/whosay/xx?msg=yy"

           serviceClass="org.apache.cxf.jaxrs.client.WebClient">

           <jaxrs:headers>

                 <entrykey="Accept" value="text/plain" />

           </jaxrs:headers>

      </jaxrs:client>

</beans>

//Clent.java

package lee;

 

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

import org.apache.cxf.jaxrs.client.WebClient;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public class Client extendsHttpServlet {

      public void service(HttpServletRequest reqest,HttpServletResponse response) {

           WebApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(getServletContext());

 

           WebClientclient=ctx.getBean("webClient",WebClient.class);

            StringstrResp=client.get(String.class);

   System.out.println(strResp);  

      }

}

6 示例:

 

你可能感兴趣的:(webservice,javaee,CXF,Restful,web服务)