Servlet-中文乱码解决

HTML表单: css

POST提交方式提交表单过程不产生乱码 html

<!DOCTYPE html>
<html>
  <head>
    <title>form.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
  <h1>个人表单</h1>
  <form action="/Encoding/GetInfo" method="get">
  u:<input type="text" name="username"/>
  <input type="submit" value="提交"/>
  <a href="/Encoding/GetInfo?username=哈后">aa</a>
  </form>
  </body>
</html>

 

GetInfo Servlet: java

package com.pas;

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;

import com.pas.util.MyTools;

public class GetInfo extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		//设置接收编码格式 保证接收到不是乱码
		request.setCharacterEncoding("utf-8");
		//Mytool 用于Get方式乱码处理
		String u=MyTools.getNewString(request.getParameter("username"));
		System.out.println(u);
		//传递给下一页面
		//java.net.URLEncoder.encode用于IE6版本及其如下浏览器
		response.sendRedirect("/Encoding/Wel?yy="+java.net.URLEncoder.encode(u,"utf-8"));
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}

 

转发Servlet Wel: 浏览器

package com.pas;

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;

import com.pas.util.MyTools;

public class Wel extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("gb2312");
		PrintWriter out = response.getWriter();
		String u=MyTools.getNewString(request.getParameter("yy"));
		System.out.println(u);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}

 

Mytool工具: 工具

package com.pas.util;

import java.io.UnsupportedEncodingException;

public class MyTools {

	public static String getNewString(String old) throws UnsupportedEncodingException
	{
		return new String(old.getBytes("iso-8859-1"),"utf-8");
	}
}
相关文章
相关标签/搜索