Detailed explanation based on the difference between request getattribute and request getparameter

  • 2020-04-01 01:44:28
  • OfStack

The HttpServletRequest class has both the getAttribute() method and the getParameter() method, which differ as follows:
1. The HttpServletRequest class has a setAttribute() method, but no setParameter() method;
2. When there is a link relationship between two Web components, the linked component obtains the request parameters through the getParameter() method;

For example, assume that there is a link between welcome.jsp and authenticate. JSP, and the following code is in the welcome.jsp:


<a href="authenticate.jsp?username=qianyunlai.com">authenticate.jsp </a>  
 //Or:  
 <form name="form1" method="post" action="authenticate.jsp">  
      Please enter the user name :<input type="text" name="username">  
     <input type="submit" name="Submit" value=" submit ">  
 </form> 

In authenticate. JSP, the request-getparameter (" username ") method is used to get the request parameter username:
< % String username = request. The getParameter (" username "); % >

3. When there is a forwarding relationship between two Web components, the forwarding target component shares the data in the request range with the forwarding source component through the getAttribute() method.
Assume a forwarding relationship between authenticate. JSP and hello.jsp. Authenticate. JSP wants to pass the current user name to hello. JSP. How do you pass this data? First, call the setAttribute() method in authenticate. JSP:


<%  
     String username=request.getParameter("username");  
     request.setAttribute("username",username);  
 %>  
 <jsp:forward page="hello.jsp" /> 

Get the user name in hello.jsp with the getAttribute() method:

<% String username=(String)request.getAttribute("username"); %>  
 Hello: <%=username %> 

4. Request-getattribute returns Object, request-getparameter returns String.


Related articles: