javaweb: request.getParameter()、request.setAttribute()与request.getAttribute()的作用 (转)

出处:https://blog.csdn.net/qq_41937388/article/details/87972914

1、request.getParameter()方法是获取通过类似post,get等方式传入的数据,即获取客户端到服务端的数据,代表HTTP请求数据。

2、request.setAttribute()方法是将request.getParameter()方法获取的数据保存到request域中,即将获取的数据重新封装到一个域中。

3、request.getAttribute()方法是返回在request.setAttribute()封装的域中存在的数据。

下面我们通过一个例子来说明:

            

点击提交后 

               

详解:

首先创建一个简单的表单:

<form action="/test/Servlet"methon="post">
        用户名:<input type="text" name="username"><br>
        年龄:<input type="text" name="age"><br>
        <input type="submit" value="提交">
    </form>

Servlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、首先获取username和age属性值
        String username=request.getParameter("username");
        String age=request.getParameter("age");    
        // 2、将获取的数据保存到request域中
        request.setAttribute("username", username);
        request.setAttribute("age", age);
        // 3、请求跳转到另外一个页面
        request.getRequestDispatcher("show.jsp").forward(request,response);
    }
 
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

show.jsp代码:

返回在request.setAttribute()封装的域中存在的数据

<body>
    登录中的用户名为:<%=request.getAttribute("username")%><br><br>
    年龄:<%=request.getAttribute("age")    %>
</body>
原文地址:https://www.cnblogs.com/myseries/p/11482137.html