Advertisement

What is Servlet ? | How to write java servlet program | How to Connect Servlet with Database

 

What is servlet? An Introduction to Java Servlets



The basic purpose of servlet is to develop web applications.  Before servlets, there was a specification called CGI.  Servlets specification developed by SUN Microsystems. A lot of server vendors came in picture for implementing these specifications of servlets. In general Servlets are  set of rules given by SUN Microsystems in the form of Interfaces.  The server vendors have developed/created their own classes by implementing the interfaces developed by SUN.

The collection of classes developed by server vendors and Interfaces developed by SUN Microsystems are known as Servlet-API.


servlets in java


What is servlet

It is a server side platform independent, dynamic and multithread java program, which execute in the context of server for extending the functionality of server.  When many users make a request to the same servlet then all requests will be processed parallelly by the container by creating multiple threads for the same servlet. In order to deal with servlet programming, we must import below given packages into our java program.

12javax.servlet.*;
javax.servlet.http.*;



  • javax.servlet.Servlet is one of pre-defined top most interface, which is containing these methods to implement[init(), service(), destroy().
  • javax.servlet.GenericServlet is one of the predefined abstract class which is implementing javax.servlet.Servlet interface,  this GenericServlet class help us for developing protocol independent applications.
  • Javax.servlet.http.HttpServlet is sub class of GenericServlet used for developing/creating protocol dependent application  [ HTTP protocol ]

Let's assume Myserlet.java is our own class always recommended to extends HttpServlet servlet, as  internet is supporting HTTP protocol right 🙂  In real time, we can use HttpServlet only not GenericServlet remember.



Steps to Write Java Servlet Program



Let us look at the basic steps to develop java servlet application.

Like writing Java code, Servlet program is not to execute through command prompt.  We need to follow some steps in order to develop any servlets program.  Even for a small HelloWorld program also one must follow this standard directory structure/rule which is prescribed by sun Microsystem.

  • Create one root directory of any name with your choice, and create another directory within that directory with this name "src" and now write one servlet program and copy this program into that ‘src’ folder
  • Now create one more folder ‘web-inf’ in the root directory, this contains web.xml file.
  • Create "classes" folder with in web-inf folder
  • Now compile our servlet program which is in "src" folder, so we will get one .class file, just copy this .class file into classes folder in web-inf folder
  • We are going to run our servlet by using Tomcat server.  So we have to set the class path for Tomcat related jar file, servlet-api.jar
  • You will find this jar file in your Tomcat directory\common\lib\,
  • Similar to Tomcat server,  if we are using WebLogic server, we need to set the class path for weblogic related jar files, i.e. weblogic.jar which is in c [your drive]:\bea\weblogic\server\lib
  • If servlet is dealing with any database like MySql or Oracle, we must have to create a folder  ‘lib’ with in web-inf folder
  • Once everything is done, now copy our root directory into Tomcat/webapps folder, and start the server and see the output.

Directory Structure


Steps To Develop Servlet Program
  • Set servlet-api.jar ( Will be available in your tomcat/lib directory) in your class path
  • Open notepad or any other text editor Notepad++ or some thing else,
  • Import javax.servlet.*;
  • Import javax.servlet.http.*;
  • Now create one user defined public class, which must extends javax.servlet.GenericServlet or  javax.servlet.http.HttpServlet.
  • We know that GenericServlet implementing Servlet interface,  and HttpServlet is the sub class of GenericServlet.  Thays why by default all life cycle methods will be overridden in GenericServlet class, so just override which need [No need all] life cycle methods of servlet in HttpServlet.
  • Save your servlet program with an extension .java
  • You must have to place your .java files in root folder or in src folder, and .class files in classes files
  • Compile and check the output.


How to Write Deployment Descriptor, web.xml In our Servlet




This web.xml work like index of books, it is containing details of static  and dynamic web resource programs.  The aim of web.xml is to hide or to achieve the security for the web application by not showing in the URL.

Deployment Descriptor [ web.xml ] in Servlets

Syntax

12345678910<web-app>
 <servlet>
    <servlet-name> Our First servlet </servlet-name>
    <servlet-class>/Our Servlet class name</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name> Our First servle </servlet-name>
<url-pattern>/UrlFriendlyName</url-pattern>
</servlet-mapping> </web-app>
  • We have to call our servlet by typing its <url-pattern> only
  • i.e.  http://localhost:8080/OurServletApplicationFolderName/UrlFriendlyName
  • Once we call our servlet just did above, then the server will load web.xml first and verifies that the url pattern we are calling is similar as what in <url-pattern> tag in web.xml or not
  • If it matched, it will check the <servlet-name> and will jump to <servlet-name>  in <servlet> tag and, will check whether the value of <servlet-name> are same or not if same it will load our class in <servlet-class>.
  • Finally our .class file will be executed, so we can check the result.


Example on Servlet Life Cycle in Java



ServletLifeCycle.java

1234567891011121314151617181920212223242526272829303132333435363738package java4s;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycle extends HttpServlet
{

	public ServletLifeCycle()
	{	
		System.out.println("showing from default constructor");
	}

public void init(ServletConfig config)
{ System.out.println("showing from Init method...!"); }
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{ res.setContentType("text/html"); PrintWriter pw = res.getWriter(); pw.println("showing from doGet method"); pw.close(); }
public void destroy()
{ System.out.println("showing from Destroy methods"); } }


How to Connect Servlet with Database 




Let us see how to connect servlet application with database. In our application i am going to display all the records from the table ‘Oop77‘.

  • Make sure you have Oop77 table in the database with some data in it
  • Make sure you have ojdbc14.jar file in your classpath and lib directory as well as  you can check the same in this figure.

Files Required

  • index.html
  • ServletDatabaseConnect.java
  • web.xml
  • ojdbc14.jar

index.html

123456<form action="show" method="post">
  <font face="verdana" size="2">
Enter Table Name :<input type="text" name="table">
<input type="submit" value="Display">
</font> </form>

ServletDatabaseConnect.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546package Oop77;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDatabaseConnect extends HttpServlet  
{
    protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
        PrintWriter pw=res.getWriter();
        res.setContentType("text/html");        
        String tb=req.getParameter("table");    

        try
        {
             Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
             Statement st=con.createStatement();
             System.out.println("connection established successfully...!!");    
             ResultSet rs=st.executeQuery("Select * from "+tb);
             pw.println("<table border=1>");                  while(rs.next())                  {                      pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+                                       "<td>"+rs.getString(3)+"</td></tr>");                  }              pw.println("</table>");              pw.close();         }         catch (Exception e){             e.printStackTrace();         }     } }

web.xml

1234567891011121314<web-app>

    <servlet>
        <servlet-name>ServletDBConnect</servlet-name>
        <servlet-class>java4s.ServletDatabaseConnect</servlet-class>    

    </servlet>

    <servlet-mapping>
            <servlet-name>ServletDBConnect</servlet-name>
            <url-pattern>/show</url-pattern>
    </servlet-mapping> </web-app>

Post a Comment

0 Comments