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
I have a Servlet, which sends values to a JSP1. I am setting the values in the servlet as
request.setAttribute();
and i am using
dispatcher.forward(request, response);
and i am able to access these values in the JSP1 using expression language.
Now, I also need to use this in another JSP2.
These two JSP's are clubbed together to display in a single page. So, I need to access the values of the servlet in the second jsp as well. How can i do that?
As you say you have both the jsp clubbed in a single page , you can simply get the attribute as,
${attributeName}
it refers to the object set in the HttpServletRequest scope . I suggest to take the tutorial for Expression language
It is quite simple. If you are setting an attribute "attr1" in a servlet and then forwarding to a JSP (file1.jsp):
request.setAttribute("attr1", "first attr");
request.getRequestDispatcher("file1.jsp").forward(request, response);
And suppose in the first JSP (file1.jsp), you are including another JSP (say file2.jsp):
<body>
.....
<jsp:include page="file2.jsp"></jsp:include>
.....
</body>
Then in file2.jsp, you can access attr1 by calling the request object's getAttribute method:
<body>
....
${attr1}
....
</body>
In case of jsp:include action, when file2.jsp is included in file1.jsp, both request and response objects are passed to file2.jsp as parameters. So file2.jsp can access the attributes of file1.jsp's request object.
i want to use JSP values in servlet. iam fetching some parameters from the url and i need to pass those parameters in my servlet and also the servlet result something by using those parameters and i want to use the result again in the same jsp and in other jsp.
i get those parameters first time when my home jsp is called.
i am getting url parameter by using jstl core tags:
<c:set var="data" scope="session" value="${param.urldata}" />
How do i do this using JSP tags???
Thanks in advance
As i understand somewhat , you are trying to send the values from JSP page to Servlet..
For this we have lot of solution
Pass the value through method
Set the value at session and get it wherever you want in the whole application
I prefer second point, because which hold the value for the entire application
Check Pass variables from servlet to jsp
Above question pass the value from servlet to JSP,Your question is opposite of the answer that's it..!
Set value at JSP : session.setAttribute("key","value");
Get value at Servlet: session.getAttribute("name");
Also refer : Sharing values between servet and JSP
I am analayising the existing project, in one of the JSP page I saw that
String server=request.getParameter("server");
But I am trying to check How I can find where is this server parameter is set
I searched for setParameter("server"), no luck
can any one suggest on this
Main idea, I need to change the values for the values which is set in "server" parameter.
You can look in any of HTML elements, where they may have tag like <input type='text' id='server' name='server' /> like that. I have given example of text box, it can be anything.
And no, there is no such method called request.setParameter()
You can get this attribute from the html/jsp page from where the form is being submitted.
It is set by the HTTP request that was generated by the client side (such as a browser). For example, an HTML form, upon submission, would result in an HTTP request with parameters for each field. A standalone client (non-browser) can set request parameters by merely adding those parameters to the URL itself.
Therefore, first you have to determine what is generating the HTTP request that results in your JSP page being called. Once you find who's generating the request, it will be very easy for you to find how the parameter itself is set.
In your web.xml first check, from which form present in JSP/HTML the request is coming.
In the corresponding action, you will get all the input fields in the form, which will be fetched in the servelet through request.getParameter('')
This parameter is set when any form is submitted. Check the page which calls this servlet. That page will contain a form having field like <input type='text' name='server' />. If not found then check URL query parameter.
EDIT
In web.xml check which URL is being mapped to your servlet.
I have 2 jsp pages, one called as MyPage.jsp and other as View.jsp. View.jsp has a tree structure. MyPage.jsp has some text fields called as number and design which need to be populated through a bean via servlet. On click of any of the tree node in View.jsp, MyPage.jsp should be rendered with the text fields values set. Now what is happening is since MyPage.jsp is being called twice, i.e. once in View.jsp(in ajax function) and second in the request dispatcher in the servlet so the bean values being set in the servlet are lost. Please suggest a better way so as to retain the values throughout and that on click of the tree node MyPagejsp is rendered with the field values set.
responseBean.setNumber("220");
responseBean.setDesign("xyz");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setAttribute("responseBean", responseBean);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/MyPage.jsp");
requestDispatcher.include(request, response);
response.getWriter().write("Success");
The jsp page from where MyPage.jsp is called with the bean values set has following code
View.jsp
$.ajax({
url : AJAX_SERVLET,
type: "GET",
data: "Number="+node.data.title,
success : function(output) {
$("[id=content]").attr("src", '/Test-portlet/MyPage.jsp');
}
});
}
MyPage.jsp
<jsp:useBean id="responseBean" class="com.web.bean.ResponseBean" scope="request">
<jsp:setProperty name="responseBean" property="*"/>
</jsp:useBean>
<body>
<%System.out.println("Values"+responseBean.getNumber()); %>
</body>
In the above MyPage.jsp code, System.out.println is printing the value twice; once as
Values 202
and second as Values null. Since it replaces the original value with null just because MyPage.jsp is called twice and so the second time value is lost. Please help
I believe that you're confusing/misunderstanding some basic concepts, particularly how HTTP works and how Ajax is supposed to work.
What is happening here is that you're effectively firing two HTTP requests. One by $.ajax() and other by element.attr('src', url). Each request results in a fully distinct bean instance being created and set. You're completely ignoring the bean data in the callback of the $.ajax() request. I am not sure what HTML element [id=content] represents, but I guess that it's an <iframe>. That's not entirely the right way.
You should end up with effectively firing one HTTP request. There are basically 2 solutions:
Forget the $.ajax() and send the request by element.attr('src', url).
$("[id=content]").attr("src", "/Test-portlet/MyPage.jsp?number=" + encodeURIComponent(node.data.title));
You can also change the URL to be a servlet one so that you have a bit more preprocessing control and finally use RequestDispatcher#forward() instead of include(). Do NOT write HTML to the response in the servlet. Let JSP do it.
Forget the <iframe> thing and process the response fully by Servlet/Ajax without intervention of JSP. You would need to convert the bean into other data format which is easily parseable by JavaScript/jQuery. I would suggest to use JSON for this.
$.get(AJAX_SERVLET, { "number": node.data.title }, function(response) {
$("#number").text(response.number);
$("#design").text(response.design);
});
with in HTML for example
<div id="number"></div>
<div id="design"></div>
and in servlet
// ... (create ResponseBean the way as you want)
String json = new Gson().toJson(responseBean);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
See also:
How to use Servlets and Ajax?
Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.