欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webservice 远程调用  

程序员文章站 2024-02-09 22:23:04
...

 

  

webservice 远程调用技术

1.1 webservice 组成及原理:

      

          Webservice是一种使用http传输SOAP协议的数据远程调用技术

     wsdl:是一个xml文件  简单的说就是webservice的说明书

      soap:简单对象访问协议

     uudi:一种目录 (不重要)

   xml文件的阅读规则:

  
webservice 远程调用
            
    
    
         
 targetNamespaces  名称空间

 portType 标签下的 name属性是实现类  massage属性是方法名称

 service 标签下的 name属性是service

1.2 webservice 的入门案例:

                           服   务   端 

   第一步:  导入jar包

/**
 * 创建接口
 * @author Administrator
 *
 */
public interface WeatherInterface {
  public String getWeather(String str);
}

  第二步:

/**
 * 创建实现类  实现类要加 @WebService 表签
 * @author Administrator
 *
 */
@WebService
public class WeatherInterfaceImpl implements WeatherInterface {

	@Override
	public String getWeather(String str) {
		System.out.println("我来了。。。。");
		return str;
	}
}

  第三步:

import javax.xml.ws.Endpoint;
/**
 * 发布服务
 * @author Administrator
 *
 */
public class WeatherServer {
  public static void main(String[] args) {
       //第一个参数服务地址
       //第二个参数实现类
	Endpoint.publish("http://127.0.0.1:12345/weather", new WeatherInterfaceImpl());
}
}

  第四步:测试服务是否发布成功    打开wsdl 阅读xml 文件

                测试地址:http://127.0.0.1:12345/weather?wsdl

                             客  户  端

   说明:dom 中

   命令wsimportjdk提供根据WSDL地址生成客户端代码的工具

   命令wsimport位置%JAVA_HOME%/bin

   命令wsimport常用的参数:

     -d指定生成*.class默认参数

     -s,指定生成*.java文件

     -p,指定代码生成包名,如果不加该参数,默认包名WSDL命名空间的倒序

              命令wsimport仅支持SOAP1.1客户端生成

 第一步:wsimport生成代码   wsimport  -s  .  http://127.0.0.1:weather?wsdl              建立一个项目 导入生成的代码 导入jar包

  第二步:

import test00.WeatherInterfaceImpl;
import test00.WeatherInterfaceImplService;
/**
 * 客户端
 * @author Administrator
 */
public class WeatherClient {
  public static void main(String[] args) {
	//创建service对象
	WeatherInterfaceImplService weatherInterfaceService=new WeatherInterfaceImplService();
	//获取实现类
	WeatherInterfaceImpl weatherInterfaceImpl=weatherInterfaceService.getPort(WeatherInterfaceImpl.class);
	//调用方法
	String weather = weatherInterfaceImpl.getWeather("晴");
	System.out.println(weather);
}
}

 

1.3 webservice 的四种客户端调用:

   说明:公网地址

     http://www.webxml.com.cn/zh_cn/web_services.aspx

     wsimport -s . http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl   生成查询天气的代码

   建一个项目  导入生成的代码  导入jar包

   第一种方式:

 

import cn.com.webxml.ArrayOfString;
import cn.com.webxml.WeatherWS;
import cn.com.webxml.WeatherWSSoap;
/**
 * 入门案例中就是用的这种
 * @author Administrator
 */
public class demo01 {

	public static void main(String[] args) {
		WeatherWS weatherWS=new WeatherWS();
		WeatherWSSoap weatherWSSoap = weatherWS.getPort(WeatherWSSoap.class);
		ArrayOfString weather = weatherWSSoap.getWeather("北京", "");
		List<String> list = weather.getString();
		StringBuffer yp=new StringBuffer();
		for(String str:list){
			yp.append(str+" ");
		}
		System.out.println(yp);
	}
}

  第二种方式:

 

/**
 * 用服务地址获取实现类  灵活
 * @author Administrator
 */
public class demo02 {
	
    public static void main(String[] args) throws MalformedURLException {
    	//服务地址
	URL url=new URL("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx");
	//第一个参数名称空间   第二个参数是service标签的name属性
    	QName name=new QName("http://WebXml.com.cn/","WeatherWS");
    	Service service=Service.create(url, name);
    	//获取实现类
    	WeatherWSSoap weatherWSSoap = service.getPort(WeatherWSSoap.class);
    	//调用方法
    	ArrayOfString weather = weatherWSSoap.getWeather("原平", "");
    	List<String> list = weather.getString();
    	for(String str:list){
    		System.out.println(str);
    	}
	}
}

  第三种方式:

 

