较完整的webservice例子

看了网上有很多关于xfir + spring 开发webservice服务的例子,本人进行了总结在这里介绍一个较完整的例子:
1、 在myeclipse中新建一个web工程xfireWS,导入需要的spring和xfire支持包,
较完整的webservice例子_第1张图片
2、创建包及所需要的类文件
较完整的webservice例子_第2张图片
其中IDataService.java为服务接口类,IDataServiceImpl.java为接口实现类,TestServlet.java为测试用servlet类,IDataService.aegis.xml和IDataService.doc.xml为接口方法描述文件,名称应与接口名匹配,由xfire-aegis包支持。下面是类的具体代码:
IDataService.java

package com.ws.test;
/**
 * WebService服务接口
 * @author zhouyang
 * 2009-7-16
 */

public interface IDataService {
	/**
	 * 从WebService服务器上获取xml数据
	 * @param user
	 * @param pwd
	 * @return String xml数据
	 */
	public String getXmlData(String userName, String pwd);

	/**
	 * 发送xml数据到WebService服务器
	 * @param user
	 * @param pwd
	 * @param xmlData 转型为byte[]类型的xml数据
	 * @return String 发送成功或失败信息
	 */
	public String sendXmlData(String userName, String pwd, byte[] xmlData);
}


IDataServiceImpl.java
public class DataServiceImpl implements IDataService {

	public String getXmlData(String userName, String pwd) {
		//这里给出该方法的简单实现,你可以写更复杂的业务逻辑
		String xmlData = "";
		if("123".equals(userName) && "123".equals(pwd)){
			xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			xmlData += "<books><book>Thinking In Java</book>" 
				    + "<book>Java &amp; Pattern</book><book>Effective Java</book></books>";
		}else{
			xmlData = "用户名和密码错误";
		}
		
		return xmlData;
	}

	public String sendXmlData(String userName, String pwd, byte[] xmlData) {
		return null;
	}

}


TestServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.xfire.client.Client;
/**
 * 通过get方式请求webservice,这里用servlet进行客户端调用处理
 *
 */
