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

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

最近一直在学习新的东西,当然也在回顾一些老的知识点。本博客涉及的主要是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,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包等。

运行页面的结果如下图:

原文链接:https://www.f2er.com/ajax/164751.html

猜你在找的Ajax相关文章