/**
 * 利用HttpURLConnection实现调用
 * @author Administrator
 */
public class demo03 {
    public static void main(String[] args) throws Exception {
    	//服务地址
	URL url=new URL("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx");
	//打开链接
	HttpURLConnection connection=(HttpURLConnection)url.openConnection();
	//设置请求方式
	connection.setRequestMethod("POST");
	//设置mime类型  这是soap1.1的    soap1.2的是 "application/soap+xml;chartset=utf-8"
	connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
	//设置输入输出
	connection.setDoOutput(true);
	connection.setDoInput(true);
	//输出请求体
	OutputStream outputStream = connection.getOutputStream();
	outputStream.write(getXml("太原").getBytes());
	//如果响应成功
	int i = connection.getResponseCode();
	if(i==200){
		InputStream inputStream = connection.getInputStream();
		BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
		String but=null;
		StringBuilder der=new StringBuilder();
		while(null!=(but=reader.readLine())){
			der.append(but);
	         }
		byte[] bytes = der.toString().getBytes();
		System.out.println(new String(bytes,"utf-8"));
		reader.close();
		inputStream.close();
		}
		outputStream.close();
	}
    //请求体
    public static String getXml(String str){
    	String xmlSpoat="<?xml version=\"1.0\" encoding=\"utf-8\"?>"
		          +" <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
			  +"  <soap:Body>"
			  +"    <getWeather xmlns=\"http://WebXml.com.cn/\">"
		          +"      <theCityCode>"+str+"</theCityCode>"
		          +"      <theUserID></theUserID>"
			  +"    </getWeather>"
		          +"  </soap:Body>"
		       +"</soap:Envelope>";
    	return xmlSpoat;
    }
}

  第四种方式:基于ajax

 

<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script >
			function getMobile(){
				alert(999);
				var xml=new XMLHttpRequest();
				
				xml.open("post","http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl",true);
				xml.setRequestHeader("context-type","text/html;charset=utf-8");
				xml.onreadystatechange=function(){
					if(xml.status==200 && xml.readyState==4){
						var div=document.getElementById("div");
						div.innerHTML(xml.responseText);
					}
				}
				var soapXml='<?xml version="1.0" encoding="utf-8"?>'
       						+'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
							+'	  <soap:Body>'
							+'	    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">'
							+'	      <mobileCode>"+document.getElementById("dd")+"</mobileCode>'
							+'	      <userID></userID>'
							+'	    </getMobileCodeInfo>'
							+'	  </soap:Body>'
							+'	</soap:Envelope>';
				xml.send(soapXml);
			}
			
		</script>
	</head>
	<body>
		电话:<input type="text" id="dd" /><br/>
		<input type="button" onclick="getMobile()" /><br/>
		<div id="div"></div>
	</body>
</html>

 

1.3 webservice 基于cxf框架:

   1.3.1 cxf的介绍

    cxf:一个开源的webservice框架,提供很多成熟的功能,帮助我们快速开发

    cxf:支持的协议:SOAP1.1/1.2REST

               cxf:支持的数据格式:XMLJSON(仅在REST支持)

  1.3.2 cxf的下载  安装

         http://cxf.apache.org/download.html

            第一步:安装前必须安装jdk 最好是1.7版本的  配置jdk的环境变量

            第二步: 解压下载完毕的apache-cxf-2.7.11

            第三步:配置cxf的环境变量

        


webservice 远程调用
            
    
    
         


 
webservice 远程调用
            
    
    
         
 
webservice 远程调用
            
    
    
         
          第四步:
测试是否配置成功在一个新的cmd窗口中输入wsdl2java -h

      
webservice 远程调用
            
    
    
         
    
1.3.3 cxf服务端和客户端代码

                 服    务    端     导入jar包

     第一步:

/**
 * 接口  @BindingType(SOAPBinding.SOAP12HTTP_BINDING)  
 * 说明是soap1.2
 * @author Administrator
 */
@WebService
@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
public interface WeatherInterface {
   public String getWeather(String str);
}

   第二步: 

/**
 * 实现类
 * @author Administrator
 */
public class WeatherInterfaceImpl implements WeatherInterface {
	public String getWeather(String str) {
		System.out.println("我来了。。。。");
		return str;
	}
}

    第三步:

