Request请求参数中文乱码问题

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>请求</title>
</head>
<body>
    <form method="get" action="/myRequest/requestDemo4">
        <input type="text" placeholder="请输入用户名" name="name" >
        <input type="submit" value="提交">
    </form>
</body>
</html>

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

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请求参数中文乱码问题

 

Request请求参数中文乱码问题

请求结束,后台输出

Request请求参数中文乱码问题

中文能正常输出

把表单改为post请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>请求</title>
</head>
<body>
    <form method="post" action="/myRequest/requestDemo4">
        <input type="text" placeholder="请输入用户名" name="name" >
        <input type="submit" value="提交">
    </form>
</body>
</html>

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

Request请求参数中文乱码问题

 

出现了乱码,不要怕,加一行代码,因为我们的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请求参数中文乱码问题

这就解决了乱码问题

上一篇:19 自动生成接口文档


下一篇:狂神说java超市管理系统filten