Http请求参数编码问题

一、Http请求参数编码问题:
1、问题:
1)页面源码,样式:
Http请求参数编码问题_第1张图片
2)servlet代码,结果:
Http请求参数编码问题_第2张图片
3)问题分析:
Http请求参数编码问题_第3张图片
4)解决问题:
方式一:手动解码:
String name = new String(name.getBytes("iso-8859-1"),"utf-8");
Http请求参数编码问题_第4张图片
问题处理:
Http请求参数编码问题_第5张图片
方式二:request.setCharacterEncoding("utf-8");
方式三:通过修改配置文件的方式(但是不建议):
tomcat目录下–>conf–>server.xml–>在修改端口号的位置处最后添加一段代码:……URIEncoding=”utf-8”/>
5)方式一方式二整合代码:

package sram.request;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;

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

public class FifthRequest extends HttpServlet {
    //统一方便地获取请求参数的方法
    public void doGet(HttpServletRequest request, HttpServletResponse 
            response)throws ServletException, IOException {
        /**
         * 设置参数查询的编码
         * 该方法只能对请求实体内容的数据编码起作用。POST提交的数据在实体内容中,所以该方法对POST方法有效!
         * GET方法的参数放在URI后面,所以对GET方式无效!!!
         */
        request.setCharacterEncoding("utf-8");
        //获得所有参数的名字
        Enumeration enums = request.getParameterNames();
        while(enums.hasMoreElements()){
            String paramName = enums.nextElement();
            if("hobit".equals(paramName)){
            //注意:paramName=="hobit"
                /**
                 * getParameterValues(name): 根据参数名获取参数值(可以获取多个值的同名参数)
                 */
                String[] value = request.getParameterValues("hobit");
                System.out.print("hobit:");
                for(String h:value){
                    if("GET".equals(request.getMethod())){
                        //手动重新解码(iso-8859-1 字符串-> utf-8 字符串)
                        h = new String(h.getBytes("iso-8859-1"),"utf-8");
                    }
                    System.out.print(h+",");
                }
                System.out.println();
            }else{
                String value = request.getParameter(paramName);
                if("GET".equals(request.getMethod())){
                    //手动重新解码(iso-8859-1 字符串-> utf-8 字符串)
                    value = new String(value.getBytes("iso-8859-1"),"utf-8");
                }
                System.out.println(paramName+":"+value);
            }
        }
    }
    //由于doGet()中获取参数的方式通用,所以只要调用doGet()方式即可
    protected void doPost(HttpServletRequest request, HttpServletResponse
            response)throws ServletException, IOException {
        this.doGet(request, response);
    }
}

注意事项:
1、手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");这种方式post、get均可使用。
2、request.setCharacterEncoding("utf-8");post专用,get用不了。
3、request.setCharacterEncoding("utf-8");如果使用这段代码建议放在方法的第一行。
4、if("hobit".equals(paramName)){//错误形式:paramName=="hobit"注意这段代码。

你可能感兴趣的:(Http请求参数编码问题)