请求参数解析和乱码

getParameter(name) --- String 通过name获得值
getParameterValues(name) --- String[ ] 通过name获得多值 checkbox
getParameterNames --- Enumeration<String> 获得所有请求参数名称组成的枚举
getParameterMap --- Map<String,String[ ]> 获取所有请求参数的组成的Map集合,注意,其中的键为String,值为String[]

获取请求参数时乱码问题:
浏览器发送的请求参数使用什么编码呢?当初浏览器打开网页时使用什么编码,发送就用什么编码。
服务器端获取到发过来的请求参数默认使用ISO8859-1进行解码操作,中文一定有乱码问题
对于Post方式提交的数据,可以设置request.setCharacterEncoding("gb2312");来明确指定获取请求参数时使用编码。但是此种方式只对Post方式提交有效。
对于Get方式提交的数据,就只能手动解决乱码:String newName = new String(name.getBytes("ISO8859-1"),"gb2312");此种方法对Post方式同样有效。
在tomcat的server.xml中可以配置http连接器的URIEncoding可以指定服务器在获取请求参数时默认使用的编码,从而一劳永逸的决绝获取请求参数时的乱码问题。也可以指定useBodyEncodingForURI参数,令request.setCharacterEncoding也对GET方式的请求起作用,但是这俩属性都不推荐使用,因为发布环境往往不允许修改此属性。


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");//--通知服务器以什么编码解码http请求中的实体内容,所以这行代码只能解决post提交的乱码

//对于get提交只能手动解决请求参数中的乱码
String username = request.getParameter("username");
username = new String(username.getBytes("iso8859-1"),"utf-8");
System.out.println(username);

// Enumeration<String> enumeration = request.getParameterNames();
// while(enumeration.hasMoreElements()){
// String name = enumeration.nextElement();
// String value = request.getParameter(name);
// System.out.println(name+":"+value);
// }
}

原文地址:https://www.cnblogs.com/superPerfect/p/4300670.html