J2EE Course - Building Servlet Web Applications

This free online course will teach you how to build dynamic web applications using Java Servlets. You'll learn how to handle HTTP requests from a browser and return HTTP responses with dynamically generated HTML. You'll also learn about sessions, cookies, and how to package and deploy a servlet-based web application to a Tomcat web server.

Course Prep:

  1. Read chapter 2 in the Core Servlets and JavaServer Pages textbook.
  2. View the Java Servlets Powerpoint lecture (also available in pdf format here).

Course Exercises:

  1. Download and install the Sysdeo plugin in Eclipse, and create a new Tomcat project called assign03. Review the "Creating a Tomcat Web Application" course for assistance with this step.

  2. Download a pre-built HTML account login form that posts to a login servlet: login.html (NOTE: right-click on the link and select "Save Target As"). Place login.html in the root folder of your Tomcat project (the same location as index.html from the Creating a Tomcat Web Application course).

  3. Configure your web application so that login.html is the default welcome page.

  4. Create a servlet named LoginServlet.java. A servlet is a regular Java class that extends javax.servlet.http.HttpServlet. You can find an example of a servlet class in the Java Servlets powerpoint lecture for this course.

  5. Declare a variable that will track the number of login attempts each time the the servlet is in service. Do not use a static variable to accomplish this. Hint: consider the servlet life cycle, discussed in the powerpoint lecture.

  6. Build a method in the login servlet that retrieves a fictitious account balance when passed a username and password:

    float getAccountBalance(String UserName, String Password);

  7. Override the doPost method and provide the following implementation:
    • Get the username and password parameters from the Http request.
    • Call the getAccountBalance() method that you created above.
    • Set the response content type to "text/html".
    • Get an instance of a PrintWriter from the response object.
    • Write a welcome message to the response, including the username, using the PrintWriter's println() method.
    • Write the account balance to the response.
    • Write the number of login attempts that have occurred while this servlet has been in service.
  8. Package your web application into a war file and deploy it to Tomcat by copying it to Tomcat's webapps folder.
  9. Run your web application by entering http://localhost/assign03 in your web browser.

Congratulations - you have successfully built a servlet-based web application!

Check your work: assign03_Solution.war

Tips and Hints

This section contains some helpful notes for completing the course exercises.

  • Sun provides a free chapter in pdf format devoted to the tags inside web.xml:
    http://java.sun.com/developer/Books/javaserverpages/servlets_javaserver/...

  • Be sure to call out.flush(); in your servlet to send the output to the browser (added this
    line of code to the powerpoint slide).

  • You can call doPost from within doGet, and pass along the request and response
    objects. This lets your servlet support both GET and POST requests without duplicating
    the logic in both methods. It also lets you debug your servlet using the address window
    (GET) in Internet Explorer without having to use the login.html form (POST).

  • The action attribute of the form element inside login.html (provided on the assignment page)
    needs to point to your servlet. For example, if you set up a servlet-mapping url of "/AccountLogin",
    then the action attribute would need to be action="AccoutLogin" (without the slash).

  • The html tags named "input" inside login.html define the parameters that will be sent to the LoginServlet.
    For example, the first input element has a name="username" attribute. When the login page is submitted
    (user clicks the Get Account Balance button), this value will be sent to the server and added to the
    HttpServletRequest object. This same request object is the first parameter of the doGet and doPost methods,
    and the value can be retrieved using request.getParameter("name").

  • The name and password values can also be passed to the servlet using the URL address field in your browser by typing http://localhost/MyApp/AccountLogin?name=rick&password=biffle (assuming you had a web app named MyApp and a servlet mapping of /AccountLogin). Note that the name/value pairs start after the question mark, and are separated by an ampersand.

DiskCopy and Clean - Download

DiskCopy and Clean - Download

Safely Copy Everything to Your New Drive & Permanently Erase Data from Your Old Drive Are you purchasing a new hard drive? Disk Copy & Clean is the perfect solution for upgrading from your old hard drive to your new hard drive. DiskCopy & Clean moves all your data, applications and Windows to your new hard in one easy step. Plus, if you have partitions on your old hard drive, they can be moved and expanded proportionally to your new hard drive.

Special Offer: Save 20% with Coupon Code AFDCC20

ServletException: Error allocating a servlet instance


I am getting this error:

javax.servlet.ServletException: Error allocating a servlet instance
...
java.lang.UnsupportedClassVersionError: zpackage/LoginServlet
(Unsupported major.minor version 49.0)

How do I fix it?

Java version must be the same for Eclipse and Tomcat


This exception can occur when the servlet was built in a higher version of JDK than the JRE that is run by the webserver.

Make sure that both Eclipse and Tomcat are using the same version of Java (1.4.2 if you're following the installation instructions for this course).

Another thing to check is your "JDK Compliance level" - it has to be 1.4 if you're using Java 1.4.2. You can check it by going to Preferences --> Java --> Complier within Eclipse.

Track all hits to the servlet?


The exercise says to create a variable that will track the number of logins while the servlet is in service. I want to make sure I understand this properly.

I interpret this to mean the overall # of logins, not number of logins per user. For example, Joe is the first to login in the application. The servlet will be started, and after he logs in, the count is 1. Then Jane comes along and logs in - the count is now 2 and this is the count
she should see when the servlet returns her account balance. The count will continue to be updated in this manner until the servlet is removed by the web server.

Is my understanding correct?

Yes, just track all hits to the servlet


The main point of this step in the exercise is to understand that all requests are services by their own thread (ie. copy) of either doGet() or doPost(), and that this thread is executing against a single instance of the servlet loaded on the web server. Read through the powerpoint lecture for more information on a servlet's life cycle.

With this in mind, a variable declared at the class level will be accessible to all requests. If you update the class level variable from within doGet() or doPost(), then the updated value will be seen by all other requests.

This results in similar behavior to a variable declared as static.

Rick

How do I create a servlet in Eclipse?


I'm not sure how I'm supposed to do this. From Eclipse, I can't see the folder WEB_INF/classes. I was thinking right click on this and go to new/create, but I can't find a 'create servlet' menu anywhere. Is it a matter of just creating a text file and saving it in that folder? Or am I missing something?

Thanks,

Mike

Create a servlet as a regular Java class


The only difference is that it will need to extend the javax.servlet.http.HttpServlet class, which gives it servlet functionality.

Once you've created your servlet, then you'll need to override either the doGet() or doPost() method, or both.

Rick