CXF Spring开发WebService,基于SOAP和REST方式
版本CXF2.6.9
添加的包文件
这个版本的不可在Tomcat7上运行,会出错。
配置文件
applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:jaxws="http://cxf.apache.org/jaxws"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
- <import resource="classpath:META-INF/cxf/cxf.xml" />
- <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
- <jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld" />
- <!-- http://localhost:7777/CXFDemo/services -->
- <!-- http://localhost:7777/CXFDemo/services//HelloWorld?wsdl -->
- </beans>
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">
- <display-name></display-name>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>WEB-INF/applicationContext.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>/services/*</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
接口及实现类文件
- package demo.spring.service;
- import javax.jws.WebService;
- @WebService
- public interface HelloWorld {
- String sayHi(String text);
- }
- package demo.spring.service;
- import javax.jws.WebService;
- @WebService(endpointInterface="demo.spring.service.HelloWorld")
- public class HelloWorldImpl implements HelloWorld {
- @Override
- public String sayHi(String text) {
- System.out.println("sayHi called");
- return "Hello " + text;
- }
- }
----------------
发布REST风格的webservice
定义接口和类
- package dcec.rdd;
- import javax.ws.rs.GET;
- import javax.ws.rs.Path;
- import javax.ws.rs.PathParam;
- import javax.ws.rs.Produces;
- import javax.ws.rs.core.MediaType;
- @Path("")
- public interface RestHelloWorld {
- @GET
- @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
- @Path("/say/{name}")
- public String say(@PathParam("name")String name);
- @GET
- @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
- @Path("/getUser/{id}")
- public List<User> getUser(@PathParam("id")String id);
- @GET
- @Path("/login")
- public String login(@QueryParam("name")String name,@QueryParam("ps")String ps);
- }
- package dcec.rdd;
- import java.util.ArrayList;
- import java.util.List;
- import javax.ws.rs.PathParam;
- //@Service("rest_HelloWorldImpl")
- public class RestHelloWorldImpl implements RestHelloWorld {
- public String say(String name) {
- System.out.println(name + ", welcome");
- return name+", welcome you.";
- }
- public List<User> getUser(String id){
- List<User> list=new ArrayList<User>();
- User user=new User();
- user.setId(id);
- user.setName("chen");
- list.add(user);
- User user1=new User();
- user1.setId(id);
- user1.setName("chen shi");
- list.add(user1);
- User user2=new User();
- user2.setId(id);
- user2.setName("chen shi cheng");
- list.add(user2);
- return list;
- }
- public String login(String name,String ps){
- return "name: "+name+", password:"+ps;
- }
- }
- package dcec.rdd;
- import javax.xml.bind.annotation.XmlElement;
- import javax.xml.bind.annotation.XmlRootElement;
- @XmlRootElement(name="user")
- public class User {
- private String id;
- private String name;
- @XmlElement(name="ID")
- public String getId(){
- return id;
- }
- public void setId(String id){
- this.id=id;
- }
- @XmlElement(name="NAME")
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name=name;
- }
- }
拦截器自定义
- package dcec.rdd;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.cxf.binding.xml.XMLFault;
- import org.apache.cxf.interceptor.Fault;
- import org.apache.cxf.message.Message;
- import org.apache.cxf.phase.AbstractPhaseInterceptor;
- import org.apache.cxf.phase.Phase;
- import org.apache.cxf.transport.http.AbstractHTTPDestination;
- public class HelloInInterceptor extends AbstractPhaseInterceptor<Message> {
- public HelloInInterceptor(String phase) {
- super(phase);
- }
- public HelloInInterceptor(){
- super(Phase.RECEIVE);
- }
- public void handleMessage(Message message)throws Fault{
- HttpServletRequest request=(HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
- System.out.println("请求的字符集编码 "+request.getCharacterEncoding());
- System.out.println("请求的URL "+request.getRequestURL());
- // try {
- // request.setCharacterEncoding("unicode");
- // } catch (UnsupportedEncodingException e1) {}
- String ip=request.getRemoteAddr();
- System.out.println(request.getRequestURI());
- Enumeration<String> e=request.getHeaderNames();
- while(e.hasMoreElements()){
- String str=e.nextElement();
- System.out.println(str+" "+request.getHeader(str));
- }
- System.out.println(ip);
- // XMLFault xmlFault=new XMLFault("异常");
- // xmlFault.setStatusCode(4000);
- // xmlFault.setMessage("wrong user and password");
- //
- // if(true)
- // throw new Fault(xmlFault);
- // System.out.println("****************************进入拦截器*********************************************");
- // System.out.println(message);
- //
- // if (message.getDestination() != null) {
- // System.out.println(message.getId() + "#"+message.getDestination().getMessageObserver());
- // }
- // if (message.getExchange() != null) {
- // System.out.println(message.getExchange().getInMessage() + "#"+ message.getExchange().getInFaultMessage());
- // System.out.println(message.getExchange().getOutMessage() + "#"+ message.getExchange().getOutFaultMessage());
- // }
- // System.out.println("**************************离开拦截器**************************************");
- }
- }
- package dcec.rdd;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.cxf.binding.xml.XMLFault;
- import org.apache.cxf.interceptor.Fault;
- import org.apache.cxf.message.Message;
- import org.apache.cxf.phase.AbstractPhaseInterceptor;
- import org.apache.cxf.phase.Phase;
- import org.apache.cxf.transport.http.AbstractHTTPDestination;
- public class HelloOutInterceptor extends AbstractPhaseInterceptor<Message> {
- public HelloOutInterceptor(String phase) {
- super(phase);
- }
- public HelloOutInterceptor(){
- super(Phase.SEND);
- }
- public void handleMessage(Message message)throws Fault{
- HttpServletResponse response=(HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE);
- response.setCharacterEncoding("utf-8");
- System.out.println("**************************离开拦截器**************************************");
- }
- }
配置文件
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- 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.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-extension-soap.xml" />
- <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
- <jaxws:endpoint id="helloService" implementor="dcec.server.HelloServiceImpl" address="/helloService" />
- <jaxws:endpoint id="PrintNameService" implementor="dcec.server.PrintNameImpl" address="/PrintNameService" />
- <bean id="restHelloWorldImpl" class="dcec.rdd.RestHelloWorldImpl" />
- <bean id="helloInInterceptor" class="dcec.rdd.HelloInInterceptor"/>
- <bean id="helloOutInterceptor" class="dcec.rdd.HelloOutInterceptor"/>
- <jaxrs:server id="restHelloWorld" address="/v1">
- <jaxrs:serviceBeans>
- <ref bean="restHelloWorldImpl" />
- </jaxrs:serviceBeans>
- <!--拦截器,请求和响应-->
- <jaxrs:inInterceptors>
- <ref bean="helloInInterceptor"/>
- </jaxrs:inInterceptors>
- <jaxrs:outInterceptors>
- <ref bean="helloOutInterceptor"/>
- </jaxrs:outInterceptors>
- <jaxrs:extensionMappings>
- <entry key="json" value="application/json" />
- <entry key="xml" value="application/xml" />
- </jaxrs:extensionMappings>
- </jaxrs:server>
- </beans>
访问地址测试
http://localhost:7777/CXFDemo/ws/
http://localhost:7777/CXFDemo/ws/v1/say/33
http://localhost:7777/CXFDemo/ws/v1/getUser/23/33?_type=json
http://localhost:7777/CXFDemo/ws/v1/getUser/23/33?_type=xml //默认的方式xml
http://192.168.133.179:7777/CXFDemo/ws/v1/login?name=chen&ps=123
=========================================================
POJO类的参数
http://blog.csdn.net/unei66/article/details/12324353
- import javax.xml.bind.annotation.XmlRootElement;
- @XmlRootElement(name = "book")
- public class Book {
- private int bookId;
- private String bookName;
- public int getBookId() {
- return bookId;
- }
- public void setBookId(int bookId) {
- this.bookId = bookId;
- }
- public String getBookName() {
- return bookName;
- }
- public void setBookName(String bookName) {
- this.bookName = bookName;
- }
- public String toString(){
- return "[bookId:"+bookId+"],[bookName:"+bookName+"]";
- }
- }
- /**
- * JSON提交
- * url:http://localhost:9000/rest/json/addBook
- * Json format:{"book":{"bookId":123,"bookName":"newBook"}}
- */
- @POST
- @Path("/addBook")
- @Consumes("application/json")
- public Response addBook(Book book);
- /**
- * Json提交2
- * url:http://localhost:9000/rest/json/addBooks
- * Json format:{"book":[{"bookId":123,"bookName":"newBook"},{"bookId":456,"bookName":"newBook2"}]}
- */
- @POST
- @Path("/addBooks")
- @Consumes("application/json")
- public Response addBooks(List<Book> books);
- @Override
- public Response addBook(Book book) {
- System.out.println("addBook is called...");
- return Response.ok().entity(book.toString()).build();
- }
- @Override
- public Response addBooks(List<Book> books) {
- System.out.println("addBooks is called...");
- return Response.ok().entity("ok").build();
- }
测试html 提交
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="http://192.168.133.179:8080/ychserver/ws/v1/file/imageupload" method="post" enctype="multipart/form-data" >
- <p>id:<input type="text" name="id"/></p>
- <p>name:<input type="text" name="name"/></p>
- <p>image:<input type="file" name="file"/>
- <p><input type="submit" value="sub"/></p>
- </form>
- </body>
- </html>
CXF Spring开发WebService,基于SOAP和REST方式的更多相关文章
- CXF Spring开发WebService,基于SOAP和REST方式 【转】
官网示例 http://cxf.apache.org/docs/writing-a-service-with-spring.html http://cxf.apache.org/docs/jax-rs ...
- WebService系列二:使用JDK和CXF框架开发WebService
一.使用JDK开发WebService 服务端程序创建: 1.新建一个JDK开发webservice的服务端maven项目JDKWebServiceServer 2. 定义一个接口,使用@WebSer ...
- 使用CXF+Spring发布WebService,启动报错
使用CXF+Spring发布WebService,启动报错,日志如下: 五月 12, 2017 9:01:37 下午 org.apache.tomcat.util.digester.SetProper ...
- WEBSERVICE之CXF框架开发webservice
之前学习了使用jdk开发webservice服务,现在开始学习使用框架(cxf)开发webservice. 1.准备工作 A.使用cxf开发webservice服务,需要用到apache-cxf-3. ...
- Axis2开发WebService客户端 的3种方式
Axis2开发WebService客户端 的3种方式 在dos命令下 wsdl2java -uri wsdl的地址(网络上或者本地) -p com.whir.ezoffi ...
- sping练习,在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台。
相关 知识 >>> 相关 练习 >>> 实现要求: 在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台.要 ...
- spring练习,使用Eclipse搭建的Spring开发环境,使用set注入方式为Bean对象注入属性值并打印输出。
相关 知识 >>> 相关 练习 >>> 实现要求: 使用Eclipse搭建的Spring开发环境,使用set注入方式为Bean对象注入属性值并打印输出.要求如下: ...
- CXF整合Spring开发WebService
刚开始学webservice时就听说了cxf,一直没有尝试过,这两天试了一下,还不错,总结如下: 要使用cxf当然是要先去apache下载cxf,下载完成之后,先要配置环境变量,有以下三步: 1.打开 ...
- JAX-WS + Spring 开发webservice
通过几天的时间研究了下使用jax-ws来开发webservice,看了网上的一些资料总结出jax-ws的开发大概分为两种. 以下项目使用的spring3.0,jar包可以到官网下载 第一种:使用独立的 ...
随机推荐
- 2、html补充
今天补充几个html标签 <body>内常用标签 1.<div>和<span> <div></div> : <div>只是一个块 ...
- C# Activator
需要动态的创建一个实例模型的时候,就用Activator.CreateInstance(Type type);如果是明确的知道要创建哪个实例的模型,就可以用 new C#在类工厂中动态创建类的实例,所 ...
- C#保存文件为无BOM的utf8格式
如图所示,发现用C#的 File.WriteAllLines 方法,无论怎么设置,最终生成的文件都是 PC utf8,也就是CRLF,用SVN进行提交的时候,显示左侧为utf8,右侧为utf8 BOM ...
- .net core使用配置文件
.net core使用配置文件 在 .net core中,配置文件的读取是通过IConfiguration来提供的,程序集是Microsoft.Extensions.Configuration,对应的 ...
- Spark2.3(四十三):Spark Broadcast总结
为什么要使用广播(broadcast)变量? Spark中因为算子中的真正逻辑是发送到Executor中去运行的,所以当Executor中需要引用外部变量时,需要使用广播变量.进一步解释: 如果exe ...
- Django 数据表更改
Django 数据表更改 « Django 开发内容管理系统(第四天) Django 后台 » 我们设计数据库的时候,早期设计完后,后期会发现不完善,要对数据表进行更改,这时候就要用到本节的知识. D ...
- Android 获取Activity当前view
View cv = getWindow().getDecorView(); 来自为知笔记(Wiz)
- [Python设计模式] 第15章 如何兼容各种DB——抽象工厂模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 如何让一个程序,可以灵活替换数据库? 基础版本 class User(): ...
- 为什么虚拟 dom 会提高性能?
虚拟 dom 相当于在 js 和真实 dom 中间加了一个缓存,利用 dom diff 算法避免了没有必要的 dom 操作,从而提高性能.用 JavaScript 对象结构表示 DOM 树的结构:然后 ...
- 阿里云物联网平台体验(树莓派+Nodejs篇)
我们在<阿里云物联网平台体验(树莓派+python篇)>里,写了通过Python语言开发云到端的物联网程序,本篇文章将介绍通过nodejs来实现类似功能. 同样在阿里云官方文档里已经有了一 ...