CXF+Spring兑现一个简单WebService

2016-04-28 09:42:02 文章

CXF+Spring实现一个简单WebService
WebService server:
创建一个名为webserviceServer的web项目, 导入相关的jar包和CXF的jar包. CXF可以apache.org去下载.

web.xml

webserviceServerSpring character encoding filterorg.springframework.web.filter.CharacterEncodingFilter

encoding

utf-8Spring character encoding filter/*org.springframework.web.context.ContextLoaderListener

contextConfigLocation

/WEB-INF/classes/config/spring/spring-*.xml CXFServlet org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /* index.jsp

spring-context.xml:

IUserService.java:

package com.hao.webservice.service;import javax.jws.WebService;@WebServicepublic interface IUserService {/** * 登录 * @param username * @param password * @return */String login(String username, String password);}

UserServiceImpl.java:

package com.hao.webservice.service.impl;import com.hao.webservice.service.IUserService;public class UserServiceImpl implements IUserService {private String username;private String password;@Overridepublic String login(String username, String password) {if (username.equals(getUsername()) && password.equals(getPassword())) {return "登录成功.";} else {return "登录失败.";}}public String getUsername() {return username;}public String getPassword() {return password;}public void setUsername(String username) {this.username = username;}public void setPassword(String password) {this.password = password;}}

现在将webserviceServer项目发布到servlet容器里(tomcat,jetty). 可以在浏览器输入http://localhost:8080/webserviceServer进行查看.

WebService client:
创建一个名为webserviceClient的web项目或java项目, 导入相关的jar包和CXF的jar包. CXF可以apache.org去下载.

UserServiceTest.java

package com.hao.webservice.client.test;import org.apache.cxf.endpoint.Client;import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;import public class UserServiceTest {public static void main(String[] args) throws Exception {JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); Client client = dcf.createClient("http://localhost:8080/webserviceServer/UserWebService?wsdl"); //login 为接口中定义的方法名称 "chenghao","123456"为传递的2个参数 返回一个Object数组 Object[] objects=client.invoke("login", "chenghao","123456"); System.out.println(objects[0].toString());}}

然后运行UserServiceTest类.

本文地址:https://www.sdfzl.com/jiaocheng-140121-1.shtml

相关阅读

热门