Request和Response学习笔记4
Request 获取请求参数,中文乱码问题
实例引入:
-
创建一个html文件:garbled.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>中文乱码问题</title> </head> <body> <form action="/RequestResponseCharset_war_exploded/demo01" method="get"> <label><input type="text" name="username" placeholder="请输入用户名"></label><br> <label><input type="password" name="password" placeholder="请输入密码"></label><br> <input type="submit" value="get提交"> </form> <br> <form action="/RequestResponseCharset_war_exploded/demo01" method="post"> <label><input type="text" name="username" placeholder="请输入用户名"></label><br> <label><input type="password" name="password" placeholder="请输入密码"></label><br> <input type="submit" value="post提交"> </form> </body> </html>
-
创建一个类:CharsetGarbled.java
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; /** * @Author: YiHua Lee * @Version: 1.8.0_201 Java SE 8 * @Application: IntelliJ IDEA * @CreateTime: 2020/5/18 22:10 * @Description: */ @WebServlet("/demo01") public class CharsetGarbled extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求参数 String username = req.getParameter("username"); System.out.println(username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
-
启动服务器,浏览器访问:http://localhost:8080/RequestResponseCharset_war_exploded/garbled.html
-
get提交
控制台输出:
彩虹
-
post提交
控制台输出:
彩è¹
浏览器页面跳转到:http://localhost:8080/RequestResponseCharset_war_exploded/demo01
-
-
解决中文乱码问题
只需要改动doGet()方法即可:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置流的编码 req.setCharacterEncoding("utf-8"); // 获取请求参数 String username = req.getParameter("username"); System.out.println(username); }
-
重启服务器,再次访问:http://localhost:8080/RequestResponseCharset_war_exploded/garbled.html
并用post提交,控制台输出:
彩虹
浏览器页面跳转到:http://localhost:8080/RequestResponseCharset_war_exploded/demo01
参考文献
本文来自博客园,作者:LeeHua,转载请注明原文链接:https://www.cnblogs.com/liyihua/p/14477455.html