Request
-
概述:Request 和 Response 对象都是由 Web 服务器(Tomcat)创建的,我们来使用它们,Request 对象是用来 获取请求消息 的,Response 对象是用来 设置响应消息 的
-
Request 对象的原理
-
Request 对象的继承体系结构
Request 常用的功能
获取请求行数据
-
请求行
- 格式:请求方式 请求URL 请求协议/版本号
- 例子:GET /heng/demo?name=zs HTTP/1.1
-
统一资源
- URL:统一资源定位符
- 示例:http://localhost/heng/demo
- URI:统一资源标识符
- 示例:/heng/demo
- URL:统一资源定位符
-
方法
方法 作用 String getMethod() 获取请求方式 :GET String getContextPath() 获取虚拟目录(项目名称):/heng String getServletPath() 获取Servlet路径: /demo String getQueryString() 获取get方式请求参数:name=zs String getProtocol() 获取协议及版本:HTTP/1.1 String getRemoteAddr() 获取客户机的IP地址: String getRequestURI() 获取请求URI:/heng/demo StringBuffer getRequestURL() http://localhost/heng/demo -
示例代码
@WebServlet("/line") public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求方式 String method = req.getMethod(); // 获取虚拟目录,项目名称 String contextPath = req.getContextPath(); // 获取Servlet路径 String servletPath = req.getServletPath(); // 获取协议及版本 String protocol = req.getProtocol(); // 获取客户机的 IP 地址 String remoteAddr = req.getRemoteAddr(); // 获取请求 URI String requestURI = req.getRequestURI(); // 获取请求 URL StringBuffer requestURL = req.