spring +cxf(Apache CXF = Celtix + XFire) 发布webservice 接口
1.soap形式,客户端访问服务端采用soap协议,
2.restful 形式,客户端访问服务端采用http协议,即采用http 的get/post请求就能获取资源。接口的数据返回形式有xml 格式和json 格式两种。
3.新版本的spring mvc 支持 http 接口数据格式自动转json(直接controller里面方法加注解)。
一.所需的jar包
<!--spring + cxf -->
<--jaxrs json转换-->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<!- webservice cxf 依赖包 -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.4</version>
</dependency>
二.xml配置
1.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 在Web.xml中声明CXF监听器
<servlet-mapping>下的<url-pattern>指明了服务访问地址的形式,
“/*”代表URL地址中,包名称后直接跟服务endpoint地址,
若指明<url-pattern>为/webservice/*,
则URL为“包名/webservice/endpoing?wsdl”。
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-server.xml</param-value>
</context-param>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<!-- 编码设置-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.applicationContext-server.xml(作为spring+cxf配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
<!--加上约束文档声明-->
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-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">
<!--引入其他的spring 相关配置-->
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!--soap形式的接口-->
<jaxws:endpoint id="helloWorld" implementor="com.webservice.server.impl.MyHelloworldimpl" address="/HelloWorld"/>
<!--restful形式的接口-->
<bean id="restSample" class="com.webservice.rest.impl.RestSampleImpl"/>
<!--拦截器-->
<bean id="encodingLoggingInInterceptor" class="com.webservice.interceptor.EncodingLoggingInInterceptor"/>
<bean id="outLoggingInterceptor" class="com.webservice.interceptor.EncodingLoggingOutInterceptor"/>
<!--json 转换-->
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
<bean id="mytest" class="com.webservice.rest.impl.RestSampleImpl"/>
<!-- 客户端通过这个地址来访问WebService -->
<jaxrs:server id="restServiceContainer" address="/rest">
<jaxrs:serviceBeans>
<ref bean="restSample" />
<ref bean="mytest" />
</jaxrs:serviceBeans>
<jaxrs:inInterceptors>
<ref bean="encodingLoggingInInterceptor"/>
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<ref bean="outLoggingInterceptor"/>
</jaxrs:outInterceptors>
<jaxrs:extensionMappings>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</jaxrs:extensionMappings>
<jaxrs:providers>
<ref bean="jsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
三.java 代码
bean 类:
user.java
package com.webservice.bean;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="userinfo")
public class User implements Serializable{
private static final long serialVersionUID = 677484458789332877L;
private int id;
private String name;
private String address;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.id+","+this.name+","+this.email+","+this.address;
}
}
server类:两种方式soap 和 restful
1.soap方式:
MyHelloworld.java(接口)
package com.webservice.server;
import javax.jws.WebService;
/**
* @author admin
* @WebService”标记表示该接口是一个WebService服务
* @WebMethod”表示表示以下方法为WebService服务中的方法
* @WebParam(name="username")”表示方法中的参数
* username属性限制了参数的名称,若没有指定该属性,参数将被重命名
*/
@WebService
public interface MyHelloworld {
/**@WebMethod
public String sayHello(@WebParam(name="username") String username);
*/
public String sayhello();
}
MyHelloworldimpl.java(实现类)
package com.webservice.server.impl;
import com.webservice.server.MyHelloworld;
/**
* @author admin
* webservice 服务实现类
*/
public class MyHelloworldimpl implements MyHelloworld{
@Override
public String sayhello() {
// TODO Auto-generated method stub
return "helloworld";
}
}
2.restful方式:
RestSample.java
package com.webservice.rest;
import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.webservice.bean.User;
/*
注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。
@Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。
@GET:这意味着以下方法可以响应 HTTP GET 方法。
@Produces:以纯文本方式定义响应内容 MIME 类型。
@Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。
@Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。
@PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。
@Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。
*/
/**
*
* @author
*/
@WebService
@Path(value="/sample")
public interface RestSample {
@GET
@Path("/get/test")
// @Consumes("application/json")
//编码直接在后面加,其他方法效果不行。
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public User doGet();
}
RestSampleImpl.java
package com.webservice.rest.impl;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.webservice.bean.User;
import com.webservice.rest.RestSample;
@Path(value="/sample")
public class RestSampleImpl implements RestSample{
@GET
@Path("/get/test")
// @Consumes("application/json")
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public User doGet() {
User user = new User();
user.setEmail("123@qq.com");
user.setId(1);
user.setAddress("花果山");
user.setName("hh");
return user;
}
}
输入过滤器
EncodingLoggingInInterceptor.java
package com.webservice.interceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.message.Message;
/**
* @author admin
*
*/
public class EncodingLoggingInInterceptor extends LoggingInInterceptor{
@Override
public void handleMessage(Message message) throws Fault {
// 这里写过滤处理
String encoding = System.getProperty("file.encoding");
System.out.println("myloginenconding:"+encoding);
super.handleMessage(message);
}
}
输出过滤器
EncodingLoggingOutInterceptor.java
package com.webservice.interceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.message.Message;
/**
* @author admin
*
*/
public class EncodingLoggingOutInterceptor extends LoggingOutInterceptor{
@Override
public void handleMessage(Message message) throws Fault {
String encoding = System.getProperty("file.encoding");
System.out.println("myenconding:"+encoding);
super.handleMessage(message);
}
}
四.运行结果
1.
2.
五.原理不详细解释了。