深入体验JavaWeb开发内幕——Request中的乱码问题及解决

前面我们提到了Response对象中出现乱码问题及相应的解决措施,那么在Request中如何解决编码问题呢?

下面来看具体的例子:

例如我想将一个form表单中的信息提取到并在控制台输出如图:

 

假设在服务端并未Request对象给指定编码时那么你在客户端添加信息如:

填入的信息有中文

假设设置表单的提交方式为post方式提交

则在服务端输出如下:

代码如下:

Register.html



  
    Register.html
	
    
    
    
    
    

  
  
  
  
用户名:
密码:  
性别:
籍贯:
简历:
&nsp;
爱好:
唱歌 跳舞 读书 看报
上传头像:




RequestLogin.java
package net.csdn.request;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestLogin extends HttpServlet 
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ 
getInformation(request); 
}
private void getParameter(HttpServletRequest request)
throws UnsupportedEncodingException
{
private void getInformation(HttpServletRequest request)
throws UnsupportedEncodingException {
//取出参数值 
String name = request.getParameter("username"); 
String pass = request.getParameter("password"); 
String sex = request.getParameter("sex"); 
String city = request.getParameter("city"); 
String intro = request.getParameter("intro"); 
String [] hobbies = request.getParameterValues("hobbies"); 
String hobby =""; 
//hobbies!=null对所取值为空时进行设置 
for(int i=0;hobbies!=null&&i

这是因为你在RegisterLogin.java中并没有给Request对象设置编码集,而Request对象的默认编码集是ISO8859-1是不支持汉字的,所以你只需要在此类中为其指明相应的编码即可:
改正:
  request.setCharacterEncoding("utf-8");
即可输出:



但是这种方式只在提交方式为post时有效当提交方式为get时是不起作用的。
即;


时即便在

RequestLogin.java
中再设置
  request.setCharacterEncoding("utf-8");
也不会起任何作用了如图:


 


这时就需要在
 
RequestLogin.java
中的含有中文的地方进行如下设置了即:
 String username = new String(name.getBytes("iso8859-1"),"utf-8");
         String introduction = new String(intro.getBytes("iso8859-1"),"utf-8");
 System.out.println("username:"+username);
           System.out.println("password:"+introduction);

此时再度测试时就OK了!如图



好了到这里,你大概已经知道该如何对Response和Request对象中的乱码问题进行操作了吧!





你可能感兴趣的:(深入体验JavaWeb开发内幕——Request中的乱码问题及解决)