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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)