Servlet中对request对象功能

 ##JAVA 萌新学习经历

1. request对象获取请求消息数据

      1. 获取请求行数据
              

                       * 方法:
                    1. 获取请求方式 :GET
                        * String getMethod()  
                    2. (*)获取虚拟目录:
                        * String getContextPath()
                    3. 获取Servlet路径: 
                        * String getServletPath()
                    4. 获取get方式请求参数:name=zhangsan
                        * String getQueryString()
                    5. (*)获取请求URI:
                        * String getRequestURI():      
                        * StringBuffer getRequestURL() 

                        * URL:统一资源定位符 : http://localhost/day14/demo1    
                        * URI:统一资源标识符 : /day14/demo1                 
                    
                    6. 获取协议及版本:HTTP/1.1
                        * String getProtocol()

                    7. 获取客户机的IP地址:
                        * String getRemoteAddr()

      注: 快速创建Servlet,  实现创建好JAVAEE项目,这里我选择JAVAEE 7 勾选Web Application 这里不用Web.xml 配置 , 我们使用注解进行配置 ,在Edit Configurations中 为了方便起见 设置端口号为HTTP默认端口号80 , 并且设置虚拟路径为/ 即可,再创建一个包,new 一个 Servlet 即可 , 该类会自动实现HttpServlet借口, 并复写 dopost 和 doget方法。

具体代码:

package 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;

/**
 * 快速创建servlet
 */
@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 method = request.getMethod();
        System.out.println("请求方式: "+method);
       //2.获取虚拟目录:
        String contextPath = request.getContextPath();
        System.out.println("虚拟目录: "+contextPath);
       //3.获取Servlet路径
        String servletPath = request.getServletPath();
        System.out.println("Servlet路径: "+servletPath);
       //4.获取get方式请求参数
        String queryString = request.getQueryString();
        System.out.println("get方式请求参数: "+queryString);
       //5.获取请求URI:
        String requestURI = request.getRequestURI();
        System.out.println("URI: "+requestURI);
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("URL: "+requestURL);
       //6.获取协议和版本:
        String protocol = request.getProtocol();
        System.out.println("协议和版本: "+protocol);
       //7.获取客户机的IP地址
        String remoteAddr = request.getRemoteAddr();
        System.out.println("客户机的IP地址: "+remoteAddr);


    }
}

启动tomcat服务器后 , 打开浏览器 在地址栏输入http://local/注解中配置的路径,即可访问,运行结果:

本次分享简单测试了request对象获取请求行数据方法的 简单实践 ,希望对初学者有帮助。

猜你喜欢

转载自blog.csdn.net/weixin_53113793/article/details/117432623
今日推荐