LDSTechForumProjects

Introduction to Servlets

This LDS Java Stack training covers Servlets and Basic Web App Architecture.

Introduction to Web App Development

Prerequisites

  • Installed LDSTech IDE (or other equivalent)
  • Basic knowledge of the Java language.
  • Basic knowledge of XML syntax and structure.
  • A laptop running Windows, Linux, or Mac OS.
  • A desire to learn.

Slide Deck

Media:IntroductionToWebAppDev.ppt

Servlets are part of the Java EE spec, and are fundamental to most MVC frameworks. This training will cover basic servlet concepts, and how to start developing servlets.

Intro To Web App Dev - Part 1

Basic WebApp Architecture

  • Web Client
  • Web Server

HTTP

  • Request Methods
  • GET
  • POST

History

  • CGI Overview
  • CGI Example
  • CGI Issues

Understanding the role of Servlets

  • Servlet Overview
  • Advantages of Servlets

Project Directory

  • Maven Project Directory Structure
  • Maven Descriptor (pom.xml)
  • Deployment Descriptor (web.xml)
Get Adobe Flash player

Lab 1: Hello World Servlet

Develop a servlet that can be called from a browser, and returns HTML for the browser to display "Hello World".

  • Download and unzip the project template.
    • Unzip the file into your workspace
    • In the LDSTech IDE go to File -> Import... -> Maven (expand) -> Existing Maven Projects -> Next
    • Browse to the unzipped project and press Finish
Update the pom.xml file with a servlet 2.5 dependency.
    <dependencies>
        <dependency> 
            <groupId>javax.servlet</groupId> 
            <artifactId>servlet-api</artifactId> 
            <version>2.5</version>
            <scope>provided</scope> 
        </dependency>
    </dependencies>
  • Test the Maven Project.
    1. Configure a Tomcat 6 server (not an LDSTech Server) in your IDE.
    2. Right click on the project, select "Run As", select "Run on Server". Select "Finish".
A browser window should open, and you should see "Hello World!" displayed.
  • Create the new Java Servlet.
    1. Right click on the project, select "New → Class". (You might need to choose New → Other... → Java → Class.)
    2. Create the Java servlet class with the following settings:
      • Source folder: \[project name]\src\main\java
      • Java package: org.lds.training
      • Class name: HelloWorldServlet
      • Superclass: javax.servlet.http.HttpServlet
  • Update the get method of the new Servlet.
    public class HelloWorldServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");  
   
            PrintWriter out = response.getWriter();
            Date today = new Date();
            out.print("<html> " + "<body> " + 
                      "<h1 align=center>Hello World</h1> " +
                      "<br> " + today +
                      "</body> " +"</html>");
        }
    }
Update the web.xml file with the servlet definitions. Note: Your IDE may have done this for you.
    <servlet>
        <servlet-name>HelloWorldServlet</servlet-name>
        <servlet-class>org.lds.training.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/HelloWorldServlet</url-pattern>
    </servlet-mapping>
  • Test the new Servlet.
    1. Right click on the project, select "Run As", select "Run on Server". Select "Finish".
    2. Change the URL to http://localhost/[project name]/HelloWorldServlet

Lab 1 Solution

Get Adobe Flash player

Intro To Web App Dev - Part 2

Servlet Life Cycle

  • Servlet Container
  • HttpServletRequest
  • HttpServletResponse
  • Servlet Class
  • init()
  • service()
  • doGet()
  • doPost()
  • destroy()
Get Adobe Flash player

Lab 2: Page Hit Counter

  1. Extend your servlet to return a count of how many times the servlet has been called, as well as the number of concurrent users. If possible, persist the state between server restarts.
  2. Retrieve and return HTTP request header information.
  3. Configure your servlet to load on startup.
  • Declare a private integer variable within the servlet class called count.
  • Update the init method of the new Servlet.
    public void init() throws ServletException {
        // Try to load the initial count from our saved persistent state
        try {
          FileReader fileReader = new FileReader("InitDestroyCounter.initial");
          BufferedReader bufferedReader = new BufferedReader(fileReader);
          String initial = bufferedReader.readLine();
          count = Integer.parseInt(initial);
          return;
        }
        catch (FileNotFoundException ignored) { }  // no saved state
        catch (IOException ignored) { }            // problem during read
        catch (NumberFormatException ignored) { }  // corrupt saved state

        // No luck with the saved state, check for an init parameter
        String initial = getInitParameter("initial");
        try {
          count = Integer.parseInt(initial);
          return;
        }
        catch (NumberFormatException ignored) { }  // null or non-integer value

        // Default to an initial count of "0"
        count = 0;
    }
  • Update the destroy method of the new Servlet.
    public void destroy() {
        // Try to save the accumulated count
	try {
	    FileWriter fileWriter = new FileWriter("InitDestroyCounter.initial");
	    String initial = Integer.toString(count);
	    fileWriter.write(initial, 0, initial.length());
	    fileWriter.close();
	    return;
        }
	catch (IOException e) {  // problem during write
	    // Log the exception. 
	}
    }
  • Update the get method of the new Servlet.
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html");  

	count++;

        PrintWriter out = response.getWriter();
        Date today = new Date();
        String headerName1 = "User-Agent";
        String headerName2 = "host";
        out.print("<html> " + "<body> " + 
                  "<h1 align=center>Hello World</h1> " +
        	  "<br> " + today +
        	  "<br> Hit Count: " + count +
        	  "<br> Request Method: " + request.getMethod() + 
        	  "<br> User Agent: " + request.getHeader(headerName1) +
        	  "<br> Host: " + request.getHeader(headerName2) +          		  
        	  "</body> " + 
        	  "</html>");
    }
  • Configure the servlet to load on startup
