用cxf編寫基於spring的webservice之下篇

程式界小強發表於2015-09-17

版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/u010741376/article/details/48518843

上一篇,我們通過客戶端的Java程式碼訪問webservice,這一篇,我們通過HttpURLConnection請求webservice,如果使用ajax直接請求webservice,會存在跨域的問題,

比如:如果我釋出的地址是localhost的,那麼在頁面的js裡使用IP訪問的話,就會有問題,訪問不了。

頁面請求的servlet程式碼:

package com.cxf.servlet;

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

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

/**
 * Servlet implementation class HttpURLConnectionServlet
 */
@WebServlet("/HttpURLConnectionServlet")
public class HttpURLConnectionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HttpURLConnectionServlet() {
        super();
    }
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code=request.getParameter("code");
        System.out.println("code:"+code);
        //請求體
        String data="<soap:Envelope xmlns:soap=`http://schemas.xmlsoap.org/soap/envelope/`><soap:Body><ns2:getOrderById xmlns:ns2=`http://ws.cxf.com/`><arg0>"+code+"</arg0></ns2:getOrderById></soap:Body></soap:Envelope>";
		URL url=new URL("http://localhost:8088/cxf_spring_ws/ws/orderws");
		HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
		openConnection.setDoOutput(true);//是否從httpUrlConnection輸出
		openConnection.setDoInput(true);// 設定是否從httpUrlConnection讀入
		openConnection.setRequestMethod("POST");//請求型別
		openConnection.setRequestProperty("Content-Type","text/xml;charset=utf-8");
		OutputStream outputStream = openConnection.getOutputStream();
		outputStream.write(data.getBytes("utf-8"));//向服務端寫入資料
		
		/**
		 * 當相應碼為200的時候,說明請求成功
		 */
		int responseCode = openConnection.getResponseCode();
		if(responseCode==200){
			InputStream inputStream = openConnection.getInputStream();//讀取服務端的資料
			System.out.println("return:"+inputStream.available());
			/**
			 * 將請求得到的資料寫到頁面
			 */
			byte[] buffer=new byte[1024];
			response.setContentType("text/xml;charset=utf-8");
			ServletOutputStream os = response.getOutputStream();
			int len;
			while((len=inputStream.read(buffer))>0){
				os.write(buffer, 0, len);
			}
			os.flush();
			
		}
		
		
		
		
		
	}

}

jsp頁面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP `index.jsp` starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">

	<script type="text/javascript" src="jquery-1.7.2.js"></script>
	<script type="text/javascript">
	     $(function(){
	    	 $("#bt").click(function(){
	    		var code=$("#code").val();
	    		 $.post(
	    		`HttpURLConnectionServlet`,
	    		{"code":code},
	    		function(msg){
	    			var $msg=$(msg);
	    		     var info=$msg.find("return").text();
	    			alert(info);
	    		},
	    		`xml`
	    		 );
	    		 
	    	 });
	    	 
	     });
	</script>
  </head>
  <body>
         <input type="text" id="code">
          <input type="button" id="bt" value="呼叫webservice">
  </body>
  
  
</html>

這樣就可以了。


相關文章