有的时候我们发送URL请求会带有中文参数,例如url.do?name=浴盆,这样直接发送会产生中文乱码的问题。
下面据个例子
请求http://localhost:8080/Url/url.do?name=浴盆
action 定义如下
package com.url.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class UrlAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String name = request.getParameter("name"); System.out.println(name); return null; } }
后台打印
14:02:05,317 INFO [STDOUT] ???è
那么我们在发送请求前就要对中文的参数进行处理,使其转化为特定的编码格式放入URL的参数中进行传递。
java提供了处理URL编码的类java.net.URLDecoder和java.net.URLEncoder;
在发送请求以前,我们利用java.net.URLEncoder来对中文参数编码
System.out.println(URLEncoder.encode("浴盆", "UTF-8"));
得到 %E6%B5%B4%E7%9B%86
我们再次请求http://localhost:8080/Url/url.do?name=%E6%B5%B4%E7%9B%86
后台打印
14:14:51,970 INFO [STDOUT] ??????
我们看到还是乱码,所以在action中还要对中文的参数进行处理
更改action
package com.url.action; import java.net.URLDecoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class UrlAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String name = request.getParameter("name"); name = URLDecoder.decode(name, "UTF-8"); System.out.println(name); return null; } }
后台打印
14:14:51,970 INFO [STDOUT] ??????
我们看到还是乱码
这是为什么呢,原来请求的信息放在request中,我们还要对request设置编码格式,才能得到正确的中文参数信息
再次更改action
package com.url.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class UrlAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); System.out.println(name); return null; } }
后台打印
14:21:47,728 INFO [STDOUT] 浴盆
我们看到已经得到了正确的参数值并不需要调用name = URLDecoder.decode(name, "UTF-8");
重要的是request.setCharacterEncoding("UTF-8");