首页 > Web开发 > 详细

HttpServletRequest

时间:2021-01-13 23:51:32      阅读:0      评论:0      收藏:0      [点我收藏+]

HttpServletRequest

作用:它代表客户端的请求。用户访问服务器,请求中携带的所有数据会被封装到HttpServletRequest里,我们可以通过HttpServletRequest获取从客户端带来的所有信息。

常见应用:

获取前端传递的参数(重点)

写一个简单的登录表单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<form action="FifthServlet" method="post">
    <p>用户名:
        <input type="text" name="username">
    </p>
    <p>密码:
        <input type="password" name="password">
    </p>
    <p>爱好:
        <input type="checkbox" name="hobby" value="eat">吃
        <input type="checkbox" name="hobby" value="drink">喝
        <input type="checkbox" name="hobby" value="play">玩
        <input type="checkbox" name="hobby" value="merry">乐
    </p>
    <input type="submit" value="提交">
    <input type="reset" value="重置">
</form>

</body>
</html>

技术分享图片

再写servlet:

public class FifthServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //通过request.getParameter()获取单个值
        String username = request.getParameter("username");
        String password = request.getParameter("password");   
        response.getWriter().println(username);
        response.getWriter().println(password);
        
        //通过getParameterValues()获取多个值
        String[] hobbies = request.getParameterValues("hobby");
        for (String hobby : hobbies) {
            response.getWriter().println(hobby);
        }

    }

技术分享图片

请求转发(重点)

public class SixthServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/FirstServlet").forward(request,response);
    }

之前学习ServletContext的时候,ServletContext也能实现请求转发,这个可以仅做了解。request实现的请求转发是使用的最多的

HttpServletRequest

原文:https://www.cnblogs.com/xxgbl/p/14274680.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号