首页 > 代码库 > CXF Spring开发WebService,基于SOAP和REST方式
CXF Spring开发WebService,基于SOAP和REST方式
版本CXF2.6.9
添加的包文件
这个版本的不可在Tomcat7上运行,会出错。
配置文件
applicationContext.xml
[html] view plain copy
- <?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
[html] view plain copy
- <?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>
接口及实现类文件
[java] view plain copy
- package demo.spring.service;
- import javax.jws.WebService;
- @WebService
- public interface HelloWorld {
- String sayHi(String text);
- }
[java] view plain copy
- 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
定义接口和类
[java] view plain copy
- 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);
- }
[java] view plain copy
- 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;
- }
- }
[java] view plain copy
- 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;
- }
- }
拦截器自定义
[java] view plain copy
- 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("**************************离开拦截器**************************************");
- }
- }
[java] view plain copy
- 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("**************************离开拦截器**************************************");
- }
- }
配置文件
[html] view plain copy
- <?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=http://www.mamicode.com/"application/json" />
- <entry key="xml" value=http://www.mamicode.com/"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
[java] view plain copy
- 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+"]";
- }
- }
[java] view plain copy
- /**
- * 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);
[java] view plain copy
- @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 提交
[html] view plain copy
- <!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=http://www.mamicode.com/"sub"/></p>
- </form>
- </body>
- </html>
CXF Spring开发WebService,基于SOAP和REST方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。