servlet解决中文乱编的问题

来源:互联网 发布:怎么修改淘宝会员名 编辑:程序博客网 时间:2024/05/16 10:55

1. 解决中文乱编的问题

要求1:自行编写程序测试通过表单参数传递引起中文乱码的情况,并解决中文乱编的问题.

(1) 当提交的方式是POST,应该如何处理?

(2) 当提交的方式是GET,应该如何处理?

要求2:编写Servlet程序,Servlet页面中通过PrintWriter输出中文,解决此种乱码情况.



<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head></head><body><center><h1>解决中文乱编的问题</h1><form action="check" method="get"><table border="1"><tr><td colspan="2"><h2>Get提交方式</h2></td></tr><tr><td>文本:</td><td><input type="text" name="username"></td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form><form action="check" method="post"><table border="1"><tr><td colspan="2"><h2>Post提交方式</h2></td></tr><tr><td>文本:</td><td><input type="text" name="username"></td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form></center><pre>当把中文做为参数进行传递的时候,容易产生中文乱码问题,可采用如下方式解决:POST传递:request.setCharacterEncoding("GBK");GET传递:将接收过来的参数进行重新转码String name=request.getParameter("username");name=new String(name.getBytes("ISO8859-1"),"GBK");修改server.xmlURIEncoding="GBK"</pre></body></html>

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><servlet><servlet-name>encoding</servlet-name><servlet-class>com.mars.check</servlet-class></servlet><servlet-mapping><servlet-name>encoding</servlet-name><url-pattern>/check</url-pattern></servlet-mapping></web-app>


package com.mars;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class check extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=GBK");String newname = new String(request.getParameter("username").getBytes("ISO-8859-1"), "GBK");PrintWriter out = response.getWriter();out.print("<html><head></head><body>GET方式提交<br/><h2>" + newname);out.print("</h2></body></html>");out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=GBK");//request.setCharacterEncoding("GBK");System.out.println("调用doPost");String newname = request.getParameter("username");PrintWriter out = response.getWriter();out.print("<html><head></head><body>POST方式提交<br/><h2>" + newname);out.print("</h2></body></html>");out.close();}}