利用AJax方式提交和Webservice完成页面输入汉字简体字回显繁体字

前端之家收集整理的这篇文章主要介绍了利用AJax方式提交和Webservice完成页面输入汉字简体字回显繁体字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近一直在学习新的东西,当然也在回顾一些老的知识点。本博客涉及的主要是webservice的调用和Ajax底层的知识的应用,做了一个在页面输入中文的简体字,Ajax方式异步的调用后台webservice服务的小工程,仅作为老知识的回顾和新知识的学习,当然我主要是为了学习webservice的调用,好了,废话不多说,直接上代码吧。

首先index.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <Meta http-equiv="pragma" content="no-cache">
  8. <Meta http-equiv="Cache-Control" content="no-cache">
  9.  
  10. <title>简化字转换为繁体字</title>
  11.  
  12. <script>
  13. function showResult(transferContent) {
  14.  
  15. //声明一个XMLHttpRequest对象
  16. var xmlhttp;
  17.  
  18. //var transferContent = document.getElementById("txt1").value();
  19.  
  20. //重置显示的区域
  21. if (transferContent.length == 0) {
  22. document.getElementById("transResult").innerHTML = "";
  23. return;
  24. }
  25.  
  26. //根据浏览器的对象不同,初始化AJAX对象
  27. if (window.XMLHttpRequest) {// code for IE7+,Firefox,Chrome,Opera,Safari
  28. xmlhttp = new XMLHttpRequest();
  29. } else {// code for IE6,IE5
  30. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  31. }
  32.  
  33. //设置回调函数,当发送的异步请求返回时调用方法
  34. xmlhttp.onreadystatechange = function() {
  35. //alert(xmlhttp.readyState + ' ' + xmlhttp.status);
  36. if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  37. document.getElementById("transResult").innerHTML = xmlhttp.responseText;
  38. }
  39. };
  40.  
  41. //GET 方式,但是在此时不适用,因为我要提交的有汉字,GET提交会乱码的
  42. /* var date = new Date();
  43. xmlhttp
  44. .open(
  45. "GET","http://localhost:8080/ToolsForSimpleToTraditional/simple2traditional?transferContent="
  46. + transferContent + "&date=" + date,true);
  47. xmlhttp.send();*/
  48.  
  49. //POST 方式
  50. xmlhttp
  51. .open(
  52. "POST","http://localhost:8080/ToolsForSimpleToTraditional/simple2traditional",true);
  53.  
  54. //在提交方式是POST的时候,这一句非常的重要!!!!(作者就在学习的时候还没有在这个坑到,没有想到写博客的竟然栽倒了。。。)
  55. xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  56. xmlhttp.send("transferContent=" + transferContent);
  57. }
  58. </script>
  59.  
  60. </head>
  61. <body>
  62.  
  63. <h3>Start typing a name in the input field below:</h3>
  64.  
  65. <form action="url">
  66. Simple Chinese: <input type="text" id="txt1"
  67. onblur="showResult(this.value)" />
  68. </form>
  69. <p>
  70. Traditional Chinese: <span id="transResult"></span>
  71. </p>
  72.  
  73. </body>
  74. </html>

