CXF Spring开发WebService,基于SOAP和REST方式

版本CXF2.6.9

添加的包文件

这个版本的不可在Tomcat7上运行,会出错。

配置文件

applicationContext.xml

[html] view plain copy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:jaxws="http://cxf.apache.org/jaxws"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
  8. <import resource="classpath:META-INF/cxf/cxf.xml" />
  9. <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  10. <jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld" />
  11. <!-- http://localhost:7777/CXFDemo/services -->
  12. <!-- http://localhost:7777/CXFDemo/services//HelloWorld?wsdl -->
  13. </beans>

web.xml

[html] view plain copy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  7. <display-name></display-name>
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>WEB-INF/applicationContext.xml</param-value>
  11. </context-param>
  12. <listener>
  13. <listener-class>
  14. org.springframework.web.context.ContextLoaderListener
  15. </listener-class>
  16. </listener>
  17. <servlet>
  18. <servlet-name>CXFServlet</servlet-name>
  19. <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  20. <load-on-startup>1</load-on-startup>
  21. </servlet>
  22. <servlet-mapping>
  23. <servlet-name>CXFServlet</servlet-name>
  24. <url-pattern>/services/*</url-pattern>
  25. </servlet-mapping>
  26. <welcome-file-list>
  27. <welcome-file>index.jsp</welcome-file>
  28. </welcome-file-list>
  29. </web-app>

接口及实现类文件

[java] view plain copy

  1. package demo.spring.service;
  2. import javax.jws.WebService;
  3. @WebService
  4. public interface HelloWorld {
  5. String sayHi(String text);
  6. }

[java] view plain copy

  1. package demo.spring.service;
  2. import javax.jws.WebService;
  3. @WebService(endpointInterface="demo.spring.service.HelloWorld")
  4. public class HelloWorldImpl implements HelloWorld {
  5. @Override
  6. public String sayHi(String text) {
  7. System.out.println("sayHi called");
  8. return "Hello " + text;
  9. }
  10. }

----------------

发布REST风格的webservice

定义接口和类

[java] view plain copy

  1. package dcec.rdd;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.Path;
  4. import javax.ws.rs.PathParam;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. @Path("")
  8. public interface RestHelloWorld {
  9. @GET
  10. @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
  11. @Path("/say/{name}")
  12. public String say(@PathParam("name")String name);
  13. @GET
  14. @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
  15. @Path("/getUser/{id}")
  16. public List<User> getUser(@PathParam("id")String id);
  17. @GET
  18. @Path("/login")
  19. public String login(@QueryParam("name")String name,@QueryParam("ps")String ps);
  20. }

[java] view plain copy

  1. package dcec.rdd;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.ws.rs.PathParam;
  5. //@Service("rest_HelloWorldImpl")
  6. public class RestHelloWorldImpl implements RestHelloWorld {
  7. public String say(String name) {
  8. System.out.println(name + ", welcome");
  9. return name+", welcome you.";
  10. }
  11. public List<User> getUser(String id){
  12. List<User> list=new ArrayList<User>();
  13. User user=new User();
  14. user.setId(id);
  15. user.setName("chen");
  16. list.add(user);
  17. User user1=new User();
  18. user1.setId(id);
  19. user1.setName("chen shi");
  20. list.add(user1);
  21. User user2=new User();
  22. user2.setId(id);
  23. user2.setName("chen shi cheng");
  24. list.add(user2);
  25. return list;
  26. }
  27. public String login(String name,String ps){
  28. return "name: "+name+", password:"+ps;
  29. }
  30. }

[java] view plain copy

  1. package dcec.rdd;
  2. import javax.xml.bind.annotation.XmlElement;
  3. import javax.xml.bind.annotation.XmlRootElement;
  4. @XmlRootElement(name="user")
  5. public class User {
  6. private String id;
  7. private String name;
  8. @XmlElement(name="ID")
  9. public String getId(){
  10. return id;
  11. }
  12. public void setId(String id){
  13. this.id=id;
  14. }
  15. @XmlElement(name="NAME")
  16. public String getName(){
  17. return name;
  18. }
  19. public void setName(String name){
  20. this.name=name;
  21. }
  22. }

拦截器自定义

[java] view plain copy

  1. package dcec.rdd;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.Enumeration;
  4. import javax.servlet.http.HttpServletRequest;
  5. import org.apache.cxf.binding.xml.XMLFault;
  6. import org.apache.cxf.interceptor.Fault;
  7. import org.apache.cxf.message.Message;
  8. import org.apache.cxf.phase.AbstractPhaseInterceptor;
  9. import org.apache.cxf.phase.Phase;
  10. import org.apache.cxf.transport.http.AbstractHTTPDestination;
  11. public class HelloInInterceptor extends AbstractPhaseInterceptor<Message> {
  12. public HelloInInterceptor(String phase) {
  13. super(phase);
  14. }
  15. public HelloInInterceptor(){
  16. super(Phase.RECEIVE);
  17. }
  18. public void handleMessage(Message message)throws Fault{
  19. HttpServletRequest request=(HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
  20. System.out.println("请求的字符集编码  "+request.getCharacterEncoding());
  21. System.out.println("请求的URL  "+request.getRequestURL());
  22. //      try {
  23. //          request.setCharacterEncoding("unicode");
  24. //      } catch (UnsupportedEncodingException e1) {}
  25. String ip=request.getRemoteAddr();
  26. System.out.println(request.getRequestURI());
  27. Enumeration<String> e=request.getHeaderNames();
  28. while(e.hasMoreElements()){
  29. String str=e.nextElement();
  30. System.out.println(str+"   "+request.getHeader(str));
  31. }
  32. System.out.println(ip);
  33. //      XMLFault xmlFault=new XMLFault("异常");
  34. //      xmlFault.setStatusCode(4000);
  35. //      xmlFault.setMessage("wrong user and password");
  36. //
  37. //      if(true)
  38. //          throw new Fault(xmlFault);
  39. //      System.out.println("****************************进入拦截器*********************************************");
  40. //      System.out.println(message);
  41. //
  42. //      if (message.getDestination() != null) {
  43. //          System.out.println(message.getId() + "#"+message.getDestination().getMessageObserver());
  44. //      }
  45. //      if (message.getExchange() != null) {
  46. //          System.out.println(message.getExchange().getInMessage() + "#"+ message.getExchange().getInFaultMessage());
  47. //          System.out.println(message.getExchange().getOutMessage() + "#"+ message.getExchange().getOutFaultMessage());
  48. //      }
  49. //      System.out.println("**************************离开拦截器**************************************");
  50. }
  51. }

[java] view plain copy

  1. package dcec.rdd;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.Enumeration;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.apache.cxf.binding.xml.XMLFault;
  7. import org.apache.cxf.interceptor.Fault;
  8. import org.apache.cxf.message.Message;
  9. import org.apache.cxf.phase.AbstractPhaseInterceptor;
  10. import org.apache.cxf.phase.Phase;
  11. import org.apache.cxf.transport.http.AbstractHTTPDestination;
  12. public class HelloOutInterceptor extends AbstractPhaseInterceptor<Message> {
  13. public HelloOutInterceptor(String phase) {
  14. super(phase);
  15. }
  16. public HelloOutInterceptor(){
  17. super(Phase.SEND);
  18. }
  19. public void handleMessage(Message message)throws Fault{
  20. HttpServletResponse response=(HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE);
  21. response.setCharacterEncoding("utf-8");
  22. System.out.println("**************************离开拦截器**************************************");
  23. }
  24. }

配置文件

[html] view plain copy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:jaxws="http://cxf.apache.org/jaxws"
  5. xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
  9. http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
  10. <import resource="classpath:META-INF/cxf/cxf.xml" />
  11. <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
  12. <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  13. <jaxws:endpoint id="helloService" implementor="dcec.server.HelloServiceImpl" address="/helloService" />
  14. <jaxws:endpoint id="PrintNameService" implementor="dcec.server.PrintNameImpl" address="/PrintNameService" />
  15. <bean id="restHelloWorldImpl" class="dcec.rdd.RestHelloWorldImpl" />
  16. <bean id="helloInInterceptor"  class="dcec.rdd.HelloInInterceptor"/>
  17. <bean id="helloOutInterceptor" class="dcec.rdd.HelloOutInterceptor"/>
  18. <jaxrs:server id="restHelloWorld" address="/v1">
  19. <jaxrs:serviceBeans>
  20. <ref bean="restHelloWorldImpl" />
  21. </jaxrs:serviceBeans>
  22. <!--拦截器,请求和响应-->
  23. <jaxrs:inInterceptors>
  24. <ref bean="helloInInterceptor"/>
  25. </jaxrs:inInterceptors>
  26. <jaxrs:outInterceptors>
  27. <ref bean="helloOutInterceptor"/>
  28. </jaxrs:outInterceptors>
  29. <jaxrs:extensionMappings>
  30. <entry key="json" value="application/json" />
  31. <entry key="xml" value="application/xml" />
  32. </jaxrs:extensionMappings>
  33. </jaxrs:server>
  34. </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

[java] view plain copy

  1. import javax.xml.bind.annotation.XmlRootElement;
  2. @XmlRootElement(name = "book")
  3. public class Book {
  4. private int bookId;
  5. private String bookName;
  6. public int getBookId() {
  7. return bookId;
  8. }
  9. public void setBookId(int bookId) {
  10. this.bookId = bookId;
  11. }
  12. public String getBookName() {
  13. return bookName;
  14. }
  15. public void setBookName(String bookName) {
  16. this.bookName = bookName;
  17. }
  18. public String toString(){
  19. return "[bookId:"+bookId+"],[bookName:"+bookName+"]";
  20. }
  21. }

[java] view plain copy

  1. /**
  2. * JSON提交
  3. * url:http://localhost:9000/rest/json/addBook
  4. * Json format:{"book":{"bookId":123,"bookName":"newBook"}}
  5. */
  6. @POST
  7. @Path("/addBook")
  8. @Consumes("application/json")
  9. public Response addBook(Book book);
  10. /**
  11. * Json提交2
  12. * url:http://localhost:9000/rest/json/addBooks
  13. * Json format:{"book":[{"bookId":123,"bookName":"newBook"},{"bookId":456,"bookName":"newBook2"}]}
  14. */
  15. @POST
  16. @Path("/addBooks")
  17. @Consumes("application/json")
  18. public Response addBooks(List<Book> books);