public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userName = req.getParameter("userName"); //用户名
		String pwd = req.getParameter("pwd");  //密码
		
		String ip = req.getLocalAddr();
		int port = req.getServerPort();
		String url = "http://" + ip + ":" + port + "/xfireWS/testService.ws?wsdl"; //wsdl描述文件路径
		
		//调用客户端方法
		String result =wsClient(url, "getXmlData", new Object[]{userName,pwd});
		if(result.indexOf("<?xml")>=0)  //设置输出格式,如果是异常信息则以html格式输出
			resp.setContentType("text/xml");
		else
			resp.setContentType("text/html");
		
		resp.setCharacterEncoding("UTF-8");
		PrintWriter   out=resp.getWriter();  
		out.write(result);
		out.flush();
	}

	/**
	 * webservice客户端调用方法
	 * @param url wsdl描述文件路径
	 * @param methodName 服务方法名
	 * @param obj 服务方法参数数组
	 * @return String
	 */
	private String wsClient(String url, String methodName, Object[] obj) {
		Client client;
		try {
			client = new Client(new URL(url));
			Object[] results = client.invoke(methodName, obj);
			return (String)results[0];
		} catch (Exception e) {
			e.printStackTrace();
			return "服务请求失败";
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}



IDataService.aegis.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xfire.codehaus.org/schemas/1.0/mapping.xsd">
    <mapping>
        <method name="getXmlData">
            <parameter index="0" mappedName="userName"/>
            <parameter index="1" mappedName="pwd"/>
            <return-type mappedName="xmlData" />
        </method>      
        <method name="sendXmlData">
            <parameter index="0" mappedName="userName"/>
            <parameter index="1" mappedName="pwd"/>
            <parameter index="2" mappedName="xmlData"/>
            <return-type mappedName="successInfo" />
        </method>  
   </mapping>
   
   
</mappings> 



IDataService.doc.xml
<service>
  <method name="getXmlData" parametersNumber="2" >
     <parameter index="0">
        <documentation>
           用户名
        </documentation>
     </parameter>
     <parameter index="1">
        <documentation>
           密码
        </documentation>
     </parameter>
      <return>
        <documentation>
         获取的xml数据
        </documentation>
      </return>
  </method>
  <method name="sendXmlData" parametersNumber="3" >
     <parameter index="0">
        <documentation>
           用户名
        </documentation>
     </parameter>
     <parameter index="1">
        <documentation>
           密码
        </documentation>
     </parameter>
     <parameter index="2">
        <documentation>
           转型为byte数组发送的xml数据
        </documentation>
     </parameter>
      <return>
        <documentation>
         发送成功或失败信息
        </documentation>
      </return>
  </method>
</service>


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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

	<bean id="dataServiceBean" class="com.ws.test.DataServiceImpl"></bean>  
</beans>


3、web.xml文件和xfire-sevlet.xml文件,“xfire”与web.xml文件中servlet-name对应。
web.xml 内容
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="starter" version="2.4" 
         xmlns="http://java.sun.com/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	
	<display-name>webservice demo</display-name>
	 <!-- 配置文件路径 开始 -->  
     <context-param>  
         <param-name>contextConfigLocation</param-name>  
         <param-value>  
             classpath:applicationContext.xml
             classpath:org/codehaus/xfire/spring/xfire.xml
         </param-value>  
     </context-param>  
       
     <!-- 启动时加载SpringContextServlet -->  
     <listener>  
         <listener-class>  
            org.springframework.web.context.ContextLoaderListener  
         </listener-class>  
     </listener>  
       
       <!-- XFire 配置 -->
       <servlet>   
         <servlet-name>xfire</servlet-name>   
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>   
       </servlet>   
         
       <servlet-mapping>  
         <servlet-name>xfire</servlet-name>  
         <url-pattern>*.ws</url-pattern>  
       </servlet-mapping>  
        <!—测试请求的serv配置-->
        <servlet>   
         <servlet-name>test</servlet-name>   
         <servlet-class>com.ws.test.TestServlet</servlet-class>   
       </servlet>   
         
       <servlet-mapping>
         <servlet-name>test</servlet-name>
         <url-pattern>/testService.ws/getXmlData/*</url-pattern>
       </servlet-mapping>
       <servlet-mapping>
         <servlet-name>test</servlet-name>
         <url-pattern>/testService.ws/sendXmlData/*</url-pattern>
       </servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


xfire-sevlet.xml内容
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> 
	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
		<property name="urlMap">
	        <map>
	        	<entry key="/testService.ws">
	            	<ref bean="test"/>  
	          	</entry> 
	        </map> 
	    </property>
	  </bean> 
	  
	  <bean id="test" parent="webService" class="org.codehaus.xfire.spring.remoting.XFireExporter"> 
	    <property name="serviceBean"> 
	        <ref bean="dataServiceBean"/> 
	    </property> 
	    <property name="serviceClass"> 
	        <value>com.ws.test.IDataService</value> 
	    </property> 
	  </bean> 
	    
	  <!-- webService base -->
	  <bean id="webService" class="org.codehaus.xfire.spring.remoting.XFireExporter" abstract="true">
        <property name="serviceFactory">
            <ref bean="xfire.serviceFactory" />
        </property>
        <property name="xfire">
            <ref bean="xfire" />
        </property>
   	 </bean>
</beans>


4、发布到tomcat服务器,启动服务器成功后,输入
http://localhost:8080/xfireWS/testService.ws?wsdl可以查看wsdl描述文件,
较完整的webservice例子_第3张图片
输入
http://localhost:8080/xfireWS/testService.ws/getXmlData?userName=123&pwd=123可以得到webservice服务提供的返回值,为一个xml数据,
较完整的webservice例子_第4张图片
如果输入用户名和密码错误则有错误提示。
关于web.xml文件和xfire-sevlet.xml文件的配置这里不在重述,如有疑问可以在网上找到答案。

你可能感兴趣的:(java,spring,xml,webservice,servlet)