As we know, a Servlet is a server side program. Its basic functionality is to provide dynamism for the web pages. In real time website development, there involves not only servlets but also pre-created html pages, images etc. Therefore, to bundle these resources in a structured manner, SERVLETS specification mandates a hierarchy of directories to place the web resources at appropriate location.
According to the specification, every web application (interactive online application) should have a root directory. Under that directory we directly place our html files, images and jsps. Root directory should have a sub directory called WEB-INF. Within WEB-INF directory we should have a file by name web.xml and two directories by name classes and lib. Our Servlet class files are to be kept in the classes directory. Any java archive files are to be placed in the lib directory. Web.xml is known as the deployment descriptor. Primarily we register the servlets with the application through this file. Container knows about the details of the servlets and their configuration and deployment information through this file only.
Example web application: – In this application, we have an html page that acts as login page for the website. Our first Servlet receives user name and password from the form and authenticates the user. The application directory structure is as follows.
Loginapp
iogin.html WEB-INF
web.xml
classes
AuthenticationServlet. class
lib
Classesl2.jar
In the above hierarchy, loginapp is the root directory. Login.html is the login web page for. the application. Servlet class is AuthenticationServlet. For the database connection we are using oracle thin driver. Therefore classesl2.jar is required.
Source code of loqin.html
<HTML>
<BODY BGCOLOR=cyan>
<CENTER>
<H2> LOG IN TO OUR WEBSITE </H2>
<FORM ACTION="http://localhost:8080/loginapp/authenticate">
USER NAME<INPUT TYPE="text" NAME="user"<BR>
PASSWORD<INPUT TYPE="password" NAME="pwd"<BR>
<INPUT TYPE="submit" VALUE=" click here to login" > </FORM>
</CENTER>
</BODY>
</HTML>
Source code of web.xml
<?xmlversion="1.0"encoding="ISO-8859-l"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun. com/dtd/web-app_2_3. dtd">
<web-app>
<servlet>
<servlet-name > login </servlet-name >
<servlet-class >AuthenticationServlet</servlet-class >
</servlet>
<servlet-mapping >
<servlet-name>login</servlet-name>
< url-pattern >/authenticate </url-pattern >
</servlet-mapping >
</web-app>
Source code of AuthenticationServiet.iava
import Java.io. *;
import java.sql. *;
import javax.Servlet. *;
public class AuthenticationServlet extends GenericServlet {
Connection con;
public void init(ServletConfig config)throws ServletException
{
try
{
Class.forName("oracle.jdbc. driver. OracleDriver");
String url= "jdbc: oracle: thin: @ local host: 1521: orcl";
con=DriverManager.getConnection(url, "scott", "tiger");
}
catch(Exception e)
{
e.printStackTrace();
}
}//init()
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException
{
Statement st=null;
ResultSet rs=null;
String user=req.getParameter("user");
String pwd=req.getParameter("pwd");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<HTML>");
outprintln("<BODY BGCOLOR=wheat>");
try
{
st=con.createStatement();
String sql="SELECT * FROM OURUSERS WHERE USR= w’+user+AND PASSWORD="’+pwd+"’";
rs=st.executeQuery(sql);
if(rs.next())
out.println("<H2>WELCOME"+user+’TO OUR WEB 5ITE</H2>"); else
{
out.println("<H2>INVALID USER OR PASSW0RD</H2>");
outprintin("<A HREF=./login.html> LOGIN AGAIN</A>");
}
}//try
catch(Exception e){ e.printStackTrace();
}
finally
{
try
{
if(rs !=null)
rs. close(); if(st !=null)
st close();
}
catch(Exception e){ e.printStackTrace(); }
}//finally
outprintln("</BODY >");
outprintln("</HTML>");
out.close();
}//service()
public void destroy()
{
try
{
if (con !=null)
con.close();
}
catch (Exception e)
{
e. printStackTraceQ;
}
}//destroy()
}//class
After developing the Servlet source code, compile it and copy the class file into the classes directory. Once all the files in the directory structure are ready, copy the loginapp into the webapps directory of the tomcat installation directory. Then start the Tomcat container. We get the following message on the Tomcat console. Installing web application at context path /loginapp from URL file: D:\Tomcat 5.0\webapps\loginapp
The above message is an indication that the web application is successfully deployed. Now, open the browser and type the following URL to get the login screen.
http://localhost:8080/loginapp/login.html
If we observe the implementation of AuthenticationServlet class, inside the init method we provided the database connection to the Servlet. It ensures that during its initialization itself, the Servlet acquires the database connection.
In the service method, by calling getRequestParameter method, we retrieved the user name and password entered in the login form.
In the database already a table by name ourusers exists. It has two columns usr and password. In that table, the list of valid users is maintained. Servlet needs to find whether the user name and password it received from the html form does exist in the database. Therefore, Servlet submitted SELECT SQL statement to the database by calling executeQuery method on the Statement object. This method returned the ResultSet object. In the if condition next method is called on the ResultSet object to find if the intended record exists. In the else part of the condition error message is displayed, a hyper link is created and sent to the client to enable the login again.
ServletResponse object is used to get an output stream to the web client by calling getWriter method. Calling setContentType method on the response object sets the MIME type to the server response to be given to the client.
In the destroy method, connection is closed. This method is called only when the Servlet is un-deployed.
