Tutorials : Building Web Applications Using Servlets and JSP :

Application!

So here we are finally, ready to build a server side Java application. We will try to use Servlet & JSP where ever appropriate.

The Problem Statement:
The user will connect to our web site and will be served a login page. After 'logging in' the user will go to our welcome page. The user can access the welcome page and the subsequent pages ONLY after login.

Assume that the userid , password and user's Name are stored in a database. So the login program will need to verify userid password and display a personalized welcome message such as 

Welcome "user Name" to ....!

Also assume that the welcome page has to display a lot of other stuff and not just the Welcome message. Also the subsequent pages to which we will provide links from the welcome page will also have a lot of 'HTML' code and may be zero or less processing.

The solution:
The very fact that the login program needs to do some 'processing' makes it candidate for a servlet. We can potentially use a 'login' JSP which calls some method of a login bean and has rest of the HTML from the welcome page. But remember our rule of thumb: More processing - Servlet and More HTML - JSP. Basically separating the HTML & java parts make the maintenance easy as the HTML programmer can look at the HTML piece and the Java programmer can look at the Java piece.

Hence we will write a login servlet. But as we have assumed , the welcome page that we want to display has a lot of HTML code. So we should not 'generate' the HTML for welcome page from within the servlet. (Refer to "HTML generation" for more info. On generating HTML from within the servlet). So our options are: 

1. In the login servlet after verifying login information display the personalized welcome message. Then serve the welcome.html file (we will need to actually read the file and 'write' to the PrintWriter).

2. In welcome servlet verify the login info. Get the user name from the database, 'pass' it to welcome.jsp which will display the welcome message and the rest of the page.

The second approach has a little more processing overhead over the first but is much more maintainable. Actually, the second approach helps us in solving the other part of the problem: "The user should see the welcome page and subsequent pages ONLY after login".

We will implement this with session objects. After successful login we will create a session object. We will put the user name in to session object. All subsequent pages can be JSP pages which check if this session variable is not null. Only then, those pages will display the 'stuff'.

Enough of explanation! Now let's look at the actual code:

Our Sample HTML index.html will be:

	
<HTML>
<HEAD>

<BODY>
<FORM METHOD="POST"  ACTION="/servlet/Login">
<TABLE ALIGN=CENTER BORDER="0" >
<TR>
<TD VALIGN=TOP ALIGN=RIGHT>
	<B>User ID:</B>
</TD>

<TD VALIGN=TOP>
	<B><INPUT 	NAME		= "userId" 
			TYPE		= "TEXT" 
			MAXLENGTH	= "10" 
			SIZE		= "10"></B>
</TD>
</TR>

<TR>
<TD VALIGN=TOP ALIGN=RIGHT>
	<B>Password:</B>
</TD>

<TD VALIGN=TOP>
	<B><INPUT 	NAME		= "password" 
			TYPE		= "Password" 
			MAXLENGTH	= "6" 
			SIZE		= "6"></B>
</TD>
</TR>

<TR>
<TD VALIGN=CENTER>
	<B><INPUT 	VALUE		= "  Log In  " 
			TYPE		= "SUBMIT"></B>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

Note the form is using Post method and submitting to login servlet.

So our login servlet in Login.java file will look like:

	
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{ String userId = req.getParameter("userId"); String password = req.getParameter("password"); /************************************************************ ** call a method to validate the password which will return the ** User Name for authorized users and null string for un-authorised. **********************************************************/ String uName = validateUser(userId, password); // if uName is null .. user is not authorized. if (uName == null) { PrintWriter ot = res.getWriter(); ot.println(" Please verify the Userid and password"); ot.close(); } else { // So the user is valid let's create a seesion // for this user. HttpSession userSession = req.getSession(true); // put the user name session variable. userSession.putValue("userName", uName); // now we need to transfer the control to welcome.jsp RequestDispatcher rd = getServletContext().getRequestDispatcher("/welcome.jsp"); if (rd != null) { rd.forward(req,res); } } }// end of doPost }// end of servlet class

So our servlet is ready! Now the only piece remaining is welcome.jsp. So here is the code:

Welcome.jsp

	
<% if ( session.getValue("userName") == null) { %>

<% // here we can give some error message %>

<% } else {%>

 <!------- so this is the authorized user let's display the welcome 
 message --- >

<HTML>

 <HEAD>

<B> Welcome  <%= session.getValue("userName")%>

</B>

 </HEAD> 

<BODY>

  <!--- all the other stuff -->

</BODY>

</ HTML>
			
<%  }   %>

That's all ! Our sample web application is ready ! All the subsequent web pages can use the same mechanism discussed above to make sure that only authorized users access those pages.

Please note that this is just a sample web application and we are not catching any exceptions and performing any 'secure transactions'!

One can easily add a lot of 'exception handling' and informative error checking. Also we have not written the validateUser method. More about how to write this validateUser method .. sample JDBC application and servlet multithreading in the next article ....

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.