Solved

Update the value of a bean from a servlet

Posted on 2007-12-02
28
411 Views
Last Modified: 2013-11-24
I am trying to figure out some servlet/bean usage for redesigning our company web site.  I had thought that it was working before, but apparently I missed something in the process.  I created a bean (code is below) that has a single getter and setter function.  Then I use a servlet to update the value and open a JSP file.  The problem is that the JSP is showing the original value -- not the input value from the servlets update. -- In this example, no matter what I do the JSP page outputs Hello World instead of the new welcome message I put in through the servlet.  
BEAN CODE:

public class TestBean {

	private String greeting = "Hello World";

	public String getWelcome(){		

		return greeting;

	}

	public void setWelcome(String test){

		greeting = test;		

	}

}
 

___________________________________________
 

Servlet Code:

TestBean tester = new TestBean();

			tester.setWelcome("NEW WELCOME");

			request.setAttribute("welcome", tester);

		    RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/Sell.jsp");

		    dispatch.forward(request, response);
 

______________________________

JSP Page
 

<?xml version="1.0" encoding="ISO-8859-1" ?>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">

  

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<title>MY TITLE IS: BOOKS</title>

</head>
 

<body>

<jsp:useBean id="testBean" class="bookcellar.TestBean" scope="session" />

<jsp:getProperty name="testBean" property="welcome" />
 
 

</body>

</html>

Open in new window

0
Comment
Question by:VoodooFrog
  • 10
  • 9
  • 9
28 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You need to update the attribute after each setting. btw, the property should be 'welcome' not 'greeting'
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
'testBean' and 'tester' are also separate objects
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you need to get the bean from the session instead of creating a new one.
You may also want to persist the bean depending on your requirements


TestBean tester = (TestBean) session.getAttribute("testBean");
                        tester.setWelcome("NEW WELCOME");
                    RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/Sell.jsp");
                    dispatch.forward(request, response);
0
 

Author Comment

by:VoodooFrog
Comment Utility
CEHJ -- I am not sure what you mean in your first response -- could you elaborate please?

on the second -- tester is an instantiation of TestBean -- I had thought that beans worked the same as other classes that way?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
My two comments are connected - i mean that you are creating two separate and unconnected objects
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(whereas you need to be creating just one and working on that instance)
0
 

Author Comment

by:VoodooFrog
Comment Utility
I still don't understand your point CEHJ -- which part of the code are you talking about?

objects -- the line TestBean tester = (TestBean)session.getAttribute("testBean");  throws an error "session cannot be resolved" -- it looks as though that is combining the request.setAttribute with the bean declaration -- is that allowed?  and if so is that the right syntax?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
just add the following to get your session

HttpSession session = request.getSession();
0
 

Author Comment

by:VoodooFrog
Comment Utility
CEHJ -- assuming your first comment was about the Bean I changed the code to:

public class TestBean {
      private String welcome = "Hello World";
      public String getWelcome(){            
            return welcome;
      }
      public void setWelcome(String test){
            welcome = test;            
      }
}

nothing changed in the results
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
your bean is fine, you don't need to change it.
What I suggested should resolve your issue for you.
0
 

Author Comment

by:VoodooFrog
Comment Utility
objects -- adding the HttpSession line gets me a NullPointerException at TestBean tester = (TestBean) session.getAttribute("testBean");
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>I changed the code to:

That's better. It's not the reason for your problem though. That's because you were using two objects when you meant to use one
0
 

Author Comment

by:VoodooFrog
Comment Utility
this is also the first instantiation of the bean so far -- I think that may be the problem.  I am just trying to feed a value into the bean and pull it right back out.  -- so the session doesn't have a bean initialized until this code is in place.  The code is in the doGet function if that makes a difference.  
0
 

Author Comment

by:VoodooFrog
Comment Utility
CEHJ -- could you show me what you mean by two objects instead of one?  my understanding of it is that I am instantiating TestBean and giving it the name tester after which I run the code from the tester object.  I will need a code illustration apparently because I do not understand what you are saying.  
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 92

Expert Comment

by:objects
Comment Utility
then change what i posted to:


HttpSession session = request.getSession(true);
TestBean tester = (TestBean) session.getAttribute("testBean");
if (tester==null)
{
   tester = new TestBean();
}
tester.setWelcome("NEW WELCOME");
RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/Sell.jsp");
dispatch.forward(request, response);
0
 

Author Comment

by:VoodooFrog
Comment Utility
nope -- null pointer is gone, but I am back to the original problem -- the update to the greeting is not being pulled through to the JSP which still displays "Hello World"  
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
sorry, missed a bit

HttpSession session = request.getSession(true);
TestBean tester = (TestBean) session.getAttribute("testBean");
if (tester==null)
{
   tester = new TestBean();
   session.setAttibute("testBean", tester);
}
tester.setWelcome("NEW WELCOME");
RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/Sell.jsp");
dispatch.forward(request, response);
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>CEHJ -- could you show me what you mean by two objects instead of one?  

You create one object called 'tester' then a new one called 'testBean'
0
 

Author Comment

by:VoodooFrog
Comment Utility
still says hello world -- feels like all we have done is change the scope of the bean from request to session scope, but the underlying problem is unchanged.  
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 100 total points
Comment Utility
>>the update to the greeting is not being pulled through to the JSP which still displays "Hello World"  

That's because the JSP creates a new object. What you want is

<%=session.getAttribute("tester")%>

in the JSP
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(Or whatever the original session attribute was called)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> still says hello world -- feels like all we have done is change the scope of the bean from request to session scope, but the underlying problem is unchanged.  

your jsp (as posted) does use session scope
check your jsp is as u posted in question
0
 
LVL 92

Accepted Solution

by:
objects earned 400 total points
Comment Utility
alternatively to use request scope:

TestBean tester = new TestBean();
tester.setWelcome("NEW WELCOME");
request.setAttribute("testBean", tester);
RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/Sell.jsp");
dispatch.forward(request, response);
 
______________________________
JSP Page
 
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>MY TITLE IS: BOOKS</title>
</head>
 
<body>
<jsp:useBean id="testBean" class="bookcellar.TestBean" scope="session" />
0
 

Author Comment

by:VoodooFrog
Comment Utility
CEHJ -- using <%=session.getAttribute("tester")%> results in a null value for the property -- no error but the JSP just says 'null' at the top.  
0
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
Comment Utility
typo in my comment above.
for using request scope the jsp should be:

<jsp:useBean id="testBean" class="bookcellar.TestBean" scope="request" />
0
 

Author Closing Comment

by:VoodooFrog
Comment Utility
thank you both for your help -- I split the points because in the end I think you were both saying the same thing.  I was able to understand objects more because of his use of code to help me.  
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>
CEHJ -- using <%=session.getAttribute("tester")%> results in a null value for the property -- no error but the JSP just says 'null' at the top.  
>>

Is that the right attribute name?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> I split the points because in the end I think you were both saying the same thing.

thats ok, but the comment by CEHJ is just plain wrong (and irrelevant, you don't need (or want) to use scriptlets) and will only confuse others with the same problem looking at this question
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Read about why website design really matters in today's demanding market.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
This video teaches users how to migrate an existing Wordpress website to a new domain.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now