HttpServletRequest对象

Posted suyang-java

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpServletRequest对象相关的知识,希望对你有一定的参考价值。

    当浏览器向服务器发送请求时,web容器会把浏览器的请求信息封装到一个HttpServletRequest对象中去,用户可以通过这个对象获取请求的头信息,请求提交的参数,请求的路径,获取客户端的信息和请求的转发等。

    一、获取客户端信息

    (1)getRequestURL():返回客户端发出请求时完整的URL地址。

    (2)getRequestURI():返回请求行中的资源名部分。

    (3)getQueryString():返回请求行中的参数部分。

    (4)getPathInfo():返回请求URL中的额外路径信息。额外路径信息是请求URL中的位于Servlet的路径之后和查询参数之前的内容,它以“/”开头。

    (5)getRemoteAddr():返回客户端的ip地址。

    (6)getRemoteHost():返回客户端的完整的主机名。

    (7)getLocalAddr():获取web服务器的ip地址。

    (8)getLocalName():获取web服务器的主机名。

public class TestRequestServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        String requestURL = request.getRequestURL().toString();
        String requestURI =  request.getRequestURI();
        String queryString = request.getQueryString();
        String pathInfo = request.getPathInfo();
        String remoteAddr = request.getRemoteAddr();
        int remotePort = request.getRemotePort();
        String remoteHost = request.getRemoteHost();
        String localAddr = request.getLocalAddr();
        String localName = request.getLocalName();
        int localPort = request.getLocalPort();
        writer.println("requestURL:"+requestURL);
        writer.println("<br/>");
        writer.println("requestURI:"+requestURI);
        writer.println("<br/>");
        writer.println("queryString:"+queryString);
        writer.println("<br/>");
        writer.println("pathInfo:"+pathInfo);
        writer.println("<br/>");
        writer.println("remoteAddr:"+remoteAddr);
        writer.println("<br/>");
        writer.println("remoteHost:"+remoteHost);
        writer.println("<br/>");
        writer.println("localAddr:"+localAddr);
        writer.println("<br/>");
        writer.println("localName:"+localName);
        writer.println("<br/>");
        writer.println("remotePort:"+remotePort);
        writer.println("<br/>");
        writer.println("localPort:"+localPort);
        writer.flush();
        writer.close();
    }

}

在浏览器上输入地址:http://test.manager.com:8080/web/request?id=12

技术图片

 

     二、获取客户机的请求头信息

    (1)getHeader(string name):获取请求头中name对应的值

    (2)getHeaderNames():获取请求中的所有的name,返回一个Enumeration<String>

    (3)getHeaders(String name):获取请求头中name对应的所有值,返回一个Enumeration<String>

public class TestRequestHeader extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        Enumeration<String> enums =  request.getHeaderNames();
        writer.println("获取请求头信息如下:<br/>");
        while(enums.hasMoreElements()){
            String name = enums.nextElement();
            String value = request.getHeader(name);
            writer.println(name+":"+value+"<br/>");
        }
        writer.flush();
        writer.close();
    }
}

在浏览器中输入:http://test.manager.com:8080/web/requestheader

技术图片

 

     三、获取客户机请求参数

    (1)getParameter(String name):根据name获取请求参数的值。

    (2)getParameterValues(String name):根据name获取请求的参数列表。

    (3)getParameterMap():返回的是一个Map类型的值,该返回值记录着前端(如jsp页面)所提交请求中的请求参数和请求参数值的映射关系。(编写框架时常用)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; utf-8">
<title>Insert title here</title>
</head>
<body>
    <form action="<%=request.getContextPath()%>/getParameterRequest" method="post">
        <div>
           <span>名字:</span>
           <input type="text" name="name" placeholder="请输入名字">
        </div>
        <div>
           <span>密码:</span>
           <input type="password" name="password" placeholder="请输入密码">    
        </div>
        <div>
           <span>性别:</span>
            <input type="radio" name="sex" value="男" checked><input type="radio" name="sex" value="女"></div>
        <div>
           <span>爱好:</span>
            <input type="checkbox" name="hobby" value="唱歌">唱歌
            <input type="checkbox" name="hobby" value="上网">上网
            <input type="checkbox" name="hobby" value="打游戏">打游戏
            <input type="checkbox" name="hobby" value="游泳">游泳
            <input type="checkbox" name="hobby" value="睡觉">睡觉
        </div>
        <div>
           <span>所在城市:</span>
           <select name="city">
              <option value="北京">北京</option>
              <option value="上海">上海</option>
              <option value="广州">广州</option>
              <option value="深圳">深圳</option>
           </select>
        </div>
        
         <dir>
             <input type="submit" value="提交" />     
        </dir>
    </form>
</body>
</html>

技术图片
 

编写一个servlet通过HttpServletRequest对象获取参数:

public class TestRequestParam  extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type","text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8"); //解决post方式提交request接收中文乱码问题
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String city = request.getParameter("city");
        String[] hobbys= request.getParameterValues("hobby");
        String hobbyStr = String.join(",", hobbys);
        PrintWriter writer =  response.getWriter();
        writer.print("name参数为:"+name+"<br/>");
        writer.print("password参数为:"+password+"<br/>");
        writer.print("sex参数为:"+sex+"<br/>");
        writer.print("city参数为:"+city+"<br/>");
        writer.print("hobbyStr参数为:"+hobbyStr+"<br/>");
        writer.flush();
        writer.close();
    }

}

浏览器输出:

技术图片

    三、请求的转发

    请求转发指一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理。在Servlet中我们可以使用两种方式实现请求的转发:1、使用ServletContext对象的getRequestDispatcher(path)或者使用HttpServletRequest对象的getRequestDispatcher(path)方法获取RequestDispatcher对象,然后调用RequestDispatcher对象的forward(request,response)方法。

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; utf-8">
<title>Insert title here</title>
</head>
<body>
    <form action="<%=request.getContextPath()%>/testReqestForwar1" method="post">
        <div>
           <span>用户名:</span>
           <input type="text" name="name" placeholder="请输入名字">
        </div>
         <div>
             <input type="submit" value="提交" />     
        </div>
    </form>
</body>
</html>

TestReqestForward1:

public class TestReqestForward1 extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/testReqestForwar2").forward(request, response);
    }
    
   
}

TestReqestForward2:

public class TestReqestForward2 extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type","text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8"); //解决post方式提交request接收中文乱码问题
        String name = request.getParameter("name");
        PrintWriter writer =  response.getWriter();
        writer.print("name参数为:"+name+"<br/>");
    }
    
   
}

请求到了TestReqestForward1中的doPost方法后被重定向到了TestReqestForward2。

技术图片

 

 这里我找到了一幅时序图可以很清楚的展示出请求是如何转发到TestReqestForward2。

技术图片

 

 转载图片地址:https://img-blog.csdn.net/20160427164748927?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast。

 

 

    

以上是关于HttpServletRequest对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在 @service 类中获取 HttpServletRequest 对象

为啥 HttpServletRequest 对象在从一个 servlet 转发到另一个 servlet 时会发生变化?

HttpServletRequest对象

HttpServletRequest对象

HttpServletRequest和ServletRequest的区别以及HttpServletRequest对象方法的用法

HttpServletRequest和HttpServletResponse对象