[java] view plain copy

  1. @Override
  2. public Response addBook(Book book) {
  3. System.out.println("addBook is called...");
  4. return Response.ok().entity(book.toString()).build();
  5. }
  6. @Override
  7. public Response addBooks(List<Book> books) {
  8. System.out.println("addBooks is called...");
  9. return Response.ok().entity("ok").build();
  10. }

测试html 提交

[html] view plain copy

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Insert title here</title>
    6. </head>
    7. <body>
    8. <form action="http://192.168.133.179:8080/ychserver/ws/v1/file/imageupload" method="post" enctype="multipart/form-data" >
    9. <p>id:<input type="text" name="id"/></p>
    10. <p>name:<input type="text" name="name"/></p>
    11. <p>image:<input type="file" name="file"/>
    12. <p><input type="submit" value="sub"/></p>
    13. </form>
    14. </body>
    15. </html>
时间: 2024-08-07 14:24:06

CXF Spring开发WebService,基于SOAP和REST方式的相关文章

axis2+spring开发webservice服务器端

需求:开发VAC与SP间订购通知接口服务器端(SP端),给定VacSyncService_SPClient.wsdl文件 首先,官网下载axis2-1.6.2-bin.zip和axis2-1.6.2-war.zipaxis2-1.6.2-bin.zip包含axis2的jar包,工具和例子axis2-1.6.2-war.zip包含了axis2的web应用,发布web服务时,将自己的程序以特定文件结构发布到axis2的web应用的service目录中 1.根据wsdl生成服务器端代码解压axis2-

