Servlets by Example Joe Howse 7 June 2011
What is a servlet? A servlet is a Java application that receives HTTP requests as input and generates HTTP responses as output. As the name implies, it runs on a server. Dependency: A "servlet container" such as Jetty or Apache Tomcat. A servlet is not similar to an applet. An applet's access to server-side files is unprivileged and slow (requiring downloads) because the applet itself runs client-side. Let's consider a step-by-step approach to setting up a simple servlet: 1. Get and configure Jetty. 2. Create the necessary directory tree for the servlet. 3. Write a webpage as a front-end. 4. Write a config file. 5. Write, compile and deploy the Java code. 6. Test it!
Setting up Jetty Follow the instructions at: http://docs.codehaus.org/display/jetty/quick+start At the download step, you want the latest stable version from: http://download.eclipse.org/jetty/ On Dalhousie's bluenose server, adapt the instructions as follows: $JETTY_HOME should be some web-accessible folder. ex. ~/public_html/jetty You should choose an unused port number between 4001 and 4030. I am using 4020 right now, so choose something else. Your test servlet can be accessed at: http://bluenose.cs.dal.ca:####/ (Here, #### should be replaced by your port number.)
Directory tree $JETTY_HOME/webapps/MyServlet/ index.html WEB-INF/ web.xml classes/myservlet/ *.class *.java build.sh lib/ *.jar A servlet must include: statically linked code (.class) configuration (.xml) Optionally, it may include: dynamically linked code (.jar) front-end website scripts (.html,. php, etc.) and content (.jpg, etc.) Just for convenience, we are putting our source code (.java) and build script (build.sh) inside the servlet directory tree too. These are not used at run-time.
index.html <html><body> <form method="get" action="myservlet"> <input type="text" id="query" name="query" size="50"/> <input type="submit" value="submit"/> </form> </body></html> Our webpage is an input form that sends to our servlet a get request with a field called query. Our servlet is called MyServlet.
web.xml <?xml version="1.0" encoding="utf-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>myservlet</servlet-name> <servlet-class>myservlet.myservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> Our web.xml config file specifies the servlet name, paths, etc.
MyServlet.java (1/2) package MyServlet; import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.servletconfig; public class MyServlet extends HttpServlet { // Initialize servlet and any back-end model it uses. @Override public void init(servletconfig config) throws ServletException { super.init(); // Initialize back-end model here. } // Respond to GET request. @Override protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); String query = request.getparameter("query"); out.println("<html><body>your query was \"" + query + "\"!</body></html>"); } // Continued on next slide....
MyServlet.java (2/2) //... Continued from previous slide. } // Respond to POST request. @Override protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { doget(request, response); // Here, POST is handled the same as GET. } // Return description of servlet. @Override public String getservletinfo() { return "MyServlet is a minimal example, echoing back a query string."; } Our MyServlet.java source file defines the mapping from requests to responses. Our simple example could be extended to: Handle errors. Initialize and use an instance of another class as its back-end.
build.sh #!/bin/sh # Configuration variable. # The path to Jetty. JETTY_HOME=~/public_html/jetty # Build command. javac -cp $JETTY_HOME/lib/servlet-api-2.5.jar MyServlet.java Our build script compiles MyServlet.java and links it with the required library in Jetty. Do not forget to set executable permission for the script. chmod +x build.sh
Testing MyServlet Run the build script!./build.sh Navigate to $JETTY_HOME and run: java -jar start.jar Direct your Web browser to: http://bluenose.cs.dal.ca:####/myservlet (Here, #### should be replaced by your port number.)
Summing up Writing and deploying a minimal servlet involves just a few steps. The complexity is not much greater than scripting solutions, such as: PHP, CherryPy (Python), Ruby on Rails (Ruby) A servlet can integrate seamlessly with other back-end Java code.