Difference between getAttribute() and getParameter() Difference between getAttribute() and getParameter() java java

Difference between getAttribute() and getParameter()


  • getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String

  • getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.


Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.

An attribute is a server variable that exists within a specified scope i.e.:

  • application, available for the life of the entire application
  • session, available for the life of the session
  • request, only available for the life of the request
  • page (JSP only), available for the current JSP page only


request.getParameter()

We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.

request.getAttribute()

We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.

For example,consider about first.jsp,

//First Page : first.jsp<%@ page import="java.util.*" import="java.io.*"%><% request.setAttribute("PAGE", "first.jsp");%><jsp:forward page="/second.jsp"/>

and second.jsp:

<%@ page import="java.util.*" import="java.io.*"%>From Which Page : <%=request.getAttribute("PAGE")%><br>Data From Client : <%=request.getParameter("CLIENT")%>

From your browser, run first.jsp?CLIENT=you and the output on your browser is

From Which Page : *first.jsp*Data From Client : you

The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.