/**
 * 基于cxf 的发布服务
 * @author Administrator
 */
public class WeatherServer {
   public static void main(String[] args) {
	  JaxWsServerFactoryBean factoryBean=new JaxWsServerFactoryBean();
	  factoryBean.setServiceClass(WeatherInterface.class);
	  factoryBean.setServiceBean(new WeatherInterfaceImpl());
	  //设置服务地址
	  factoryBean.setAddress("http://127.0.0.1:1314/weather");
	  //发布
	  factoryBean.create();
}
}

 

                     客    户    端

     说明:

    wsdl2java命令生成客户端代码
    命令wsdl2javaCXF提供的根据WSDL地址生成客户端代码的工具

    命令wsdl2java位置%CXF_HOME%\bin

    命令wsdl2java常用参数:

                  -d,生成java代码,指定代码的存放目录

                 -p指定代码生成包名,不指定该参数,默认包名WSDL命名空间的倒序

    命令wsdl2java支持SOAP1.1SOAP1.2生成

  

             E:\workspace\wsimport\src>wsdl2java  -p  cn.itcast.cxf -d . http://127.0.0.1:12345/weather?wsd

     建一个新项目 导入生成的代码 导入jar包

     

/**
 * 客户端 使用JaxWsProxyFactoryBean类获取
 * @author Administrator
 *
 */
public class WeatherClient {
    public static void main(String[] args) {
		JaxWsProxyFactoryBean factoryBean=new JaxWsProxyFactoryBean();
		factoryBean.setServiceClass(WeatherInterface.class);
		factoryBean.setAddress("http://127.0.0.1:1314/weather?wsdl");
		//获取接口
		WeatherInterface weatherInterface = factoryBean.create(WeatherInterface.class);
		//调用方法
		String weather = weatherInterface.getWeather("小风吹的凉爽");
		System.out.println(weather);
	}
}

 1.3.4 cxf与spring的整合

      服务端:建一个项目 导入jar包
     第一步   web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name></display-name>
  <!-- 加载applicationContext.xml -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  	<listener>
  	   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  	</listener>
  	
  	<!-- cxf服务 -->
  	<servlet>
  	   <servlet-name>cxf</servlet-name>
  	   <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  	</servlet>
  	<servlet-mapping>
  	   <servlet-name>cxf</servlet-name>
  	   <url-pattern>/ws/*</url-pattern>
  	</servlet-mapping>
  	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
   第二步: config下面的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" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				            http://www.springframework.org/schema/beans/spring-beans.xsd
				            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
				            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
				            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
	<!-- <jaxws:server>发布服务  -->
	<jaxws:server address="/weather" serviceClass="cn.xebest.weather.WeatherInterface">
		<jaxws:serviceBean>
			<ref bean="weatherInterface"/>
		</jaxws:serviceBean>
		
		<jaxws:inInterceptors>
			<ref bean="inInterceptor"/>
		</jaxws:inInterceptors>
		<jaxws:outInterceptors>
			<ref bean="outInterceptor"/>
		</jaxws:outInterceptors>
	</jaxws:server>
	<!-- 配置拦截器 -->
	<bean id="inInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
	<bean id="outInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
	
	<!-- 配置实现类的bean -->
	<bean id="weatherInterface" class="cn.xebest.weather.WeatherInterfaceImpl"/>
	
</beans>
  第三步:接口
/**
 * 接口  @BindingType(SOAPBinding.SOAP12HTTP_BINDING)  
 * 说明是soap1.2
 * @author Administrator
 */
@WebService
@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
public interface WeatherInterface {
   public String getWeather(String str);
}
   第四步:实现类
/**
 * 实现类
 * @author Administrator
 */
public class WeatherInterfaceImpl implements WeatherInterface {
	public String getWeather(String str) {
		System.out.println("我来了。。。。");
		return str;
	}
}
   
  客户端:
   在dom 中 用命令 wsdl2java  生成代码
   建一个项目 导入生成的代码 导入jar包
  第一步: config 下的 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" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				            http://www.springframework.org/schema/beans/spring-beans.xsd
				            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
				            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
				            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
	<jaxws:client id="weatherInterface" address="http://127.0.0.1:8090/webservice00/ws/weather?wsdl"
	 serviceClass="cn.xebest.weather.WeatherInterface"/>
	
</beans>
  第二步:获取配置文件
/**
 * 获取xml 文件
 * @author Administrator
 */
