javaweb中解决get与post中文乱码问题的方式

2023-09-03

package com.hh.RequestAndResponse;
/**
 * @author hh
 * @version 1.0
 * @DATE 2023-09-03 12:51:44
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/req6")
public class RequestServlet6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post方式的解决方式
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        System.out.println("未编码解码之前 " + username);
        //get的解决方式,先解码后编码
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        username = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("编码解码之后 " + username);




    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

 

posted @ 2023-09-03 13:15  努力是一种常态  阅读(44)  评论(0编辑  收藏  举报