This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
How can a servlet "use:bean" (use a bean) in a web application? In my app, I am creating a bean, using 'use:bean', from a JSP page that then calls a servlet. I now want to access some methods in the bean from the servlet. How is this done? Thanks much for any input or ideas. -- Mike
You're a bit backwards. Normally what happens is that: (1) a servlet takes in the initial HTTP request, creates a Java class (bean) with the standard new operator and a constructor, (2) Then places that bean in one of the standard "buckets" for J2EE (either the HttpRequest or HttpSession) and then (3) invokes a JSP (using a RequestDispatcher) which can then (4) take the bean OUT of the bucket with the "usebean" tag and then send messages to it to retrieve the data placed in it in part (1) above. I'd suggest that you take a look at some of the books or articles on the MVC pattern that describe this entire process. My book does so in depth, as do many others. Kyle
Let's create a simple JavaBean that works with a JSP and a servlet. We will make: 1. a main.html that takes a String parameter and forwards it to 2. a mainController.jsp that instantiates a JavaBean and populates it with the String parameter, then forwards it to a servlet 3. a JavaBean called InputBean that has a property called "input" 4. an OutputServlet that takes the property from InputBean and displays it on the browser. Let's say we're using Tomcat4 and the tomcat install directory is called catalina. For main.html we have:
We'll put this html in the app root, C:\catalina\webapps\myContext. For the JSP we have:
For more information on JSP tags, refer to the Sun link. Basically, since I will create the bean inside a package I will import it using the page directive, instantiate it with useBean, populate its "input" property with setProperty, and then finally forward it to the OutputServlet with servlet URL "/output". We'll also put this JSP in the app root, C:\catalina\webapps\myContext. For the JavaBean, go to C:\catalina\webapps\myContext\WEB-INF\classes and create a folder named beans. Inside beans, create a JavaBean named InputBean:
Note that the public no-args constructor, as well the private fields and public accessor methods are part of the JavaBean specs. Finally, we create the OutputServlet:
Note that we instantiate the actual JavaBean, retrieve its property and then display it to the client browser. Of course, this servlet resides in C:\catalina\webapps\myContext\WEB-INF\classes We must register this servlet since the JSP uses a servlet mapping to forward the request. We must make the following changes to the web.xml file: