Using request.setAttribute in a JSP page - java

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.

Related

How should I do to send data between two jsp with a servlet

I want to display something from one jsp page in another jsp page by clicking a button. I did it using request.setAttribute request.getAttribute but it doesn't work for me, for some reason the variable I send is null or the page is blank.
From your original question : When you are doing setAttribute(), its scope is limited to the request when the main page is loading and hence will not be available on the next page as it will be a new request.
<%Object product=ptp;
request.setAttribute("purchase", ptp.getId());
%>
What you can do is, submit this value in URL param as GET or in a form (get/ post) to fetch it on next JSP using request.getParameter().
Or you can use session scope by session.setAttribute()
Hope it helps
you can pass the variables through request scope or session scope.
request.setAttribute("variable name","value of its");
session.setAttribute("variable name","value");
Here a detailed exmple
http://www.jsptut.com/sessions.jsp

servlets / .jsp / sessons...confused

I am brand new to all of this, I like servlets and java on a whole so far but I'm having some growing pains.
Servlet Question: Just starting to learn servlets and I'm having an issue with Attributes/Parameters, Sessions and jsp.
Basically, I have a very basic
form. My servlet code states:
println("Hello, " + request.getParameter("name") + "!!!");
..and my .jsp states:
<form action="SimpleServlet" method="POST">
<input type="text" name="name">
<input type="submit"/>
</form>
So now what I need to do is take the last name input into this servlet, save it in session and then send it to a different .jsp that states:
'Hello, '
For example, if I input JIM into the servlet and it returns 'Hello, Jim!!!' in my first .jsp I would then need to click on a link on that page that re-directs me to another .jsp that takes the 'Jim' input and also displays 'Hello, Jim!'.
So I created a 2nd .jsp and have tried many different combinations of code on both to try and get this to work and I keep on getting null or screwing up the output of the first part of the form.
Could someone guide me in the right direction, I would greatly appreciate it.
if you want to show your last name JIM in multiple jsp pages you can use session to store your last name add following code in your servlet.
String name = request.getParameter("name");
HttpSession session=request.getSession();
session.setAttribute("name",name);
then in all your jsp you need to do is put following scriplet where you want to print your name.
<%
String name = request.getSession().getAttribute("name");
out.print(name);
%>
You can do exactly what you want using a single .jsp page, you don't have to create a different one. Just create a link that will POST different parameters to the same .jsp
But as an advice/direction to you, I think the first thing you must understand well is how can you pass and receive parameters and attributes to deal with at server side. Understanding what a request can carry has a huge importance in server-side development.
Just an addon to Mitul's answer
I'd advice you to use EL. It is a simplified approach.
Instead of String name = request.getSession().getAttribute("name"); use
${sessionScope.name} It would give you the desired output.
The best part is that scope resolution is done automatically. So, here name could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as

How to create a parameter in JSP? [duplicate]

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)

how to check getParameter is set in the project

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.

Get user input from textbox on JSP

I need to get the value that a user has entered in a textbox on a JSP. I used JavaScript to obtain the value, but then I need to access that same variable outside the JavaScript later on in the page.
Here's what I have:
<script type="text/javascript">
var sp;
function setPolicy(){
sp = document.getElementById('policy').value;
if(sp != "")
alert("You entered: " + sp)
else
alert("Would you please enter some text?")
}
</script>
the textbox:
input type="text" id='policy' size="15" tabindex = "1" onblur="setPolicy()"
But I need to access the string entered in this "policy" textbox later on in a scriplet to call a function within my session bean. Is there any way I can pass that variable outside the JavaScript? Or is there another way to do this?
Thanks!
JavaScript execution happens at client side and Scriptlet executes at server side. You are trying to combine the two.
You should submit the form to the same page by passing a param which will have the value entered in the textbox. Your scriptlet should check if the param is present or not. First time coming on this jsp the param will not be present, it will be available only when user enter something in textbox.
May not be the best solution as I don't know the whole context.
I'm not sure you have the lifecycle of a jsp down quite yet. By the time that the javascript is running, all the scriptlets have been evaluated.
By this I mean, one the JSP is rendered, html and javascript are emitted on the response to the browser, and there is no more server to interpret the JSP.
So, you should think of your problem as how do I communicate back to the server, the result of the user action?
Probably by posting a form to an action on the server.
If you are asking how to get hold of text input value in a java session bean, it has nothing to do with your javascript code.
The session bean is server side code. To pass the input value to your session bean, you need to change server side code, a servlet, strut action, webwork action depending on which web framework you use.

Categories

Resources