标签:
上一篇创建了WebService,这里我创建了另一个Web项目web_client来调用这个WebService。
项目代码结构如下:
其中itc10.client包下的java文件是通过WebService的WSDL生成的。
利用JDK自带的wsimport 命令可以利用WSDL文件生成Java代码。
wsimport -s . -p itc10.client http://192.168.1.103:8090/web_service/ws?wsdl
其中 “-s” 是生成源码,“.”是表示源码存放在当前目录下,“-p itc10.client” 是包名,后面的地址是WebService的WSDL文件地址。
这里使用BusQueryAction.java这个Servlet来访问WebService。
1 package itc10.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import itc10.client.BusQuery; 11 import itc10.client.BusQueryWS; 12 13 /** 14 * Servlet implementation class BusQueryAction 15 */ 16 public class BusQueryAction extends HttpServlet { 17 private static final long serialVersionUID = 1L; 18 19 /** 20 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 21 */ 22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 23 // response.getWriter().append("Served at: ").append(request.getContextPath()); 24 doPost(request, response); 25 } 26 27 /** 28 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 29 */ 30 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 // doGet(request, response); 32 BusQueryWS ws = new BusQueryWS(); 33 BusQuery wsPort = ws.getBusQueryPort(); 34 String result = wsPort.queryLine(request.getParameter("city"),
request.getParameter("line")); 35 response.getWriter().append(result); 36 } 37 38 }
在doPost中,创建BusQuery对象,调用queryLine方法查询公交线,注意这里需要两个参数。
可以利用JSP来测试一下:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Line JSP</title> </head> <body> line-info: <br> <div id="line-info"></div> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript"> $(function() { var city = "广州"; var line = "B25"; $.ajax({ type : "POST", url : "BusQueryAction", data : "city=" + city + "&line=" + line, success : function(msg) { console.info(msg); $("#line-info").html(msg); } }); }); </script> </body> </html>
利用jQuery发送异步请求,并将返回的结果显示在div中。
这里查询的是广州的B25公交的信息。
最后将项目发布到tomcat中。
访问项目:http://127.0.0.1/web_client/index.jsp
可以看到返回的结果:
标签:
原文地址:http://www.cnblogs.com/itc10/p/4771014.html