public class test05 {
   public static void main(String[] args) {
	 ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	 WeatherInterface weatherInterface = (WeatherInterface) context.getBean("weatherInterface");
	 String weather = weatherInterface.getWeather("原平的天气也很好");
	 System.out.println(weather);
}
}
  
 1.3.5 cxf与spring的综合案例
    说明:根据地址:http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl 先获取到手机的服务 再把获取到的手机服务发布
    在dom中用命令生成 天气服务http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl的代码 导入项目中  导入所需jar包

   第一步:接口 MobileInterface

 

/**
 * 接口
 * @author Administrator
 */
@WebService
@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
public interface MobileInterface {
   public String getMobile(String str);
}

   第二步:实现类 MobileInterfaceImpl

 

/**
 * 实现类
 * @author Administrator
 */
public class MobileInterfaceImpl implements MobileInterface {
	//声明要获取的天气的实现类
	public MobileCodeWSSoap mobileCodeWSSoap;
	//set方法是为了能在配置文件中给这个属性赋值
	public void setMobileCodeWSSoap(MobileCodeWSSoap mobileCodeWSSoap) {
		this.mobileCodeWSSoap = mobileCodeWSSoap;
	}
    //要发布的方法
	public String getMobile(String str) {
		return mobileCodeWSSoap.getMobileCodeInfo(str, "");
	}

}

   第三步:定义servlet类 Mobile

 

/**
 * 自定义的servlet类  继承HttpServlet
 * @author Administrator
 *
 */
public class Mobile extends HttpServlet {
    //get的请求
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}
	//post请求
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MobileInterfaceImpl mobileInterfaceImpl;
        WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        mobileInterfaceImpl=(MobileInterfaceImpl) context.getBean("mobileInterfaceImpl");
        
        request.setCharacterEncoding("utf-8");
        String num=request.getParameter("mobileNum");
        num=mobileInterfaceImpl.getMobile(num);
        request.setAttribute("num",num);
        request.getRequestDispatcher("/form.jsp").forward(request, response);
		System.out.println("请求来了");
	}
}

 

  第四步:配置web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name></display-name>	
  <!-- 加载spring 配置文件 -->
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 加载cxf服务 -->
  <servlet>
     <servlet-name>cxf</servlet-name>
     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>cxf</servlet-name>
     <url-pattern>/mobile/*</url-pattern>
  </servlet-mapping>
  <!-- 配置自定义的servlet -->
   <servlet>
    <servlet-name>Mobile</servlet-name>
    <servlet-class>cn.xebest.mobile.Mobile</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Mobile</servlet-name>
    <url-pattern>/mobile.action</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  第五步:config 下的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" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				            http://www.springframework.org/schema/beans/spring-beans.xsd
				            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
				            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
				            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
	<!-- 服务端 -->
	<jaxws:server id="mobileInterface" serviceClass="cn.xebest.mobile.MobileInterface" address="/address">
	    <jaxws:serviceBean>
	       <ref bean="mobileInterfaceImpl"/>
	    </jaxws:serviceBean>
	</jaxws:server>
	<!-- 给属性赋值 -->
	<bean id="mobileInterfaceImpl" class="cn.xebest.mobile.MobileInterfaceImpl">
	   <property name="mobileCodeWSSoap" ref="mobileCodeWSSoap" />
	</bean>
	
	<!-- 客户端  获取公网的数据-->
	<jaxws:client id="mobileCodeWSSoap" address="http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl" serviceClass="cn.com.webxml.MobileCodeWSSoap"></jaxws:client>			            
</beans>				            

 第六步:form.jsp

 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/mobile.action" method="post" onsubmit="return sub()">
  <input type="text" name="mobileNum"  />
  <input type="submit" value="submit">
</form>
${num}
</body>
</html>

   127.0.0.1:8090/项目名/mobile/address?wsdl

 

1.4 webservice 基于cxf框架的rest风格:(cxf是能实现rest风格的框架)

    1.4.1 普通的发布:

     建立项目  导入jar包

   第一步:实体类

 

/**
 * 在这个类上面必须有此标签 name 的值谁编写
 * @author Administrator
 */
@XmlRootElement(name="student")
public class Student implements Serializable{
	 private String name;
	    private String sex;
	    private String age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
}

  第二步:接口

 

@WebService
@Path("/student")//类的路径
public interface StudentInterface {
    
