Request获取请求行数据的方法介绍以及代码演示
Request获取请求行数据的方法介绍
获取请求行数据:
GET /demo3?name=zhangsan HTTP/1.1
方法:
1、获取请求方式:GET
String getMethod();
2、获取虚拟目录: /
String getContextPath();
3、获取Servlet路径: /demo3
String getServletPath();
4、获取get方式的请求参数:name=zhangsan
String getQueryString();
5、获取请求URL路径:/demo3
String getRequestURI(); /demo3
StringBUffer getRequestURL(); http://localhost/demo3
URL:统一资源定位符
URI:统一资源标识符
6、获取协议和版本号:HTTP/1.1
String getProtocol();
7、获取客户机的IP地址:
String getRemoteAddr();
package com.tomcat1.web.request; 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; /** * 演示Request对象获取请求行数据 */ @WebServlet("/requestDemo1") public class RequestDemo1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 1、获取请求方式:GET * String getMethod(); * 2、获取虚拟目录: / * String getContextPath(); * 3、获取Servlet路径: /requestDemo1 * String getServletPath(); * 4、获取get方式的请求参数:name=zhangsan * String getQueryString(); * 5、获取请求URL路径:/requestDemo1 * String getRequestURI(); /requestDemo1 * StringBUffer getRequestURL(); http://localhost/requestDemo1 * 6、获取协议和版本号:HTTP/1.1 * String getProtocol(); * 7、获取客户机的IP地址: * String getRemoteAddr(); */ //1、获取请求方式:GET String method = request.getMethod(); System.out.println(method); //2、获取虚拟目录: /day14 String contextPath = request.getContextPath(); System.out.println(contextPath); //3、获取Servlet路径: /demo3 String servletPath = request.getServletPath(); System.out.println(servletPath); //4、获取get方式的请求参数:name=zhangsan String queryString = request.getQueryString(); System.out.println(queryString); //5、获取请求URL路径:/day14/demo3 String requestURI = request.getRequestURI(); System.out.println(requestURI); StringBuffer requestURL = request.getRequestURL(); System.out.println(requestURL); //6、获取协议和版本号:HTTP/1.1 String protocol = request.getProtocol(); System.out.println(protocol); //7、获取客户机的IP地址: String remoteAddr = request.getRemoteAddr(); System.out.println(remoteAddr); } }


浙公网安备 33010602011771号