Difference between getAttribute() and getParameter() - java

What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?

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.

It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name) method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on #Bozho's response, as additional information that can be useful for other people.

The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.

-getParameter() :
<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
</body>
</html>
request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
-getAttribute() :
request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.

getParameter - Is used for getting the information you need from the Client's HTML page
getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.

from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server
- typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these
encoded directly into the URL (after the ?, each in the form
name=value, and each pair separated by an &). Other times, they are
included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in
scoped attribues is ever transmitted outside the server unless you
explicitly make that happen. Attributes have String names, but store
Object values. Note that attributes are specific to Java (they store
Java Objects), while parameters are platform-independent (they are
only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag
files only), "request" (limited to the current client's request,
destroyed after request is completed), "session" (stored in the
client's session, invalidated after the session is terminated),
"application" (exist for all components to access during the entire
deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the
client, use scoped attributes when storing objects on the server for
use internally by your application only.

Another case when you should use .getParameter() is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp, you can access userName like this:
request.getParameter("userName")

Basic difference between getAttribute() and getParameter() is the return type.
java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

Related

How to process form by <jsp:setBean> and send it to servlet?

Could you help me to come up with solution.
There are JSP-page which sends form parameters to servlet.
Usually I parse parameters by HttpServletRequest.getParameter() which works fine for forms with tiny parameter numbers.
Now I'm developing application which has a lot of JSPs with number of parameters and the standard way of form processing is inconvenient.
I think that possible solution might be by using -action.
I don't understand whether it works for me.
I browsed a lot of materials but find nothing about it.
I mean that there is any information regarding possibility to get form parameters in jsp by ,
automatically create instance of the entity class,
map all the parameters to entity-properties and send the entity-instance to the servlet.
Please take a look at the code:
index.jsp
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="NewFormServlet" enctype="application/x-www-form-urlencoded">
<jsp:useBean id="client-bean" class="model.entity.Client" scope="request"/>
<h3>Please enter client information</h3><br>
Client first name<input type="text" name="first-name"/><br>
<jsp:setProperty name="client-bean" property="firstName" value="${requestScope.first-name}"/>
Client last name<input type="text" name="last-name"/><br>
<jsp:setProperty name="client-bean" property="lastName" value="${requestScope.last-name}"/>
Client address<input type="text" name="address" size="100"/><br>
<jsp:setProperty name="client-bean" property="address" value="${requestScope.address}"/>
Client city<input type="text" name="city"/><br>
<jsp:setProperty name="client-bean" property="city" param="${requestScope.city}"/>
Client postal code<input type="text" name="postal-code"><br>
<jsp:setProperty name="client-bean" property="postalCode" value="${requestScope.postal-code}"/>
<input type="hidden" name="jsp-identifier" value="client-form">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is incorrect in this code? Thank you in advance.
You should first think about what occurs on server and what occurs in browser, as well as what is transmitted via HTTP. A form submission uses many phases :
on server : the JSP is executed using servlet context, session, and request attributes, with still full access at the previous request (parameters, ...) => all that generates a HTML page (with eventually css or javascript linked or included)
on browser : the browser gets and parses the HTML page, optionnaly gets linked resources (images, etc.), and display the form to the user
on browser : the user fills the input fields of the form and clicks the input button
on browser : the browser collates data form input fields, generate an new HTTP request (usually a POST one) and sends it to server
on server : the servlet container pre-processes the request (until that is is only a stream of bytes conforming to HTTP protocol) and calls the appropriate servlet method with a new HttpServletRequest reflecting current HTTP request, and a HttpServletResponse to prepare what will be sent back to browser after processing
All that means that anything you can do to request attributes in the JSP part will be lost at the time of processing of the submitted form by the servlet. You can only rely on session attributes, and on input form fields that will be accessible as request parameters.
So with your current JSP, the Servlet will find nothing in request attributes (it is a different HttpServletRequest) and will only be able to use parameters with names firstName, lastName, address, city, etc.
I can understand it is not the expected answer, but HTTP protocol is like that ...
EDIT per comment :
You can put the attribute in session, and then the servlet will use the same session as the JSP. But read again what I wrote above and think when things happen :
on server, when executing the JSP, you create an empty Client bean that you put in session scope, and use its value to initialize the form fields. Stop for the server part
on client, user fills the input fields - the server knows nothing on that - and submit the form through a new request
on server, the servlet has the values in request parameters, but the session still contains the previous values and so the Client bean has null values
I'm sorry but there's not enough magic for the server to automatically find in its attributes (either request or session) what comes from form submission : it only exists in request parameters, and it is the servlet job to process them and eventually put them in attributes.
Edit:
It appears that jsp:useBean is an old school way to collect up a group of parameter values for easier display on a page.
It does not add an attribute when the request is posted.
Based on that,
I see little value in the jsp:useBean tag,
since you can use el expressions to access attributes that you set in a servlet.
This does not help you get the posted parameter values into a bean in the servlet.
You can write a method on the bean to extract the parameter values from the request (visitor pattern).
For example:
class bean
{
private String value;
public void loadFromHttpServletRequest(final HttpServletRequest request)
{
value = request.getParameter("value");
}
}
Consider using a package like spring-mvc.

read parameters passed by one jsp to another

I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.

Pass Hidden parameters using response.sendRedirect()

How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post.
response.sendRedirect("/content/test.jsp");
TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:
Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).
Controller (your servlet)
request.setAttribute("message", "Hello world");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
View (your JSP)
Using scriptlets:
<%
out.println(request.getAttribute("message"));
%>
This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.
<c:out value="${message}" />
If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example
Controller
//if request is not from HttpServletRequest, you should do a typecast before
HttpSession session = request.getSession(false);
//save message in session
session.setAttribute("helloWorld", "Hello world");
response.sendRedirect("/content/test.jsp");
View
Again, showing this using scriptlets and then EL + JSTL:
<%
out.println(session.getAttribute("message"));
session.removeAttribute("message");
%>
<c:out value="${sessionScope.message}" />
<c:remove var="message" scope="session" />
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD).
You can consider encrypting your query string parameters if security is an issue.
Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.
If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:
<h1>Welcome ${name}</h1>
To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.
String value="xyz";
response.sendRedirect("/content/test.jsp?var="+value);
Use this:
out.println("<script>window.location.href = \"hoadon?OrderId=" + getIdOrder + "\"\n</script>>");

