02jQuery异步传递中文字符串

1 test.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">
		<title>Insert title here</title>
		<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.4.3.js"></script>
		<script type="text/javascript">
			var a = encode('你好');
			ajaxText(a);
			
			function encode(value) {
				return encodeURIComponent(value);
			}
			
			function ajaxText(a) {
				$.ajax({
					url : "decode.do",
					type : "post",
					data : {
						param : a
					},
					dataType : "text",
					// 下面这种参数也可以达到encodeURIComponent(value)方法的效果
					//contentType: "application/x-www-form-urlencoded; charset=utf-8", 
					success : function(msg) {
						alert(msg);
					}
				});
			}
		</script>
	</head>
	<body>
		
	</body>
</html>

2 web.xml

...
	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>action.DemoServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
...

3 DemoServlet.java

package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		if (uri.endsWith("decode.do")) {
			String param = request.getParameter("param");
			String result = URLDecoder.decode(param, "UTF-8");
			
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(result);
			out.close();
		}
	}
}


你可能感兴趣的:(02jQuery异步传递中文字符串)