	@GET//get请求
	@Path("/string/{id}")//方法的路径  id是参数  在方法中用@PathParam获取
	@Produces(MediaType.APPLICATION_XML)//xml格式
	public Student getString(@PathParam("id")String id);
		
	@GET
	@Path("/list/{id}")
	//可以是xml 也可以是 json
    @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
	public List<Student> getList(@PathParam("id")String id);
}

  第三步: 实现类

 

public class StudentInterfaceImpl implements StudentInterface{

	@Override
	public Student getString(String id) {
		Student t=new Student();
		t.setName("小刚");
		t.setAge("18");
		t.setSex("男");
		if(StringUtils.isNotBlank(id)){
			return t;
		}
		return null;
	}

	@Override
	public List<Student> getList(String id) {
		Student t1=new Student();
		t1.setName("小刚");
		t1.setAge("18");
		t1.setSex("男");
		Student t2=new Student();
		t2.setName("小刚");
		t2.setAge("18");
		t2.setSex("男");
		Student t3=new Student();
		t3.setName("小刚");
		t3.setAge("18");
		t3.setSex("男");
		@SuppressWarnings("unused")
		List<Student> list=new ArrayList<Student>();
		list.add(t1);
		list.add(t2);
		list.add(t3);
		if(StringUtils.isNotBlank(id)){
			return list;
		}
		return null;
	}

}

 第四步:发布服务

 

/**
 * rest发布服务
 * @author Administrator
 *
 */
public class StudentServer {

	public static void main(String[] args) {
		//rest框架的api
		JAXRSServerFactoryBean factroyBean=new JAXRSServerFactoryBean();
		factroyBean.setAddress("http://127.0.0.1:1232/server");
		factroyBean.setResourceClasses(StudentInterfaceImpl.class);
		factroyBean.create();
	}
}

   http:127.0.0.1:1232/server/student/list/99?_type=json   //获取json格式

   http:127.0.0.1:1232/server/student/list/99?_type=xml   //获取xml格式

   http:127.0.0.1:1232/server/student/string/99                //获取xml格式

   

  1.4.2 rest与spring整合的发布:

   建立项目  导入jar包

  第一步:实体类

 

package cn.xebest.rest;

import javax.xml.bind.annotation.XmlRootElement;
/**
 * 实体类   
 * 此处必须有标签 @XmlRootElement
 * @author Administrator
 *
 */
@XmlRootElement(name="student")
public class Student {
		private String name;
		private String age;
		private String sex;
	   public Student() {
			super();
		}
		public Student(String name,String age,String sex){
			   this.name=name;
			   this.age=age;
			   this.sex=sex;
		   }
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		} 
		   
}

 

   第二步:接口

  

@WebService
@Path("/student")
public interface StudentInterface {

	@GET
	@Path("/string/{id}")
	@Produces(MediaType.APPLICATION_XML)
	public Student getStudent(@PathParam("id")String id);
	
	@GET
	@Path("/list/{id}")
	@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
	public List<Student> getList(@PathParam("id")String dd);
}

   第三步:实现类

 

public class StudentInterfaceImpl implements StudentInterface {

	public Student getStudent(String id) {
		Student t=new Student("小明","21","男");
		if(StringUtils.isNotBlank(id)){
			return t;
		}
		return null;
	}

	public List<Student> getList(String dd) {
		Student t1=new Student("小明","21","男");
		Student t2=new Student("小明","21","男");
		Student t3=new Student("小明","21","男");
		List<Student> list=new ArrayList<Student>();
		if(StringUtils.isNotBlank(dd)){
			list.add(t1);
			list.add(t2);
			list.add(t3);
			return list;
		}
		return null;
	}

}

 

 第四步:config下的 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" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				            http://www.springframework.org/schema/beans/spring-beans.xsd
				            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
				            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
				            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
	<jaxrs:server address="/address" >
	    <jaxrs:serviceBeans>
	      <ref bean="studentInterfaceImpl"/>
	    </jaxrs:serviceBeans>
	</jaxrs:server>
	<bean id="studentInterfaceImpl" class="cn.xebest.server.StudentInterfaceImpl"></bean>			            
</beans>				           

 第五步:web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name></display-name>	
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <servlet>
      <servlet-name>cxf</servlet-name>
      <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>cxf</servlet-name>
      <url-pattern>/server/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

   http:127.0.0.1:8090/项目名/server/address/student/string/99

 

 

 

 

 

 

 

 

 

 

 

  • webservice 远程调用
            
    
    
         
  • 大小: 14.3 KB