webserive学习记录6-页面请求webservice

Posted liunianfeiyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webserive学习记录6-页面请求webservice相关的知识,希望对你有一定的参考价值。

  前面都是通过JAVA代码访问webservice服务,下面将介绍通过javascript,jquery访问webservice服务并介绍过过servlet解决跨域问题的方法。

  服务端

技术分享图片

  编写服务代码,解决跨域的servlet,通过spring管理项目。在此不在赘述。

  servlet代码如下:

package js.ws.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

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

import org.omg.CORBA.BAD_TYPECODE;

public class HttpURLConnectionServlet extends HttpServlet{
	private static final long serialVersionUID = -3903837158147517884L;

	@Override 
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String data = "<soap:Envelope xmlns:soap=‘http://schemas.xmlsoap.org/soap/envelope/‘><soap:Body><ns2:helloJS xmlns:ns2=‘http://interf.ws.js/‘><arg0>leo</arg0></ns2:helloJS></soap:Body></soap:Envelope>";
		URL url = new URL("http://192.168.0.102:8080/jsws/services/helloJS");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
		
		OutputStream os = conn.getOutputStream();
		os.write(data.getBytes("utf-8"));
		
		int responseCode = conn.getResponseCode();
		if(responseCode == 200)
		{
			resp.setContentType("text/xml;charset=utf-8");
			InputStream is = conn.getInputStream(); // string xml
			ServletOutputStream outputStream = resp.getOutputStream();
			
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = is.read(buffer)) > 0)
			{
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush();
		}
	}
}

   用于获取浏览器发出的访问webservice服务的请求,并真实访问webservice服务,并返回访问服务的结果。

  客户端

  简单起见,测试代码也写在了服务器中。

技术分享图片

  Hello.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<title>hello eclipse</title>
<script type="text/javascript">
	var servletUrl = "/jsws/services/helloServlet";
	var url = "http://localhost:8080/jsws/services/helloJS";
	var data = ‘<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:helloJS xmlns:ns2="http://interf.ws.js/"><arg0>leo</arg0></ns2:helloJS></soap:Body></soap:Envelope>‘;

	function getXMLHttpRequest() {
		var xmlHttpReq = null;
		if (window.XMLHttpRequest) {// Mozilla Firefox, Opera 8.0+, Safari
			xmlHttpReq = new XMLHttpRequest();
		} else {
			if (window.ActiveXObject) {// Internet Explorer
				try {
					xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					try {// Internet Explorer
						xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e) {
					}
				}
			}
		}
		return xmlHttpReq;
	}
	
	$(function(){
		$.post(servletUrl,
			   null,
			   function(msg){
				  var $return = $(msg);
				  alert("servlet: " + $return.find("return").text());
			   },
			   "xml");
		
		$.post(url,
			   data,
			   function(msg){
				  var $return = $(msg);
				  alert("ajax: " + $return.find("return").text());
			   },
			   "xml")
	});
	
	window.onload = javascriptWs;
		
	function javascriptWs()
	{
		var xmlHttpReq = getXMLHttpRequest();
		xmlHttpReq.open("post", url);
		xmlHttpReq.responseType = "document";
		xmlHttpReq.onreadystatechange = function(){
			if(xmlHttpReq.status == 200 && xmlHttpReq.readyState == 4)
			{
				var dom = xmlHttpReq.response;
				var returnEle = dom.getElementsByTagName("return")[0];
				alert("javascript: " + returnEle.firstChild.data);
			}
		}
		xmlHttpReq.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
		xmlHttpReq.send(data);
	}
</script>
</head>
<body>
</body>
</html>

    上面代码分别采用了javascript,jquery发送ajax请求和servlet方式请求webservice服务。

  跨域问题来源于JavaScript的同源策略,即只有 协议+主机名+端口号 (如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。这里通过servlet方式解决跨域问题。

  web.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jsws</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 加入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>  
        <description>Apache CXF Endpoint</description>  
        <display-name>cxf</display-name>  
        <servlet-name>cxf</servlet-name>  
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>cxf</servlet-name>  
        <url-pattern>/services/*</url-pattern>  
    </servlet-mapping>
    <servlet>
    	<servlet-name>wsaccrossdomain</servlet-name>
    	<servlet-class>js.ws.servlet.HttpURLConnectionServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>wsaccrossdomain</servlet-name>
    	<url-pattern>/services/helloServlet</url-pattern>
    </servlet-mapping>
</web-app>

   执行结果如下:

技术分享图片

  代码地址:https://files.cnblogs.com/files/liunianfeiyu/jsws.rar

 

以上是关于webserive学习记录6-页面请求webservice的主要内容,如果未能解决你的问题,请参考以下文章

webserive学习记录4-获取天气的例子

webserive学习记录2-cxf框架基础使用

webserive学习记录5-拦截器完成登陆校验

suds调用webserive时出现suds.TypeNotFound错误

nginx 怎么多个路径访问一个静态目录,改成配置通用符号?

工作部署服务器