webService总结(三)——使用CXF + Spring发布webService

近些年来,Spring一直很火,许多框架都能跟Spring完美集成,CXF也不例外.下面,我就介绍一下如何使用CXF + Spring发布webService.我们还是使用前两篇博客使用的实例. 服务端: 目录结构: 这里需要的所有Spring的包,CXF的lib目录下都有. IHelloWorldServer代码: package com.test.server; import javax.jws.WebService; @WebService public interface IHelloW

WebService系列二:使用JDK和CXF框架开发WebService

一.使用JDK开发WebService 服务端程序创建: 1.新建一个JDK开发webservice的服务端maven项目JDKWebServiceServer 2. 定义一个接口,使用@WebService注解标注接口,使用@WebMethod注解标注接口中定义的所有方法 1 package com.study.webservice.ws; 2 3 import javax.jws.WebMethod; 4 import javax.jws.WebService; 5 6 /** 7 * 定义

CXF整合Spring开发WebService

刚开始学webservice时就听说了cxf,一直没有尝试过,这两天试了一下,还不错,总结如下: 要使用cxf当然是要先去apache下载cxf,下载完成之后,先要配置环境变量,有以下三步: 1.打开环境变量配置窗口,点击新建,新建%CXF_HOME%变量,值为你下载的cxf所在的目录,我的是D:\tools\apache-cxf-3.1.0 2.在Path变量中新加一句%CXF_HOME%\lib,注意要和已有的path变量用;隔开 3.在CLASSPATH中新加一句%CXF_HOME%\li

Apache CXF+Spring开发环境搭建小试

最近手上一个项目要开发webservice,而原有系统使用了spring,所以在选择框架的时候,我选择了cxf,这样在开发整合的时候就比较方便了.在搭建开发环境的过程中发现这篇文章写得比较详细,所以就搬到自己博客里,希望给自己和同行做参考. CXF 应用开发 下面就将开始我们的 CXF Web Services 的开发之旅!首先,要有一个基于 Eclipse 的开发环境:然后,我们将利用这个开发环境开发一个简单的“调查投票”示例,同时我们将解释一些 CXF 在开发中进行配置的基本方法. 开发环境

CXF+Spring搭建WebService

WebService: WebService 是一套标准,而不是一种具体的技术.不同的平台,不同的语言,大都提供了对 WebService 的开发实现. 从表面上看,Webservice 就是一个应用程序,它向外界暴露出一个能够通过 Web 进行调用的 API .也就是说,可以利用编程的方法通过 Web 来调用这个应用程序. 对 Webservice 更精确的解释 : Webservice 是建立可互操作的分布式应用程序的新平台.Webservice 平台是一套标准,它定义了应用程序如何在 We

JAX-WS + Spring 开发webservice

通过几天的时间研究了下使用jax-ws来开发webservice,看了网上的一些资料总结出jax-ws的开发大概分为两种. 以下项目使用的spring3.0,jar包可以到官网下载 第一种:使用独立的端口(指端口可以在spring中自定义配置) 首先说第一种方式,这种方式不需要添加额外的jar包,他使用的是JDK自带的JWS来实现的. web.xml文件配置: <?xml version="1.0" encoding="UTF-8"?> <web-

cxf+spring发布webservice和调用

项目所需jar包:http://files.cnblogs.com/files/walk-the-Line/cxf-spirng.zip 首先写一个demo接口 package cn.cxf.demo; import javax.jws.WebService; @WebService public interface Demo { String sayHi(String text); } 然后就需要它的实现类 targetNamespace 是指向接口的包路径 package cn.cxf.de

CXF+Spring实现WebService

  接口类: import javax.jws.WebService; @WebService public interface CxfService { public String putName(String uname); } 接口实现类: import javax.jws.WebService; import com.cxf.dao.CxfService; @WebService public class CxfServiceImpl implements CxfService { pu