# Presentation: 130762

## Java TrainingIntroduction to Servlets

- Written by Jeff Smith

## What is a Servlet? -1

- Servlets are server side Java classes that add functionality to a web server in a manner similar to the way applets add functionality to a browser.
- Servlets can be used as a replacement for CGI scripts (or ASP scripts) and they support the standard request/response protocol supported by web servers.
- In this request/response protocol, a client sends a request message to a server and the server responds by sending back a reply message
- Reply is usually as HTML
- Could be image, audio stream, video stream, etc.

## What is a Servlet? -2

- Servlets generally implement either the Servlet interface or extend the HttpServlet abstract class
- Most programmers extend HttpServlet class
- More on this class later...
- Servlets run in a servlet container (Tomcat is a popular one)
- Servlets are platform independent
- Your servlets will work on an Apache web server running on Linux or a IIS web server running on Windows XP
- Servlets are generally invoked from a hyperlink or from the action attribute of an HTML form

## What is a Servlet? -3

## What is a Servlet? -4

## Web/Servlet Architecture

## Servlets -1

- Servlets can run on the web server platform as part of the same process as the web server itself.
- Alternatively, the servlet container can also run on a different machine
- Tomcat is a popular (and free) servlet and JSP container and can be downloaded from the JavaZone web page
- Apache Tomcat can also run web services
- You can use Apache Axis (SOAP implementation for web services) with Tomcat

## Servlets -2

- The web server communicates with servlets via a simple interface: javax.servlet.Servlet. This interface defines three important methods:
-      init()  -- invoked on servlet startup, put init code hereservice() -- each client request invokes this methoddestroy() -- put cleanup code here
- The servlet container controls the lifecycle of the servlet objects
- initializes, invokes, and destroys each servlet instance.
- You can write a servlet by extending the Servlet class and implement these three methods

## Servlets -3

- Servlet Lifecycle
**init()**  -- This method is called when a servlet is first invoked by the servlet container. It could be used to write code that initializes files or connections to databases
**service()**  -- This method process requests from the client (for example, a hyperlink or form action). It returns a response (usually HTML) back to the client.
- The service() method provides two parameters: ServletRequest and ServletResponse to provide access to the request object and response object
**destroy()**  -- Called just before servlet is destroyed by container to enable programmer to clean up any resources (e.g. close a db connection)

## Servlet Example -1

**import java.io.*;**
**import javax.servlet.*;**
**public class MyServlet implements Servlet **
**{**
**  ****private ServletConfig config;**
**  ****public void ****init**** (ServletConfig config)**
**    ****throws ServletException **
**  ****{**
**    ****this.config = config;**
**  ****}**
**  ****public void ****destroy****() {} // do nothing**
**  **

## Servlet Example -2

**  ****public ServletConfig getServletConfig() //optional**
**  ****{                                       //method**
**    ****return(config);**
**  ****}**
**  **
**  ****public void ****service****(ServletRequest req,**
**                      ****ServletResponse res)**
**                  ****throws ServletException, IOException  **
**  ****{**
**    ****res.setContentType( "text/html" );**
**    ****PrintWriter out = res.getWriter();**
**    ****out.println( "<html>My Servlet!!!</html>" );**
**    ****out.close();**
**  ****}**
**}**

## Useful Servlet Methods -1

**getRealPath()** -- method translates a relative or virtual path to a new path relative to the server's HTML documentation root location. This is useful if your servlet needs to access a file, for example.
**getServlet()** -- Returns a Servlet object of a given name. Useful when you want to access the services of other servlets.
**log()** -- Writes information to a servlet log file. The log file name and format are server specific.
- Note: When extending the HttpServlet class, you access these methods via the ServletContext. For example
**realPath = getServletContext().getRealPath(virtualPath);**

## HTTP GET vs. POST -1

- HTTP GET sends the contents of the form fields as extra data appended to the URL specified in the form's ACTION attribute.
- For example, if you had a form with an action *MyServlet* and a single text element called *search *and you typed in "football" and clicked the submit button*, *the resulting URL might look like:http://www.noaa.gov/MyServlet?search=football
- Note that you could bookmark this URL to quickly reload it in a browser.
- HTML forms that use do HTTP GETs should not contain too much data (1000 chars?) or they might overflow the web server

## HTTP GET vs. POST -2

- HTTP POST sends the contents of the form fields as a separate data stream to the web server
- HTTP POSTs cannot be bookmarked by the browser
- HTML forms that use do HTTP POSTs can send large amounts of data to the web server without any problems
- The data that is sent is not visible in the URL that appears in the browser
- For example, if you have a password field, you would want to do a HTTP POST so the password doesn't appear in the URL

## HttpServlet -1

