02.Get请求中文乱码问题

 

package com.gyf.web.servlet.lesson02;

import java.io.IOException;
import java.util.Arrays;

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


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * Get请求中文乱码问题
         * 1.在tomcat8以上的版本,get请求已经不会有乱码的问题
         * 2.在tomcat7以前的版本,get请求有乱码的问题
         * 
         * 原因?
         * 客户端传到服务器的编码是UTF-8
         * 在 tomcat7中,在接收客户端的请求数据是以ISO-8859-1的形式来接收
         * 在tomcat8以后,在接收客户端的请求数据就是UTF-8
         */
        
        //1.获取请求参数
        String username = request.getParameter("username");
        String[] hobbies =request.getParameterValues("hobby");
        
        //byte[] buf = {23,18,23}
        //2.还原UTF-8编码
        username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
        
        for(int i=0;i<hobbies.length;i++){
            String hobby = hobbies[i];
            hobby = new String(hobby.getBytes("ISO-8859-1"), "UTF-8");
            //替换
            hobbies[i] = hobby;
        }
        /*for(String hobby : hobbies){
            
            System.out.println("hobby:" + hobby);
        }*/
    
        
        
        System.out.println("username:" + username);
        System.out.println("hobbies:" + Arrays.toString(hobbies));
    
    }

}

 

posted @ 2019-01-25 00:23  expworld  阅读(111)  评论(0)    收藏  举报