最近一直在学习新的东西,当然也在回顾一些老的知识点。本博客涉及的主要是webservice的调用和Ajax底层的知识的应用,做了一个在页面输入中文的简体字,Ajax方式异步的调用后台webservice服务的小工程,仅作为老知识的回顾和新知识的学习,当然我主要是为了学习webservice的调用,好了,废话不多说,直接上代码吧。
首先index.jsp
<%@ 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"> <META http-equiv="pragma" content="no-cache"> <META http-equiv="Cache-Control" content="no-cache"> <title>简化字转换为繁体字</title> <script> function showResult(transferContent) { //声明一个XMLHttpRequest对象 var xmlhttp; //var transferContent = document.getElementById("txt1").value(); //重置显示的区域 if (transferContent.length == 0) { document.getElementById("transResult").innerHTML = ""; return; } //根据浏览器的对象不同,初始化AJAX对象 if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //设置回调函数,当发送的异步请求返回时调用的方法 xmlhttp.onreadystatechange = function() { //alert(xmlhttp.readyState + ' ' + xmlhttp.status); if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("transResult").innerHTML = xmlhttp.responseText; } }; //GET 方式,但是在此时不适用,因为我要提交的有汉字,GET提交会乱码的 /* var date = new Date(); xmlhttp .open( "GET", "http://localhost:8080/ToolsForSimpleToTraditional/simple2traditional?transferContent=" + transferContent + "&date=" + date, true); xmlhttp.send();*/ //POST 方式 xmlhttp .open( "POST", "http://localhost:8080/ToolsForSimpleToTraditional/simple2traditional", true); //在提交方式是POST的时候,这一句非常的重要!!!!(作者就在学习的时候还没有在这个坑到,没有想到写博客的竟然栽倒了。。。) xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("transferContent=" + transferContent); } </script> </head> <body> <h3>Start typing a name in the input field below:</h3> <form action="url"> Simple Chinese: <input type="text" id="txt1" onblur="showResult(this.value)" /> </form> <p> Traditional Chinese: <span id="transResult"></span> </p> </body> </html>
接着后台的Servlet,就一个简单的servlet,所以就直接写了。
package com.fit.test01; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SimpleToTraditionalServlet */ public class SimpleToTraditionalServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SimpleToTraditionalServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println("----------------------------------------"); request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=UTF-8"); String param = request.getParameter("transferContent"); System.out.println("---------------------" + param); String result = ""; try { result = new Simple2TraditionalServiceImpl() .getTraditionalChinese(param); } catch (Exception e) { e.printStackTrace(); } OutputStream os = response.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8"); osw.write(result); osw.flush(); osw.close(); // System.out.println("===================================" + result); } }
后台调用Webservice的service,(当然我直接用了一个网站提供的Webservice服务,主义此网站提供的服务仅供学习使用,不能作为商业用途。)
package com.fit.test01; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Simple2TraditionalServiceImpl { private String buildSOAPString(String content) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>") .append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">") .append("<soap:Body>") .append("<toTraditionalChinese xmlns=\"http://webxml.com.cn/\">") .append("<sText>").append(content).append("</sText>") .append("</toTraditionalChinese>").append("</soap:Body>") .append("</soap:Envelope>"); return sb.toString(); } private InputStream sendSOAPMessage(String content) throws IOException { String soapMessage = this.buildSOAPString(content); URL url = new URL( "http://webservice.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx"); URLConnection conn = url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(soapMessage.length())); conn.setRequestProperty("SOAPAction", "http://webxml.com.cn/toTraditionalChinese"); OutputStream os = conn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8"); osw.write(soapMessage); osw.flush(); osw.close(); InputStream is = conn.getInputStream(); return is; } public String getTraditionalChinese(String content) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream is = null; String result = ""; try { is = sendSOAPMessage(content); Document doc = builder.parse(is); NodeList nodeList = doc .getElementsByTagName("toTraditionalChineseResult"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); result = node.getFirstChild().getNodeValue(); System.out.println(node.getFirstChild().getNodeValue()); } } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } } return result; } public static void main(String[] args) throws Exception { new Simple2TraditionalServiceImpl().getTraditionalChinese("���յ�"); } }
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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ToolsForSimpleToTraditional</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>SimpleToTraditionalServlet</display-name> <servlet-name>SimpleToTraditionalServlet</servlet-name> <servlet-class>com.fit.test01.SimpleToTraditionalServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleToTraditionalServlet</servlet-name> <url-pattern>/simple2traditional</url-pattern> </servlet-mapping> </web-app>
附件为全部的工程代码,下载下来导入到Eclipse中可以直接在tomcat中跑起来,不用做什么配置,也不依赖于其他jar包等。
运行页面的结果如下图:
相关推荐
WebService\Ajax的总结,全方面介绍了.net下的webservice和ajax原理以及扩展空间。
三个文档打包下载,分别详细讲述了ajax以及JavaScript调用WebService的具体用法,是学习ajax和WebService的良好示例。
jQuery使用Ajax方法调用WebService.rarjQuery使用Ajax方法调用WebService.rarjQuery使用Ajax方法调用WebService.rar
jQuery使用Ajax方法调用WebService.doc
模仿QQ空间的相册效果,利用XML做数据库,对XML进行解析获取数据,页面显示利用了Ajax调用Webservice实现页面无刷新,Jquery对DOM进行解析操作,比利用jquery实现了动画效果
利用ajax和WebService实现的无刷新三级联动源码.zip
网上有,但是只是介绍,没有现成的代码,现在我做了一个最简单的web服务,在客户端运用AJAX技术进行了调用,测试成功!
利用ajax和WebService实现的无刷新三级联动源码,提供给有需要的同道者
基于HTML5_Ajax和WebService的WebGIS研究_徐卓揆 论文
相关知识点说明:此测试程序包含Json、Webservice、Jquery、Ajax相关知识 引用程序集:Newtonsoft.Json.Net35 文件夹及文件说明: JsonDemo\ 应用Newtonsoft相关用例文件夹 ContractResolver.aspx 传入泛型类...
AJAX和Webservice 的长轮询方式ServerPush模拟 vs2005、ASPAJAXExtSetup.msi、ASPAJAXCTP.msi
AJAX和SOAP ─ 異步數據和XML獲取 11 使用 AJAX 調用 SOAP Web 服務 13 XML Webservice實現原理及相關知識 26 UDDI FAQs 29 ASP.NET中利用SQLXML WEB服務訪問XML數據 37 企業應用的Web服務安全技術之一︰問題介紹 45...
ajax跨域调用webservice实现文件上传,项目使用vs2019创建,请示用vs2019以上版本工具进行打开。
通过ajax调用webserivce,并返回值到页面
使用Ajax和WebService重构网上书店AjaxWebService
jquery ajax和webservice 前台jquery和后台的asmx交互,能够有很好的用户体验
ajax+webservice
ajax调用webservice示例 看例子才是最好的学习方法
在不能引用其他jar包的情况调用webservice有时可以解决jar引用和冲突的问题