- Instead of implementing the Servlet interface, most servlets extend the **HttpServlet** class because it has http support built in, making it easier to access the request and response objects.
- When you extend HttpServlet, you generally write code for one or both of the following methods:
**doGet()** -- corresponds to HTTP GET
**doPost()** -- corresponds to HTTP POST

## HttpServlet -2

- The doGet() and doPost() methods take two parameters:
**HttpServletRequest** -- contains all the information about the request made by a web page, including any form data
**HttpServletResponse** -- object you can use to send data (usually html) back to the calling web page

## HttpServlet -3

- doGet() and doPost() methods generally do the following:
- Read the request data (html form data)
- Process the request (perhaps invoking the code in other user-written classes within the servlet's package)
- Set response object headers (what type of response will be sent--for example, will it be HTML or a JPEG image?)
- Write the response data (for example, send HTML back to the calling web page)

## HttpServlet Style Suggestions

- It is a good idea to keep your servlet classes as lean as possible
- In general, good OOP design would suggest that you put your "business" or "application" logic in a separate class and have your servlet's doPost() or doGet() methods invoke that code
- For example, you don't want to have a doPost() method with 300 lines of code in it
- Your servlet can directly return HTML, but in most real world (and complex) web apps, your servlets would not return HTML via out.println() statements.
- Instead, your servlets would return JSP pages with all the HTML formatting already in it. These JSP pages could be created by a tool like Dreamweaver

## HttpServlet Example -1

- This web page prompts the user for the background color, title, and message that will be passed to a servlet. The servlet will read this data and create a new web page using the supplied information.

## HttpServlet Example -2

- In this example, the servlet will read the information typed into the web form and generate a new html document based on the user supplied information
- To keep things simple, it will build the html string in the Java code and return it (it will not use JSP)
- The form action for this web page might look like:
- <form action="http://www.noaa.gov/DesignPageServlet"
-   method="post">

## HttpServlet Example -3

**import javax.servlet.*;**
**import javax.servlet.http.*;**
**import java.io.*;**
**import java.util.*;**
**public class DesignPageServlet extends HttpServlet**
**{**
**  ****//Initialization**
**  ****public void init(ServletConfig config) **
**              ****throws ServletException**
**  ****{**
**    ****super.init(config);**
**  ****}**

## HttpServlet Example -4

**public void doPost(HttpServletRequest request,**
**                   ****HttpServletResponse response) **
**       ****throws ServletException, IOException**
**  ****{**
**    ****String sBKCOLOR = request.getParameter("BKCOLOR");**
**    ****String sTITLE = request.getParameter("TITLE");**
**    ****String sMESSAGE = request.getParameter("MESSAGE");**
**    ****response.setContentType("text/html");**
**    ****PrintWriter out = new PrintWriter**
**                      ****(response.getOutputStream());**
**    ****out.println("<html><head><title>");**
**    ****out.println(sTITLE + "</title></head>");**
**    ****out.println("<body bgColor=" + sBKCOLOR + ">");**
**    ****out.println("<h1>" + sTITLE + "</h1>");**
**    ****out.println("<br><br>" + sMESSAGE);**
**    ****out.println("</body></html>");**
**    ****out.close();**
**  ****}**
**}**

## Tomcat Setup -1

- Tomcat is a free servlet container that you can download from the web
- Download it from here:**http://tomcat.apache.org/**** **
- After installation, the Tomcat folder will contain "Start Tomcat" and "Stop Tomcat" shortcuts
- Make sure you have the JAVA_HOME environment variable set so Tomcat can find your JDK. For example, if your JDK is installed in c:\jdk1.5_07 then
- JAVA_HOME=c:\jdk1.5_07
- In Windows, you set an environment variable by going to control panel, System, Advanced, and click on the Environment Variables button

## Tomcat Setup -2

- By default, once Tomcat has loaded a servlet, it does NOT reload it even if you modify and recompile the servlet
- You must stop Tomcat and then re-start it in order for Tomcat to load the new version of your servlet
- This results in better runtime performance since Tomcat doesn't need to check for re-loads each time a web user submits a request to the servlet
- You can override this behavior and have Tomcat reload the servlet each time by changing the "reloadable" option in the Admin Tool to "true"

## Tomcat Setup -3

- Once Tomcat is running, you can go to the Tomcat home page (on your PC):

## Tomcat Setup -4

- To set up a new web application (or servlet) with Tomcat, you need to add a directory under the **webapps** dir and create a subdirectory called **WEB-INF**.
- WEB-INF needs to contain a **web.xml** file (a Tomcat/servlet configuration file)
- Make sure you are consistent in the way you use upper case and lower case in your directory names (since UNIX web servers will be picky about that detail!)
- The easiest thing to do is to make a copy of the webdav directory and give it a new name
- After the WEB-INF directory is created, create a subdirectory under it called **classes**
- Your Java package/classes will go under this directory
- (See next slide)

## Tomcat Setup -5

## Tomcat Setup (Oracle Tip) -6

- Tomcat looks for libraries that match *.jar
- In their wisdom, Oracle's JDBC driver is named classes12.zip.
- In order for Tomcat to reliably load the Oracle driver, you need to rename it classes12.jar (and place it in the Tomcat/common/lib directory)

## Tomcat Setup (mySQL Tip) -6

- External libraries to be used by Tomcat can be placed in the Tomcat common/lib directory
- For example, you might put mail.jar or mySQL’s jar there

## web.xml file -1

- Tomcat’s web.xml contains servlet configuration info
- You can find it here

## web.xml file -2

- web.xml contains servlet configuration info for Tomcat
- You need to add a **servlet entry** and a **servlet mapping entry** for each servlet you want Tomcat to run.
- Add your entries ***after*** the <web-app> tag inside web.xml
- Tip—start with existing web.xml and swap in text below
-  <servlet>
-     <servlet-name>DesignPageServlet</servlet-name>
-     <servlet-class>gov.noaa.DesignPageServlet
-     </servlet-class>
-   </servlet>
-  <servlet-mapping>
-     <servlet-name>DesignPageServlet</servlet-name>
-     <url-pattern>/DesignPageServlet</url-pattern>
-   </servlet-mapping>

## web.xml file -3

- Servlet mappings are how Tomcat matches a URL to the correct servlet on disk
- They aren’t required to have the same name (although it usually makes sense to keep things simple and give them the same name)
- For example, the following URL in your browser might invoke the DesignPageServlet on Tomcat
- http://noaa.gov:8080/mywebapp/DesignPageServlet
- is invoked with this url-pattern in web.xml
- <url-pattern>/DesignPageServlet</url-pattern>

## Tomcat Admin Tool -1

- Tomcat comes with a web based admin tool that you can use to configure Tomcat
- You don't have to use the tool--you can edit the config files (server.xml) manually if you know what you are doing
- Or if you are satisfied with the Tomcat default values, you don't need to run the Admin Tool at all
- Run the Admin Tool by going to the Windows Start Button, Apache Tomcat program group, Tomcat Administration
- This will load the admin tool in a web browser
- You will be prompted for the admin login (use the values you specified during the install process)

## Tomcat Admin Tool -2

## Tomcat Admin Tool -3

## Servlets, Actions, and Tomcat -1

- When Tomcat is running on your local machine, you specify **localhost:8080** in your URL (e.g. form action).
- By default, Tomcat runs on port 8080
- You can change this to port 80 (so you never have to specify a port number) by using the admin tool or by editing the [tomcat-home]/conf/server.xml file and changing the default port from 8080 to just 80
- For example, the following form action would refer to a servlet named *MyServlet* that is running in the *wms* folder on Tomcat running on the *local* machine
- <form action='http://localhost:8080/wms/MyServlet' method=GET>
*MyServlet* would reside in /<TomcatDir>/webapps/wms/WEB-INF/classes

## Servlets, Actions, and Tomcat -2

- You could also invoke your servlet by calling it directly from a browser address bar:

## Servlet Development Summary

- Step 1 – Create your html web form
- Step 2 – Create your Java Servlet
- Step 3 – Create app directory under [tomcat]/webapps
- Tip--copy webdav directory and give it new name
- Step 4 – Modify web.xml file with your Servlet mappings
- Step 5 – Start or re-start tomcat
- Step 6 – Test servlet from your web form, remembering to restart Tomcat anytime you change your Servlet or your web.xml file
- Alternatively, you may be able to set reloadable=true

## Exercise 1

- Create the "Design your own web page" web page (html)
- Write your servlet class (name it DesignWebPageServlet)
- Download and install Tomcat (if it has not already been installed on your machine)
- Create a folder with your name (e.g. jeff) under the [tomcat-dir]/webapps directory (see earlier slide) and edit your web.xml file to configure the DesignWebPageServlet
- Deploy your servlet to Tomcat (place your package/classes under the **classes** directory under the **WEB-INF** directory
- Specify your form action to be a HTTP GET to your servlet
- Test your web application!
- Extra credit 1: rewrite your web page to do a HTTP POST
- Extra credit 2: write an Ant script that builds and deploys your servlet

## Exercise 2

- Create a guest book web application that prompts the user for a name, an email address, and a message.
- When the user submits this information to your servlet, the servlet should write the user's information to a text file on disk (or database table) and then return a web page containing the current entries in the guest book
- Extra credit: Add an admin feature that allows a user to delete a guest book entry if they know the admin password
- Extra credit: write an Ant script that builds and deploys your servlet

## Exercise 2 (continued)

- Tip– start out with a simple servlet, that when invoked from the
- browser simply reads a guest book text file that you created
- yourself. It should read this text file and return it to the browser
- (preferably formatted nicely in an HTML table)
- Tip – the code that reads the guest book file could be in a class
- called GuestBook.java