首页 > 代码库 > CXF Spring开发WebService,基于SOAP和REST方式

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.      
  9.     <import resource="classpath:META-INF/cxf/cxf.xml" />  
  10.     <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  11.       
  12.    <jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld" />  
  13.       
  14.     <!-- http://localhost:7777/CXFDemo/services -->  
  15.     <!-- http://localhost:7777/CXFDemo/services//HelloWorld?wsdl -->  
  16. </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.     
  9.    <context-param>  
  10.       <param-name>contextConfigLocation</param-name>  
  11.       <param-value>WEB-INF/applicationContext.xml</param-value>  
  12.    </context-param>  
  13.    
  14.    <listener>  
  15.       <listener-class>  
  16.          org.springframework.web.context.ContextLoaderListener  
  17.       </listener-class>  
  18.    </listener>  
  19.      
  20.     <servlet>  
  21.         <servlet-name>CXFServlet</servlet-name>  
  22.         <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
  23.         <load-on-startup>1</load-on-startup>  
  24.     </servlet>  
  25.   
  26.     <servlet-mapping>  
  27.         <servlet-name>CXFServlet</servlet-name>  
  28.         <url-pattern>/services/*</url-pattern>  
  29.     </servlet-mapping>  
  30.      
  31.   <welcome-file-list>  
  32.     <welcome-file>index.jsp</welcome-file>  
  33.   </welcome-file-list>  
  34. </web-app>  

接口及实现类文件

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

 

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

发布REST风格的webservice

定义接口和类

 

[java] view plain copy
 
  1. package dcec.rdd;  
  2.   
  3. import javax.ws.rs.GET;  
  4. import javax.ws.rs.Path;  
  5. import javax.ws.rs.PathParam;  
  6. import javax.ws.rs.Produces;  
  7. import javax.ws.rs.core.MediaType;  
  8.   
  9.   
  10. @Path("")    
  11. public interface RestHelloWorld {    
  12.    
  13.     @GET     
  14.     @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})  
  15.     @Path("/say/{name}")     
  16.     public String say(@PathParam("name")String name);    
  17.       
  18.     @GET  
  19.     @Produces ({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})  
  20.     @Path("/getUser/{id}")  
  21.     public List<User> getUser(@PathParam("id")String id);  
  22.   
  23.     @GET  
  24.     @Path("/login")  
  25.     public String login(@QueryParam("name")String name,@QueryParam("ps")String ps);  
  26.  }  
[java] view plain copy
 
  1. package dcec.rdd;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.ws.rs.PathParam;  
  7.   
  8.   
  9. //@Service("rest_HelloWorldImpl")   
  10. public class RestHelloWorldImpl implements RestHelloWorld {  
  11.   
  12.     public String say(String name) {  
  13.               
  14.             System.out.println(name + ", welcome");  
  15.             return name+", welcome you.";  
  16.     }  
  17.       
  18.     public List<User> getUser(String id){  
  19.         List<User> list=new ArrayList<User>();   
  20.           
  21.         User user=new User();  
  22.         user.setId(id);  
  23.         user.setName("chen");  
  24.         list.add(user);  
  25.           
  26.         User user1=new User();  
  27.         user1.setId(id);  
  28.         user1.setName("chen shi");  
  29.         list.add(user1);  
  30.           
  31.         User user2=new User();  
  32.         user2.setId(id);  
  33.         user2.setName("chen shi cheng");  
  34.         list.add(user2);  
  35.         return list;  
  36.     }  
  37.     public String login(String name,String ps){  
  38.         return "name: "+name+", password:"+ps;  
  39.     }  
  40.  }  

 

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

 

拦截器自定义

 

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

 

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



 

 

配置文件

 

 

[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.                            
  11.     <import resource="classpath:META-INF/cxf/cxf.xml" />  
  12.     <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
  13.     <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  14.   
  15.     <jaxws:endpoint id="helloService" implementor="dcec.server.HelloServiceImpl" address="/helloService" />  
  16.     <jaxws:endpoint id="PrintNameService" implementor="dcec.server.PrintNameImpl" address="/PrintNameService" />  
  17.   
  18.     <bean id="restHelloWorldImpl" class="dcec.rdd.RestHelloWorldImpl" />  
  19.       
  20.     <bean id="helloInInterceptor"  class="dcec.rdd.HelloInInterceptor"/>  
  21.     <bean id="helloOutInterceptor" class="dcec.rdd.HelloOutInterceptor"/>  
  22.   
  23.       <jaxrs:server id="restHelloWorld" address="/v1">  
  24.   
  25.         <jaxrs:serviceBeans>  
  26.             <ref bean="restHelloWorldImpl" />  
  27.         </jaxrs:serviceBeans>  
  28.   
  29. <!--拦截器,请求和响应-->  
  30.         <jaxrs:inInterceptors>    
  31.             <ref bean="helloInInterceptor"/>   
  32.         </jaxrs:inInterceptors>   
  33.           
  34.         <jaxrs:outInterceptors>    
  35.             <ref bean="helloOutInterceptor"/>   
  36.         </jaxrs:outInterceptors>   
  37.           
  38.   
  39.   
  40.         <jaxrs:extensionMappings>  
  41.             <entry key="json" value=http://www.mamicode.com/"application/json" />  
  42.             <entry key="xml" value=http://www.mamicode.com/"application/xml" />  
  43.         </jaxrs:extensionMappings>  
  44.     </jaxrs:server>  
  45.       
  46. </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.     
  3. @XmlRootElement(name = "book")    
  4. public class Book {    
  5.     private int bookId;    
  6.     private String bookName;    
  7.     
  8.     public int getBookId() {    
  9.         return bookId;    
  10.     }    
  11.     
  12.     public void setBookId(int bookId) {    
  13.         this.bookId = bookId;    
  14.     }    
  15.     
  16.     public String getBookName() {    
  17.         return bookName;    
  18.     }    
  19.     
  20.     public void setBookName(String bookName) {    
  21.         this.bookName = bookName;    
  22.     }    
  23.         
  24.     public String toString(){    
  25.         return "[bookId:"+bookId+"],[bookName:"+bookName+"]";    
  26.     }    
  27. }    

 

[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. /**  
  12.  * Json提交2  
  13.  * url:http://localhost:9000/rest/json/addBooks  
  14.  * Json format:{"book":[{"bookId":123,"bookName":"newBook"},{"bookId":456,"bookName":"newBook2"}]}  
  15.  */    
  16. @POST    
  17. @Path("/addBooks")    
  18. @Consumes("application/json")    
  19. 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.   
  7. @Override    
  8. public Response addBooks(List<Book> books) {    
  9.     System.out.println("addBooks is called...");    
  10.     return Response.ok().entity("ok").build();    
  11. }    

测试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=http://www.mamicode.com/"sub"/></p>    
    13.     </form>    
    14. </body>    
    15. </html>    

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