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:
Note that all the <servlet> elements precede the <servlet-mapping> elements. This is the required order.
Finally, to "run" this webapp, simply type the URL
http://localhost:8080/myContext/main.html