Home » Java Basics » 09 - Java Servlet Basics
Screen Shot 9c: Adding a class library to a project
Screen Shot 9d: Servlet Output
9
Netbeans Set-up and a First Servlet
How to set up netbeans and a first servlet sample
- To make the servlet API available on Netbeans, open the MySamples project on Netbeans5.5
- Expand the 'MySamples' node by clicking on the '+' next to it on the project tree in the left hand window.
- Right click on the 'libraries' link on the left hand window and click on properties
- You may have to increase the width of the properties pop up window in order to see the buttons on the right hand side. Click on the Add JAR/Folder button and browse to <Tomcat 5.5 Program Directory>\common\lib and select 'servlet-api.jar' (<Tomcat 5.5 Program Directory> typically resolves to c:\Program Files\Apache Software Foundation\Tomcat 5.5\ if you chose the default set up directory during installation). Click on the 'open' button . Click on 'OK'.
Screen Shot 9c: Adding a class library to a project
- You are now ready to write the first web page for your application.
- Open a new HTML file in Netbeans5.5 by clicking File -> New File. Select Other" and "HTML" under "Categories" and "File Types". Click Next.
- Enter 'index' next to file name.
- Just type '<h1>Hello there!</h1>' between the '<body>' and '</body> tags and 'Welcome' between the start and end '<title>' tags. 'h1' is mark up for an HTML heading; 'title' specifies the window title.
- Save this file in the MySamples\src folder (NetBeans saves here when you hit 'save'). Copy it into the 'ShowFruits' application subfolder deployed through tomcat (typically at c:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ShowFruits).
- Now, if you browse to 'http://localhost:8080/ShowFruits/', you will see your web page. (tomcat configures index.html to be the default home page of an application).
- Now, open up the a new HTML file with a name 'addNewFruit.html' and replace its content with the following:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>New Fruit</title> </head> <body> <form name="addform" action="showAddedFruit" method="post"> <table> <tr><td>Name:</td><td> <input type="text" name="name"></td></tr> <tr><td>Colors:</td><td> <input type="text" name="color"></td></tr> <tr><td>Image:</td><td> <input type="text" name="image"></td></tr> <tr><td>Calories:</td><td> <input type="text" name="calories"></td></tr> <tr><td colspan=2> <input type=submit></td></tr> </table> </form> </body> </html>
- The above is a very simple Internet form held in a two column HTML table (<tr> tags define table rows and <td> tags define cells in a row. The <table> tags are table containers)
- The form has as its action 'showAddedFruit' - this URL represents a processing servlet on the server. The HTTP method used is POST. The form contains text input fields for the name, color, ii mage, and calories. These same property names are used to name the corresponding form fields. The form also includes a submission button.
- Save the form under the <Tomcat 5.5 Program Directory>\webapps\ShowFruits directory.
- Now, open a new Java class called 'showFruitInfo.Java' and replace its contents with the showFruitInfo.Java file.
- Study the Java file. All servlet classes extend HTTPServlet and override either the doPost or doGet method or both. If the form whose submission caused an HTTP request for this servlet contained 'method=POST' in its tag, the doPost method is executed. Otherwise, the doGet method is executed. Since we specified 'method=Post', our servlet will execute the doPost method. The doPost method always has the following signature. It takes as arguments references to the request and response HTTP messages.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
- The form parameters may be accessed through the 'request' input parameter variable of type 'HttpServletRequest' while responses may be constructed and sent to the client machine using the 'response' input parameter variable of type 'HttpServletResponse'. This is exactly what we do:.
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><head><title>" +
Fruits</title></head><body><table>");
out.println("<tr><td>Name:</td><td>" +
request.getParameter("name") + "</td></tr>");
out.println("<tr><td>Color:</td><td>" +
request.getParameter("color") + "</td></tr>");
out.println("<tr><td>Image:</td><td>" +
request.getParameter("image") + "</td></tr>");
out.println("<tr><td>Calories:</td><td>" +
request.getParameter("calories") + "</td></tr>");
out.println("</table></body></html>");
- A PrintWriter object is created to allow us to write to the HTTP response through response.getWriter(). Now, every line of the form 'out.println(....)' where out is the variable of type PrintWriter becomes part of the HTML file sent back to the user. Here, we include a table containing the values the user sent.
- The request.getParameter(<Form_Field_Name>) method returns a string whose value is the information the user entered into the form with name <Form_Field_Name> (in our case - name, color, image, and calories). Note that all fields are returned as strings
- The doPost method always throws a servletException; the PrintWriter may throw an IOException. We attempt to catch these exceptions in our code.
- Compile this file. Go to the MySamples\build\classes subdirectory. Find showFruitInfo.class. Save it in the <Tomcat 5.5 Program Directory>\webapps\ShowFruits\WEB-INF\classes subdirectory.
- Now, we need to configure Tomcat so that it knows where to send forms that have 'addFruit' in their action tag. Open up the web.xml file in <Tomcat 5.5 Program Directory>\webapps\ShowFruits\WEB-INF\.
- Remove all the content between the following tags:
<!-- JSPC servlet mappings start --> <!-- JSPC servlet mappings end -->
Copy and paste the following between the above tags in the following way, save the file, and close it.
<!-- JSPC servlet mappings start --> <servlet> <servlet-name>showInfo</servlet-name> <servlet-class>showFruitInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>showInfo</servlet-name> <url-pattern>/showAddedFruit</url-pattern> </servlet-mapping> <!-- JSPC servlet mappings end -->
- Every servlet in an application should contain two such entries in web.xml. Each servlet should have a unique name (showInfo in our case). Note that the url-pattern corresponds to the form action - showAddedFruit. Tomcat looks up the url pattern whenever it gets a request for a certain servlet from a form submission or a link. Then, it searches for the servlet's class in a 'servlet' tag by looking up its name. Here, showInfo is assigned the class we just created - showFruitInfo.class.
- Now, browse to the web site http://http://localhost:8080/ShowFruits/addNewfruit.html
- Enter some values and click the 'submit' button
- You should see output that reflects your entries:
|
|
|
|
Screen Shot 9d: Servlet Output