接着后台的Servlet,就一个简单的servlet,所以就直接写了。

  1. package com.fit.test01;
  2.  
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.io.OutputStreamWriter;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11.  
  12. /**
  13. * Servlet implementation class SimpleToTraditionalServlet
  14. */
  15. public class SimpleToTraditionalServlet extends HttpServlet {
  16. private static final long serialVersionUID = 1L;
  17.  
  18. /**
  19. * @see HttpServlet#HttpServlet()
  20. */
  21. public SimpleToTraditionalServlet() {
  22. super();
  23. // TODO Auto-generated constructor stub
  24. }
  25.  
  26. /**
  27. * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse
  28. * response)
  29. */
  30. protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
  31. // TODO Auto-generated method stub
  32. this.doPost(request,response);
  33. }
  34.  
  35. /**
  36. * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse
  37. * response)
  38. */
  39. protected void doPost(HttpServletRequest request,IOException {
  40.  
  41. // System.out.println("----------------------------------------");
  42. request.setCharacterEncoding("utf-8");
  43. response.setContentType("text/html; charset=UTF-8");
  44.  
  45. String param = request.getParameter("transferContent");
  46. System.out.println("---------------------" + param);
  47. String result = "";
  48.  
  49. try {
  50. result = new Simple2TraditionalServiceImpl()
  51. .getTraditionalChinese(param);
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55.  
  56. OutputStream os = response.getOutputStream();
  57.  
  58. OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");
  59.  
  60. osw.write(result);
  61.  
  62. osw.flush();
  63.  
  64. osw.close();
  65.  
  66. // System.out.println("===================================" + result);
  67. }
  68.  
  69. }

后台调用Webservice的service,(当然我直接用了一个网站提供的Webservice服务,主义此网站提供的服务仅供学习使用,不能作为商业用途。)

  1. package com.fit.test01;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9.  
  10. import javax.xml.parsers.DocumentBuilder;
  11. import javax.xml.parsers.DocumentBuilderFactory;
  12.  
  13. import org.w3c.dom.Document;
  14. import org.w3c.dom.Node;
  15. import org.w3c.dom.NodeList;
  16.  
  17. public class Simple2TraditionalServiceImpl {
  18.  
  19. private String buildSOAPString(String content) {
  20. StringBuilder sb = new StringBuilder();
  21.  
  22. sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
  23. .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/\">")
  24. .append("<soap:Body>")
  25. .append("<toTraditionalChinese xmlns=\"http://webxml.com.cn/\">")
  26. .append("<sText>").append(content).append("</sText>")
  27. .append("</toTraditionalChinese>").append("</soap:Body>")
  28. .append("</soap:Envelope>");
  29.  
  30. return sb.toString();
  31. }
  32.  
  33. private InputStream sendSOAPMessage(String content) throws IOException {
  34.  
  35. String soapMessage = this.buildSOAPString(content);
  36. URL url = new URL(
  37. "http://webservice.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx");
  38.  
  39. URLConnection conn = url.openConnection();
  40.  
  41. conn.setUseCaches(false);
  42. conn.setDoInput(true);
  43. conn.setDoOutput(true);
  44.  
  45. conn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
  46. conn.setRequestProperty("Content-Length",String.valueOf(soapMessage.length()));
  47. conn.setRequestProperty("SOAPAction","http://webxml.com.cn/toTraditionalChinese");
  48.  
  49. OutputStream os = conn.getOutputStream();
  50.  
  51. OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");
  52.  
  53. osw.write(soapMessage);
  54. osw.flush();
  55.  
  56. osw.close();
  57.  
  58. InputStream is = conn.getInputStream();
  59.  
  60. return is;
  61.  
  62. }
  63.  
  64. public String getTraditionalChinese(String content) throws Exception {
  65.  
  66. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  67.  
  68. DocumentBuilder builder = factory.newDocumentBuilder();
  69.  
  70. InputStream is = null;
  71. String result = "";
  72. try {
  73. is = sendSOAPMessage(content);
  74.  
  75. Document doc = builder.parse(is);
  76.  
  77. NodeList nodeList = doc
  78. .getElementsByTagName("toTraditionalChineseResult");
  79.  
  80. for (int i = 0; i < nodeList.getLength(); i++) {
  81. Node node = nodeList.item(i);
  82. result = node.getFirstChild().getNodeValue();
  83. System.out.println(node.getFirstChild().getNodeValue());
  84. }
  85. } catch (Exception e) {
  86. throw e;
  87. } finally {
  88. if (is != null) {
  89. is.close();
  90. }
  91. }
  92.  
  93. return result;
  94. }
  95.  
  96. public static void main(String[] args) throws Exception {
  97. new Simple2TraditionalServiceImpl().getTraditionalChinese("���յ�");
  98. }
  99. }

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. id="WebApp_ID" version="2.5">
  6. <display-name>ToolsForSimpleToTraditional</display-name>
  7. <welcome-file-list>
  8. <welcome-file>index.html</welcome-file>
  9. <welcome-file>index.jsp</welcome-file>
  10. </welcome-file-list>
  11. <servlet>
  12. <description></description>
  13. <display-name>SimpleToTraditionalServlet</display-name>
  14. <servlet-name>SimpleToTraditionalServlet</servlet-name>
  15. <servlet-class>com.fit.test01.SimpleToTraditionalServlet</servlet-class>
  16. </servlet>
  17. <servlet-mapping>
  18. <servlet-name>SimpleToTraditionalServlet</servlet-name>
  19. <url-pattern>/simple2traditional</url-pattern>
  20. </servlet-mapping>
  21. </web-app>

附件为全部的工程代码,下载下来导入到Eclipse中可以直接在tomcat中跑起来,不用做什么配置,也不依赖于其他jar包等。

运行页面的结果如下图:

猜你在找的Ajax相关文章