首页 > 代码库 > WebService学习笔记-Ajax通过servlet请求跨域Webservice

WebService学习笔记-Ajax通过servlet请求跨域Webservice

ajax不能直接访问跨域的Webservice,但是可以通过servlet去访问跨域的Webservice


页面

<%@ 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>
<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	//var url = "http://192.168.13.232:8989/ws_01/umgsai";
	$(function(){
		$("#WebserviceJQuery2").click(function(){
			var name = document.getElementById("username").value;
			$.post("HttpURLConnectionServlet","name="+name,
					function(msg){
				//alert("msg");
				var $Result = $(msg);
				var value = $Result.find("return").text();
				alert($Result.text());
			},"xml");
		});
</script>
</head>
<body>
	name:
	<input id="username" name="username" value="" />
	<button id="WebserviceJQuery2">Ajax请求Webservice JQuery 跨域</button>
</body>
</html>


HttpURLConnectionServlet.java

package com.umgsai.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;

/**
 * Servlet implementation class HttpURLConnectionServlet
 */
public class HttpURLConnectionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HttpURLConnectionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		System.out.println("传过来的name:"+name);
		String data = "<soapenv:Envelope xmlns:soapenv=‘http://schemas.xmlsoap.org/soap/envelope/‘ xmlns:q0=‘http://ws.umgsai.com/‘ xmlns:xsd=‘http://www.w3.org/2001/XMLSchema‘ xmlns:xsi=‘http://www.w3.org/2001/XMLSchema-instance‘><soapenv:Body><q0:sayHello><arg0>" + name + "</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";
		
		URL url = new URL("http://192.168.13.232:8989/ws_01/umgsai");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
		OutputStream outputStream = connection.getOutputStream();
		outputStream.write(data.getBytes("utf-8"));
		int responseCode = connection.getResponseCode();
		if (responseCode == 200) {
			//
			InputStream inputStream = connection.getInputStream();
			System.out.println("返回的字节数:" + inputStream.available());//
			response.setContentType("text/xml;charset=utf-8");
			ServletOutputStream outputStream2 = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) > 0) {
				outputStream2.write(buffer, 0 , len);
			}
			outputStream2.close();
			inputStream.close();
		}
		outputStream.close();
		connection.disconnect();
	}

}


无论是通过localhost还是IP地址来访问页面都可以请求webservice得到相应的结果。

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1563995

WebService学习笔记-Ajax通过servlet请求跨域Webservice