Global variables in jsp

Ok, I'm an experienced programmer, so you can talk to me like I am one, however, I am a huge jsp newb.  I dont have time to read up, i have a deadline.  I have a base homepage.  And from there, serveral popups.  Each popup contains a html form.  the user will fill in the form. push okay.  that popup will close.  All the data they entered into all 5 of the popups needs to be retained somehow.  i am thinking global variable. you guys will know better. please help
LVL 2
lmpsteelwireIT / Business AnalystAsked:
Who is Participating?
 
bloodredsunCommented:
Right, lets start from scratch!!

We'll do everything in jsps so we don't need to worry about servlets (jsps are easier conceptually anyway). Here's a simple 2 page example of what you want to achieve.

form1.jsp
----------------
<html>
<head><title>Form1</title></head>
<body>

<form name="form1" action="form2.jsp">
Input for page one:<input type="text" name="one" size="10">
<input type="Submit" value="Submit">
</form>

<body>
</html>

form2.jsp
---------------
<%
session.setAttribute("one" , request.getParameter("one"));
%>

<html>
<head><title>Form2</title></head>
<body>

<form name="form2" action="form3.jsp">
Input for page two:<input type="text" name="two" size="10">
<input type="Submit" value="Submit">
</form>


<body>
</html>

form3.jsp
------------
<%
session.setAttribute("two" , request.getParameter("two"));
%>
<html>
<head><title>Form3</title></head>
<body>
Output from form1 = <%=session.getAttribute("one")%><br>
Output from form2 = <%=session.getAttribute("two")%><br>
<body>
</html>

--------------

The above example shows you how to put information into the session object in JSPs when handling form data witht he final form just displaying the information. This should be all you need to know
0
 
lmpsteelwireIT / Business AnalystAuthor Commented:
oh ya, the data is retained for the main front site, and from there, i will do logic on that data. everything is already written, except for the jsp. thanks for your time
0
 
objectsCommented:
Store any values needed in the application (ServletContext) context
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Jim CakalicSenior Developer/ArchitectCommented:
Hi,

I would have recommended putting the form values in HttpSession. What are you planning to do with them?

Best regards,
Jim Cakalic
0
 
objectsCommented:
Yes if they need to be global to the session you'd put them in the session scope.
0
 
jessegivyDeveloperCommented:
The session is not intended to be used for form data!  I have been tempted to use it for the same purpose and always find another way.  I would suggest just using javascript if yo don't mind it.  The DOM object makes it easy to communicate between windows.  You could have functions that are called from the popups and pass all of the field values via parameters or you could reference them directly and store them in some fashion on your main page.  Not a jsp solution but one you may be more comforatble with.

In jsp you could conceivably build an object and store all of your form values in the session but again, not the best convention.  
0
 
Jim CakalicSenior Developer/ArchitectCommented:
I've seen it done both ways -- a workflow object in session to manage state across multiple views in the workflow and a plethora of hidden fields on each page of a workflow (assuming that is what you are suggesting?) By and large, I prefer the "cleanliness" of an object in session. As long as you can manage the lifecycle of the workflow there isn't an issue with leaving objects in session. Although I certainly don't recommend placing a large number of "loose" objects in session because that tends to be harder to clean up.

Jim
0
 
KuldeepchaturvediCommented:
depends how big the forms are on the pop ups... if each have got 3-4 fields in each.. I wd have a hidden frame in the main window. upon submit I will move the data from the pop ups to the main window and on the last window submit the main form to the server...
but if you have got more fields per form I wd rather use a session at the server.. each pop up submitting to a servlet which moves fields to session.. and finally do whatever you want to do with these fields
0
 
KuldeepchaturvediCommented:
Global variables are a no no.. every user will enter its own data and if we keep them in global variables every new user will overwrite the data of the previous guy..
0
 
bloodredsunCommented:
When you say "global variable" I presume that you mean a variable that is available to the jsps throughout the users browsing on the site. in that case, I agree with jim_cakalic and object's second comment by putting the data in the session.

e.g. in your form handler (where you send the data in the form action)
-----
            HttpSession session = request.getSession() ;//needed in servlet not jsp as it's an implcit object
            String name = request.getParameter("name");
            String age= request.getParameter("age");
            session.setAttribute("name" , name);
            session.setAttribute("age" , age);
