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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM