当前位置: 首页 > news >正文

HttpServletRequest常用功能简介-笔记

javax.servlet.http.HttpServletRequest 是 ServletRequest 接口的子接口,专用于处理 HTTP 协议相关的请求。它提供了访问请求行、请求头、请求参数以及请求属性等方法。

1.请求行(Request Line)

✅ 功能说明

请求行包含客户端发送的 HTTP 请求的基本信息,包括:

  • HTTP 方法:如 GETPOSTPUTDELETE
  • 请求 URI:如 /user/login
  • 协议版本:如 HTTP/1.1
  • 查询字符串:如 ?username=admin
方法说明
getMethod()获取 HTTP 方法(如 GET、POST)。
getRequestURI()获取请求的 URI(如 /app/user)。
getRequestURL()获取完整的 URL(如 http://localhost:8080/app/user?name=Tom)。
getQueryString()获取查询字符串(如 name=Tom&age=25)。
getProtocol()获取协议版本(如 HTTP/1.1)。

🧩 使用场景

  • 根据请求方法决定执行逻辑(如 GET 显示表单,POST 处理提交)
  • 日志记录或访问统计
  • 基于 URI 的路由处理

🔧 示例代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String method = request.getMethod(); // 获取 HTTP 方法String requestURI = request.getRequestURI(); // 获取请求 URIStringBuffer requestURL = request.getRequestURL(); // 获取完整 URLString queryString = request.getQueryString(); // 获取查询字符串String protocol = request.getProtocol(); // 获取协议版本System.out.println("Method: " + method);System.out.println("Request URI: " + requestURI);System.out.println("Request URL: " + requestURL.toString());System.out.println("Query String: " + queryString);System.out.println("Protocol: " + protocol);
}

2. 请求头(Request Headers)

✅ 功能说明

请求头包含客户端发送的元数据,如:

  • User-Agent:客户端浏览器信息
  • Accept:客户端可接受的内容类型
  • Content-Type:请求体的格式
  • Referer:请求来源页面
方法说明
getHeader(String name)获取指定头字段的值。
getHeaders(String name)获取所有同名头字段的值(返回 Enumeration<String>)。
getHeaderNames()获取所有头字段名称(返回 Enumeration<String>)。
getContentType()获取 Content-Type 头字段值。
getContentLength()获取 Content-Length 头字段值(以字节为单位)。

🧩 使用场景

  • 根据 User-Agent 判断客户端类型(手机 / PC)
  • 内容协商(如返回 JSON 或 HTML)
  • 安全校验(如检查 Referer 防止跨站攻击)

🔧 示例代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("=== Request Headers ===");Enumeration<String> headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()) {String name = headerNames.nextElement();String value = request.getHeader(name);System.out.println(name + ": " + value);}// 获取特定头信息String userAgent = request.getHeader("User-Agent");System.out.println("\nUser-Agent: " + userAgent);
}

3.请求参数(Request Parameters)

✅ 功能说明

请求参数是客户端提交的数据,主要来源于:

  • URL 查询字符串(如 ?username=admin
  • 表单数据(如 <form method="POST"> 提交)
方法说明
getParameter(String name)获取单个参数值(如 username)。
getParameterValues(String name)获取多个参数值(如复选框 hobby,可以选择多个爱好)。
getParameterMap()获取所有参数的键值对(返回 Map<String, String[]>)。
getParameterNames()获取所有参数名称(返回 Enumeration<String>)。

🧩 使用场景

  • 表单处理(登录、注册)
  • 分页、搜索、过滤等查询条件
  • API 接口的参数接收

🔧 示例代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//对于 POST 请求,建议在 getParameter() 前,先设置 request.setCharacterEncoding("UTF-8")request.setCharacterEncoding("UTF-8"); // 设置编码System.out.println("=== Request Parameters ===");String username = request.getParameter("username");String[] hobbies = request.getParameterValues("hobby");System.out.println("Username: " + username);System.out.println("Hobbies: " + Arrays.toString(hobbies));// 遍历所有参数Enumeration<String> paramNames = request.getParameterNames();while (paramNames.hasMoreElements()) {String name = paramNames.nextElement();String value = request.getParameter(name);System.out.println(name + ": " + value);}
}

4. 请求属性(Request Attributes)

✅ 功能说明

请求属性是服务器内部在处理请求时传递的数据,通常通过 setAttribute() 设置,通过 getAttribute() 获取。