-----

>> The session is not intended to be used for form data!
It depends on the use of the data. If the data is going to be re-used later in the session, then the session object is the best place for them.

>>In jsp you could conceivably build an object and store all of your form values in the session but again, not the best convention.
Sorry to disagree again, but personally I would store the data in a javabean that is then put in the session as its better code hygiene and you're less likely to forget what data you have stored in the session. I think that this is better than hidden fields as it makes maintainance much easier, especially if there is a long series of forms that are linked. The only reason not to would be if your server cannot deal with the user load and the number of sessions would slow the server to an unacceptable crawl. In my experience, that's pretty difficult to do if you set the session duration value to a sensible one and make sure that you call session.removeAttribute(String name) on the bean when you are done and  session.invalidate() when you no longer have a use for the session object.

So you can re-write the code to this:

------
            HttpSession session = request.getSession() ;//needed in servlet not jsp as it's an implcit object
            Person myPerson = new Person() ;//example javabean
            myPerson.setName( request.getParameter("name") );
            myPerson.setAge( Integer.parseInt(request.getParameter("name") ) );
            session.setAttribute("myPerson" , myPerson ) ;
------

This is just a basic example which can be improved by adding a proper constructor and validating the form parameters

But if the data is not going to be used later on, then put it into the Db striaght away, there's no point keeping it in the session
0
 
lmpsteelwireIT / Business AnalystAuthor Commented:
So, here is another question.  

1) Where in my website would I put this.  Lets call the opening page the "root".  From the root, I open four or five branches that I enter extra information.  Would I need to call the session (HttpSession session = request.getSession() ) from within every branch or just from within the root?

2) Does getSession() return the current session, or does it create a new one?  

3) Can we utilize Javascript inside JSP tags?
0
 
KuldeepchaturvediCommented:
getSession(true);
returns the current session if there is one.. otherwise it creates one and returns it...
and yes you will have to call it from every branch... it should return the same session to every one
0
 
bloodredsunCommented:
1)In a JSP, the session object is provided for you by the servlet container, normally tomcat. Here's and example:
<html>
<body>
<%= session.getAttribute("username") %>
</body>
</html>

In this example, you are outputting the session variable with the name of username, if it exists. As I said it the earlier example you don't need to call that line of code in a JSP, only in a servlet, which is a different but related thing.

2)As Kuldeepchaturvedi kind of explained, getSession() returns the current session object or creates a new one is one doesn't exist and then returns that. getSession() and getSession(true) are exactly the same (the reason getSession( boolean bool) exists is so that you can call getSession(false) if you need to, which returns the current session is there is one, but returns a null if one doesn't already exist, a subtle difference)

3)Nope. What you can do is utilise JSP inside JavaScript. Remember , JSP is serverside and JavaScript is Client side. This means that you can output JSP into JavaScripts to make them dynamic in the same way you would HTML.

e.g.
for the URL example.jsp?alert=Hello
<script>
 alert( "<%=request.getParameter("alert")%>" );
</script>

would output:
<script>
 alert( "Hello" );
</script>
0
 
KuldeepchaturvediCommented:
Damn u r good bloodred....:-)
0
 
bloodredsunCommented:
you're too kind, Kuldeepchaturvedi  ;-)
0
 
lmpsteelwireIT / Business AnalystAuthor Commented:
HttpSession session = request.getSession() ;//needed in servlet not jsp as it's an implcit object


needed in servlet? how am i going to use both a servlet and jsp?
0
 
KuldeepchaturvediCommented:
well you can not write the same piece of code that will work both places..
in servlet you will have to do
HttpSession session = request.getSession() ;//

in jsp you can start using it without putting this first line..

you can use with name "session"..

i.e.
session.getAttribute("blah");
0
 
lmpsteelwireIT / Business AnalystAuthor Commented:
ok dude your way smart, need to slow down for me...

So I need to create a servlet and put that line of code in it

Then what?
0
 
lmpsteelwireIT / Business AnalystAuthor Commented:
thanks a lot blood, that was exactly what I needed.
0
 
bloodredsunCommented:
no probs, glad to help :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.