那么如何让解决呢?
public class RequsetDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //post提交的乱码问题 request.setCharacterEncoding("utf-8"); //获取超链接传递过来的数据 System.out.println("-----获取超链接传递过来的数据-----"); String name = request.getParameter("name"); String pwd = request.getParameter("password"); System.out.println(name); System.out.println(pwd); System.out.println("-----获取表单传递过来的数据-----"); String nickname = request.getParameter("nickname"); System.out.println(nickname); String[] hobbys = request.getParameterValues("hobby"); //System.out.println(Arrays.toString(hobbys)); for (int i = 0; i < hobbys.length; i++) { //如果是get提交,处理乱码问题 String hb = hobbys[i]; //把中文转换成字节 byte[] ch = hb.getBytes("iso-8859-1"); System.out.println(Arrays.toString(ch));. //再把字节以指定编码组合 String str = new String(ch,"utf-8"); //或者简写为 //String str=new String(request.getParameter("nickname").getBytes("ISO-8859-1"),"utf-8"); System.out.println(str); /* *或者服务器的server.xml中的 *Connector标签中添加URIEncoding="utf-8(也就是设置端口的那一个标签). *如下 *<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="utf-8"/> * */ } } }
在网上也有其他的解决方式,比如添加编码过滤器(如spring中的),又或是自定义编码过滤器等等:
Spring中的编码过滤器 <!-- 编码过滤器 --> <filter> <filter-name>Spring character encoding filter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>gb2312</param-value> </init-param> </filter> <filter-mapping> <filter-name>Spring character encoding filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>