方法说明
setAttribute(String name, Object value)设置请求属性。
getAttribute(String name)获取请求属性。
removeAttribute(String name)移除请求属性。
getAttributeNames()获取所有属性名称(返回 Enumeration<String>)。

🧩 使用场景

  • 在多个 Servlet 或 JSP 页面之间共享数据
  • 从过滤器传递数据到目标资源
  • 传递业务处理结果或错误信息

🔧 示例代码


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 设置属性request.setAttribute("message", "Hello from Servlet!");// 获取属性String message = (String) request.getAttribute("message");System.out.println("Message: " + message);// 遍历所有属性Enumeration<String> attributeNames = request.getAttributeNames();while (attributeNames.hasMoreElements()) {String attrName = attributeNames.nextElement();Object attrValue = request.getAttribute(attrName);System.out.println(attrName + ": " + attrValue);}}

5. 完整示例

以下是一个综合示例,展示如何在 doGet 方法中使用上述方法:

@WebServlet("/example")
public class ExampleServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 请求行System.out.println("=== Request Line ===");System.out.println("Method: " + request.getMethod());System.out.println("Request URI: " + request.getRequestURI());System.out.println("Request URL: " + request.getRequestURL().toString());System.out.println("Query String: " + request.getQueryString());// 请求头System.out.println("\n=== Request Headers ===");Enumeration<String> headers = request.getHeaderNames();while (headers.hasMoreElements()) {String header = headers.nextElement();System.out.println(header + ": " + request.getHeader(header));}// 请求参数System.out.println("\n=== Request Parameters ===");Enumeration<String> params = request.getParameterNames();while (params.hasMoreElements()) {String param = params.nextElement();System.out.println(param + ": " + request.getParameter(param));}// 请求属性request.setAttribute("testAttr", "AttributeValue");System.out.println("\n=== Request Attributes ===");System.out.println("testAttr: " + request.getAttribute("testAttr"));}
}

⚠️ 注意事项

  1. 字符编码:对于 POST 请求,建议在 getParameter() 前,先设置 request.setCharacterEncoding("UTF-8")
  2. 文件上传:若需处理文件上传,需使用 Part 或第三方库(如 Apache Commons FileUpload)。
  3. 安全:避免直接信任客户端提交的数据,需进行验证和过滤。
http://www.xdnf.cn/news/458551.html

相关文章:

  • Go 中闭包的常见使用场景
  • 【Spring Cloud Gateway】Nacos整合遇坑记:503 Service Unavailable
  • 【人工智能-agent】--Dify+Mysql+Echarts搭建了一个能“听懂”人话的数据可视化助手!
  • 全国青少年信息素养大赛 Python编程挑战赛初赛 内部集训模拟试卷八及详细答案解析
  • 数据科学和机器学习的“看家兵器”——pandas模块 之四
  • 红黑树:数据世界的平衡守护者
  • Android开发-在应用之间共享数据
  • HTML 表格与div深度解析区别及常见误区
  • 【Linux】socket网络编程基础
  • 解决ubuntu20中tracker占用过多cpu,引起的风扇狂转
  • 从算力困境到创新突破:GPUGEEK如何重塑我的AI开发之旅
  • 【HCIA】策略路由
  • C#+WPF+prism+materialdesign创建工具主界面框架
  • 安装win11硬盘分区MBR还是GPT_装win11系统分区及安装教程
  • MongoDB数据库深度解析:架构、特性与应用场景
  • MySQL-数据库分布式XA事务
  • 深度解析 Meta 开源 MR 项目《North Star》:从交互到渲染的沉浸式体验设计
  • 可解释性AI 综述《Explainable AI for Industrial Fault Diagnosis: A Systematic Review》
  • elementUI 循环出来的表单,怎么做表单校验?
  • elementUI如何动态增减表单项
  • 【Trae插件】从0到1,搭建一个能够伪装成网页内容的小说阅读Chrome插件
  • 交叉编译源码的方式移植ffmpeg-rockchip
  • 【学习心得】WSL2安装Ubuntu22.04
  • 前端npm的核心作用与使用详解
  • 【kafka】基本命令
  • Node.js 循环依赖问题详解:原理、案例与解决方案
  • 【hadoop】Kafka 安装部署
  • “傅里叶变换算法”来检测纸箱变形的简单示例
  • Android Coli 3 ImageView load two suit Bitmap thumb and formal,Kotlin(七)
  • MySQL 8.0 OCP 1Z0-908 101-110题