How to access a request attribute set by a servlet in JSP?

I'm trying to retrieve attribute values set by a servlet in a JSP page, but I've only luck with parameters by ${param}. I'm not sure about what can I do different. Maybe its simple, but I couldn't manage it yet.
public void execute(HttpServletRequest request, HttpServletResponse response) {
//there's no "setParameter" method for the "request" object
request.setAttribute("attrib", "attribValue");
RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
rd.forward(request,response);
}
In the JSP I have been trying to retrieve the "attribValue", but without success:
<body>
<!-- Is there another tag instead of "param"??? -->
<p>Test attribute value: ${param.attrib}
</body>
If I pass a parameter through all the process (invoking page, servlets and destination page), it works quite good.
It's available in the default EL scope already, so just
${attrib}
should do.
If you like to explicitly specify the scope (EL will namely search the page, request, session and application scopes in sequence for the first non-null attribute value matching the attribute name), then you need to refer it by the scope map instead, which is ${requestScope} for the request scope
${requestScope.attrib}
This is only useful if you have possibly an attribute with exactly the same name in the page scope which would otherwise get precedence (but such case usually indicate poor design after all).
See also:
Our EL wiki page
Java EE 6 tutorial - Expression Language
Maybe a comparison between EL syntax and scriptlet syntax will help you understand the concept.
param is like request.getParameter()
requestScope is like request.getAttribute()
You need to tell request attribute from request parameter.
have you tried using an expression tag?
<%= request.getAttribute("attrib") %>
If the scope is of request type, we set the attribute using request.setAttribute(key,value) in request and retrieve using ${requestScope.key} in jsp .

accessing the values of class in jsp page from the action class

I am doing one project on Struts 2 that I am getting knowledge little by little bit..
I have the action like this
<action name="backaction" class="HandlerAction">
<result name="user_profile" type="redirect">hai.jsp</result>
In the class Handler action I have the object userprofile in which the name and age are members.
In the execute function
log.info(userprofile.getName())//it is giving name xyz
return "user_profile"
I am getting hai.jsp but I am unable to retreive the value in that object userprofile in jsp.
hai.jsp is as follows..
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<s:textfield name="user_name" value="%{userprofile.name}"/>
</body>
</html>
I tried by putting as value="%{name}" also but i am not getting the value xyz..
The problem is with
<result name="user_profile" type="redirect">hai.jsp</result>
since you are using redirect result type which means that framework will create a new Request and response object and discarding old request/response Object.So when you are returning from your action your user-object is theirs in the value stack till you tell S2 that you want to use redirect result type.
On seeing redirect result type, it will discard any existing data and will create a new request for you place its content in value stack and that's why this is not working for you.I am not sure why you using redirect result type since you can do the same using any build in result type say success.
If you still want to use redirect result, i suggest you to save the user-profile data in either Session and retrieve it in your next action or use scope-interceptor
Struts2 Redirect Result
Calls the {#link HttpServletResponse#sendRedirect(String) sendRedirect} method to the location specified. The response is told to redirect the browser to the specified location (a new request from the client). The consequence of doing this means that the action (action instance, action errors, field errors, etc) that was just executed is lost and no longer available. This is because actions are built on a single-thread model. The only way to pass data is through the session or with web parameters (url?name=value) which can be OGNL expressions.

Categories