Update the web.xml file
    <web-app 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"
     version="2.5">

        <display-name>Welcome to Java Stack Training</display-name>
        <description>Introduction to Servlets</description>

        <servlet>
  	    <display-name>HelloWorldServlet</display-name>  
  	    <servlet-name>HelloWorldServlet</servlet-name>
  	    <servlet-class>org.lds.training.HelloWorldServlet</servlet-class>
            <load-on-startup>1</load-on-startup>  	
        </servlet>

        <servlet-mapping>
  	    <servlet-name>HelloWorldServlet</servlet-name>
  	    <url-pattern>/HelloWorldServlet</url-pattern>
        </servlet-mapping>
    </web-app>
  • Test the new Servlet.
    1. Right click on the project, select "Run As", select "Run on Server". Select "Finish".
    2. Change the URL to http://localhost/[project name]/[servlet name]

Lab 2 Solution

Get Adobe Flash player

Intro To Web App Dev - Part 3

Event Listeners

  • web.xml

Servlet Filters

  • web.xml

Servlet Response

  • Redirect
  • Request Dispatch
Get Adobe Flash player

Lab 3: Login Filter

Develop a servlet filter that can be used to prevent a user from calling your servlet unless they submit their name.

Note: There are multiple ways to do this. Below are step-by-step instructions specifically for the LDSTech IDE.

  • Create an HTML form page (client).
    1. Create (or update) "index.html" in the src\main\webapp subdirectory.
    2. Add HTML content
    <html>
        <body>
            <h2>Hello World!</h2>

            <form action="HelloWorldServlet" method="POST">
                <p>Name <input type="text" name="fullName" size="40"></p>
	        <p><input type="submit" value="Submit"></p>
            </form>
        </body>
    </html>
  • Create a new filter.
    • Right click on the project, select "New/Other", select "Web/Filter".
    • Configure the filter properties.
      • Source folder: \[project name]\src\main\java
      • Java package: org.lds.training
      • Class name: LoginFilter
  • Add business logic to the filter.
    public class LoginFilter implements Filter {
    ...
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse)response;
            String name = request.getParameter("fullName");
	    
	    if (name == null || name.equals("")) {
                res.sendRedirect("index.html");
                return;
	    }

	    // pass the request along the filter chain
	    chain.doFilter(request, response);
        }
    }
  • Configure the filter.
Update the web.xml file
    <filter>
        <display-name>LoginFilter</display-name>
        <filter-name>LoginFilter</filter-name>
        <filter-class>org.lds.training.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <servlet-name>HelloWorldServlet</servlet-name>
    </filter-mapping>
  • Override the doPost method.
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
  • Update your servlet to display the user name (optional).
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
	count++;
	String name = request.getParameter("fullName");
	    
        PrintWriter out = response.getWriter();
        Date today = new Date();
        String headerName1 = "User-Agent";
        String headerName2 = "host";
        out.print("<html> " + "<body> " + 
        	  "<h1 align=center>Hello " + name + "</h1> " +
        	  "<br> " + today +
        	  "<br> Hit Count: " + count +
        	  "<br> Request Method: " + request.getMethod() + 
        	  "<br> User Agent: " + request.getHeader(headerName1) +
        	  "<br> Host: " + request.getHeader(headerName2) +          		  
        	  "</body> " + 
        	  "</html>");
    }

Lab 3 Solution

Get Adobe Flash player

Credit: All clip art shown in videos is from the Microsoft clip art library.
This page was last modified on 27 July 2012, at 18:36.

Note: Content found in this wiki may not always reflect official Church information. See Terms of Use.