RHS -> Allan-> WSPJ ->Exercises ->Login

Login check:

An easy Servlet exercise (Author: Anders Borjesson, adapted by Allan Helboe)

You are to make a simple login form (username + password) and a Servlet that checks if the username and password are OK.

Login form

  1. Start a new Netbeans project, choose Web as the category
  2. Close and delete the index.jsp file
  3. Create a HTML page as the figure below

loginform

Don't worry about the visual design of the page.
The password field is of type password - that's why you see the stars in the input field in the browser.

The action attribute of the form should refer to a page called checklogin.

The method attribute of the form must be post.

Check login

Make a Servlet using Netbeans:

This Servlet is supposed to check the validity of the username and password from the login form.

Things can go wrong in many ways:

 
Error Action
No username is entered A HTML documents informs about the error and offers a link "Try again" that loads the login form again
No password is entered
Username or password (or both) are not legal in this application

If username and password is accepted the user should see a HTML-page with a greeting!

HTTP methods GET and POST

In the login form page change the method attribute from post to get.

What effects does this have when you re-run the web application?

Do you prefer GET or POST?

Title

As you can see from the above screen shots the title of the Servlet generated pages are "Servlet checklogin".

Change the Servlet to generate a more appropriate title.

 

Extra: Forwarding

This is an extra exercise for those of you who finished the above exercises quickly: The fast and the fearless!

In case of bad username or password the Servlet should forward the request back to the login form.

Make another NetBeans project.

Technical hint:

getServletContext().getRequestDispatcher("/login.jsp?message=No username").forward(request, response);

forward the request. More information in Marty Hall: Core Servlets and JavaServer Pages, page 223-224.

Note that the Servlet is not allowed to do send any output to the client (browser) prior to forwarding.

Note that the login form page is now a JSP page, not an HTML page. This allows is to show an optional message to the user.


Maintained by: Allan Helboe
Updated: 28 November, 2007 15:57