其實質就是向webservice放送soap信息,好比上一篇的soap信息爲前端
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header><daidao><name>kevin</name><password>123456</password></daidao></soap:Header> <soap:Body><ns2:selectByPrimaryKey xmlns:ns2="http://service.cxf.rain6.com/"><arg0>143347</arg0></ns2:selectByPrimaryKey> </soap:Body> </soap:Envelope>
1.Ajax(會有跨域的問題)java
主要就是js代碼web
$("#btn").click(function(){ //回調函數 var name = document.getElementById("name").value; var data = 'soap信息'; $.ajax({ type : "post", url : "http://localhost:8092/webservice/testService", data : data, success : function(msg){ alert("------"); var $Result = $(msg); var value = $Result.find("return").text(); alert(value); }, error : function(msg) { //alert("-----"+msg); }, dataType : "xml" }); });
2.HttpURLConnectionajax
1)簡單點,直接web.xml配置該sevlet跨域
<servlet> <description></description> <display-name>HttpURLConnectionServlet</display-name> <servlet-name>HttpURLConnectionServlet</servlet-name> <servlet-class>httptows.HttpURLConnectionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HttpURLConnectionServlet</servlet-name> <url-pattern>/HttpURLConnectionServlet</url-pattern> </servlet-mapping>
2)HttpURLConnectionServlet.javaapp
public class HttpURLConnectionServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println("doPost "+name); String data = "soap信息";
//localhost建議改成ip地址 URL url = new URL("http://localhost:8092/webservice/testService"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); OutputStream os = connection.getOutputStream(); os.write(data.getBytes("utf-8")); int responseCode = connection.getResponseCode(); if(responseCode==200) { InputStream is = connection.getInputStream();//String xml System.out.println("return "+is.available()); response.setContentType("text/xml;charset=utf-8"); ServletOutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len=is.read(buffer))>0) { outputStream.write(buffer, 0, len); } outputStream.flush(); } } }
3)前端調用函數
$("#btn2").click(function(){ var name = document.getElementById("name").value; $.post( "HttpURLConnectionServlet", "name="+name, function(msg) { //alert(msg); var $Result = $(msg); var value = $Result.find("return").text(); alert(value); }, "xml" ); });