Request请求参数中文乱码问题

少说点话,先来个表单,get请求,提交跑/myRequest/requestDemo4接口




    
    请求


    

 所以来个接口,接收参数输出

package com.lingaolu.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 林高禄
 * @create 2020-07-07-12:06
 */
@WebServlet("/requestDemo4")
public class RequestDemo4 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println("名字为:"+name);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println("名字为:"+name);
        this.doPost(request,response);
    }
}

表单发出请求

Request请求参数中文乱码问题_第1张图片

 

Request请求参数中文乱码问题_第2张图片

请求结束,后台输出

Request请求参数中文乱码问题_第3张图片

中文能正常输出

把表单改为post请求




    
    请求


    

 同样的操作发出请求,后台输出

Request请求参数中文乱码问题_第4张图片

 

出现了乱码,不要怕,加一行代码,因为我们的html表单的编码方式为uft-8,所以接口加上这段代码request.setCharacterEncoding("utf-8");

package com.lingaolu.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 林高禄
 * @create 2020-07-07-12:06
 */
@WebServlet("/requestDemo4")
public class RequestDemo4 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        System.out.println("名字为:"+name);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println("名字为:"+name);
        this.doPost(request,response);
    }
}

重启,还是post请求,请求,后台输出

Request请求参数中文乱码问题_第5张图片

这就解决了乱码问题

你可能感兴趣的:(Web核心,Request,中文乱码,post请求)