Java培训JavaWeb之HttpServletRequest接口

该接口是ServletRequest接口的子接口,封装了HTTP请求的相关信息,由Servlet容器创建其实现类对象并传入service(ServletRequest req, ServletResponse res)方法中。我们请求的详细信息都可以通过HttpServletRequest接口的实现类对象获取。这个实现类对象一般都是容器创建的,我们不需要管理。

前端培训

HttpServletRequest主要功能

1 获取请求参数

1)什么是请求参数?

前端培训

请求参数就是浏览器向服务器提交的数据

2)浏览器向服务器如何发送数据

a)附在url后面,如:http://localhost:8989/MyServlet/MyHttpServlet?userId=20

前端培训

b)通过表单提交

前端培训

<form action="MyHttpServlet" method="post">

                  你喜欢的足球队<br /><br />

                  巴西<input type="checkbox" name="soccerTeam" value="Brazil" />

                  德国<input type="checkbox" name="soccerTeam" value="German" />

                  荷兰<input type="checkbox" name="soccerTeam" value="Holland" />

                  <input type="submit" value="提交" />

         </form>

前端培训

 

3)使用HttpServletRequest对象获取请求参数

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                       //一个name对应一个值

                       String userId = request.getParameter("userId");

                       System.out.println("userId="+userId);

            }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                       //一个name对应一组值

                       String[] soccerTeams = request.getParameterValues("soccerTeam");

                       for(int i = 0; i < soccerTeams.length; i++){

                                   System.out.println("team "+i+"="+soccerTeams[i]);

                       }

            }

前端培训

2 在请求域中保存数据

数据保存在请求域中,可以转发到其他Servlet或者jsp页面,这些Servlet或者jsp页面就会从请求中再取出数据

前端培训

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  //将数据保存到request对象的属性域中

                  request.setAttribute("attrName", "attrValueInRequest");

                  //两个Servlet要想共享request对象中的数据,必须是转发的关系

                  request.getRequestDispatcher("/ReceiveServlet")

                                   .forward(request, response);

         }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  //从request属性域中获取数据

                  Object attribute = request.getAttribute("attrName");

                  System.out.println("attrValue="+attribute);

         }

3、转发页面

4、获取请求头相关信息

想要了解跟多关于Java培训课程内容欢迎关注尚硅谷Java培训,尚硅谷除了这些技术文章外还有免费的高质量Java培训课程视频供广大学员下载学习