• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Servlet

Steps for Sending Cookies

By Dinesh Thakur

Sending cookies to the client involves the following steps,

1. Create a Cookie object.

2. Setting the maximum age.

3. Placing the Cookie into the HTTP response headers.

Creating a Cookie Object

You create a cookie by calling the Cookie constructor that takes the following form Cookie(String cookieName, String cookieValue)

For example:

Cookie c = new cookie (“email”, “[email protected]”);

It creates a cookie c with a name email and value [email protected]

Setting the Maximum Age (OPTIONAL)

By default, when a cookie is sent to the browser it is stored in the browser’s memory and deleted when the user closes the browser. If you want to store the cookie on the hard disk instead of memory, use setMaxAge () method to specify how long (in seconds) the browser should keep the cookie before it expires. For example, on using the statements

c.setMaxAge (60*60);

The browser will delete the cookie after 60 minutes.

Place the Cookie in Response Headers

After creating the cookie object and calling the setMaxAge () method, the next step is to send the cookie to the client. In order to send the cookie, call the addCookie () method of HttpServletResponse. This method will insert the cookie into a Set-Cookie response header. For example,

response.addCookie (c);

Now let us consider a servlet that will create two cookies named Name and email and send it to the client.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class setCookie extends HttpServlet

{

    public void doGet (HttpServletRequest request, HttpServletResponse

    response) throws ServletException, IOException

    {

        PrintWriter out;

        //set content type and other response header fields first

        response.setContentType (“text/html”);

        //write the response of the data

        out = response.getWriter ();

        //create a cookie            

       Cookie c1 = new Cookie (“name”, “Daljeet”);

       Cookie c2= new Cookie (“email”, “[email protected]”);

       response.addCookie (c1);  

       response.addCookie (c2); 

       out.println (“<HTML> <HEAD> <TITLE>”);

       out.println (“Settings cookies”);

       out.println (“</TITLE> </HEAD> <BODY>”);

       out.println (“Two cookies are set named: name and email”);

       out.println (“</BODY> </HTML>”);

       out.close ();

    }

}

Output:   Two cookies are set named: name and email    

Session Tracking Using Cookies

By Dinesh Thakur

The Hypertext Transfer Protocol (HTTP) is the network protocol that the web servers and the client browsers use to communicate with each other. The HTTP is a stateless protocol. A client browser opens a connection and requests for a resource from the web server. The web server then responds with a requested resource and closes the connection.

After closing the connection, the web server does not remember any information about the client. So any next request from the same client will be treated as a fresh request without any relation to the previous request. This is what makes HTTP a stateless protocol. This protocol works fine for simple web browsing where each request typically results in an HTML file being sent back to the client. This is because web server does not need to know whether a series of requests came from the same client or from a different client. However, maintaining state is important in just about any web application. The appropriate example is a shopping cart where user select items, add them to their shopping cart and continue shopping. If you want to associate a shopping cart with a user over multiple page requests, then you need some method of maintaing state. One way of maintaing state is to use cookies.

Cookies are small textual files that a web server may send to the user’s web browser which in turn saves it to the hard disk (or if they are temporary in the web browser’s memory). The server sends the cookie to the browser in response to an initial request. Subsequent request sends the same cookie back to the server, which enables the server to identify these requests as being from the same client. By letting the server read information it send to the client previously, the site can provide visitors with a numbers of benefits such as,

• Saving login identity i.e. user names.

• Customizing sites : Many web sites now have pages where users can customize what they see when they arrive. After giving the user choice of layouts and color schemes, the site stores the preferences on the client’s computer through the use of cookies. The user can return to the site at any time and get the previously configured page.

• Identifying a user during e-commerce session.

• It let sites remember which topics interest certain users and show advertisements relevant to those interests.

• Frequent visitor bonuses.

• Bookmarks : Cookie let the use remember where he was when he last visited the site.

• Games : Cookie let remember the current or highest scores and present new

  challenges based on past answers and performance.

In the simplest form, cookies store data in the form of name-value pairs with certain additional attributes which are exchanged in the response and request headers. Each attribute/value pair is separated by a semicolon. The web servers send a cookie by sending the user-cookie response header in the following format

set-cookie: Name= Value; Comment= COMMENT; Domain= DOMAINNAME;

Max-age= SECONDS         ; Path= PATH; Secure; Version = 1*DIGIT

Here,

• Name is the name of the cookie.

• Value is the value this name can hold.

• Comment is an optional parameter that specifies the purpose associated with the cookie.

• Domain is an optional parameter that is used to specify the domain to which the cookie will be sent in future requests. By default, it is the host name of the domain that has sent the set-cookie header.

• Max-age is an optional parameter that specify how long (in seconds) the browser should keep the cookie before it expires.

• Path is an optional parameter that specifies the URL path for which the cookie

 is valid.

• The Secure parameter specifies whether the cookie should be sent only over a

  secure connection (HTTPS). By default its value is false.

In Java, cookies are created and manipulated via the javax.servlet.http.Cookie class. This class provides numerous methods. Some of the most commonly used ones are,

Method

Description

String getComment ()             

Returns the comment associated with the cookie.

String getDomain ()                

Returns the domain limitation associated with the Cookie.

int getMaxAge ()                     

Returns the maximum age allowed for this cookie.

String getPath ()

Returns the path limitation fort this servlet.

boolean getSecure ()               

Returns true if this cookie requires a secure connection.

String getName ()                    

Returns the name of the cookie.

String getValue ()                   

Returns the value of the cookie in string format.

void setComment

(String purpose)

Sets the comment that describe the cookie’s purpose.

void setDomain          

(String pattern)                                    

Specifies the domain within which the cookie should be presented.

void setMaxAge

    (int expiry)                      

Sets the maximum age of cookie in seconds.

void setPath  

(java.lang.String url)                                           

Specifies the path for the cookie to which the  client should return the cookie.

void setValue  

(java.lang.String newValue)                               

Assigns a new value to a cookie after the cookie is created.                       

                                            Some methods of Cookie class

Understanding HTML Forms

By Dinesh Thakur

Before handling HTTP get requests and HTTP post requests, you should have some knowledge about HTML forms.

HTML forms provide a simple and reliable user interface to collect data from the user and transmit the data to a servlet or other server side programs for processing. You might have seen HTML forms while using search engine visiting online book stores, tracking stocks on the web, getting information about availability of train tickets etc.

In order to construct a HTML form the following HTML tags are generally used .

• <FORM ACTION = “url” METHOD = “method”></FORM>

This tag defines the form body. It contains two attributes action and method. The action attribute specifies the address of the server program (i.e. servlet or JSP page) that will process the form data when the form is submitted. The method attribute can be either GET or POST, it indicates the type of HTTP request sent to the server. If the Method attribute is set to GET, the form data will be appended to the end of the specified URL after the question mark. If it is set to POST, then the form data will be sent after the HTTP request headers and a blank line.

•  <INPUT TYPE = “type” NAME = “name” >………… </INPUT>

This tag creates an input field. The type attribute specifies the input type. Possible types are text for single line text field, radio for radio button, checkbox for a check box ,textarea for multiple line text field, password for password field, submit for submit button ,reset for reset button etc. The name attribute gives a formal name for the attribute. This name attribute is used by the servlet program to retrieve its associated value. The names of radio buttons in a group must be identical.

• <SELECT NAME = “name” SIZE =” size”>…….. </SELECT>

This tag defines a combobox or a list. The NAME attribute gives it a formal name. The SIZE attribute specifies the number of rows in the list.

• <OPTION SELECTED= “selected” VALUE = “value”>

This tag defines a list of choices within the <SELECT> and </SELECT> tag. The value attribute gives the value to be transmitted with the name of the select menu if the current position is selected. The selected attribute specifies the particular menu item shown is selected, when the page is loaded.

           user registration form

                 The Fig. shows a user registration form

HANDLING FORM DATA USING HTTP GET REQUEST

In order to handle form data using HTTP GET request, we first create a user registration form as shown earlier and a servlet that will handle HTTP GET request. The servlet is invoked when the user enters the data in the form and clicks the submit button. The servlet obtains all the information entered by the user in the form and displays it.

The coding for user-registration form (c:\Tomcat6\webApps\examples) is as follows,

<html>
   <head>
      <title> User Registration Form </title>    
   </head>
   <body>
      <h2 align=”center”> User Registration Form </h2>
      <form method =”get” action =”/examples/servlet/DisplayUserInfo”>
       <p align=”center”> First Name :<input type=”text” name=”fname”/>                              
          <p align=”center”> Last Name : <input type=”text” name=”lname”/>
          <p align=”center”> Email Id : <input type=”text” name=”emailid”/>
          <p align=”center”> <input type="submit" value="submit" />
          <input type="reset" value="Reset" />
          </p>
      </form>
   </body>
</html>

In the given html code, notice that the Method attribute of the FORM tag is set to GET, which indicates that the HTTP GET request is sent to the server. The ACTION attribute of the FORM tag is set to/examples/servlet/DisplayUserInfo which identifies the address of the servlet that will process the HTTP GET request. The code for the DisplayUserInfo. java is as follows,.

import java.io.*; 
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayUserInfo extends HttpServlet
{
     public void doGet (HttpServletRequest request, HttpServletResponse
     response) throws ServletException, IOException
     {
          response.setContentType (“text/html”);
          PrintWriter out =response.getWriter ();   
          String fname = request.getParameter (“fname”);
          String lname = request.getParameter (“lname”);
          String emailid = request.getParameter (“emailid”);
          out.println (“You have entered:<br>”)
          out.println (“First Name ……”+fname);
          out.println (“<br> Last Name ……”+lname);
          out.println (“<br> Emailid ……”+emailid);
          out.println (“<h2> thanks for registration </h2> <hr>”);
          out.close ();
        }
}

In the above servlet code, our servlet class DisplayUserInfo extends HttpServlet class which is the most likely class that all the servlets will extend when you create servlets in web application. We override doGet () method as it has to process HTTP GET request. This method takes an HttpServletRequest object that encapsulates the information contained in the request and HTTPServletResponse object that encapsulates the information contained in the response. Our implementation of doGet () method performs two tasks:

• To extract the form parameters from HTTP request.

• To generate the response.

We call the getParameter () method of HTTP servlet request to get the value of a form parameter. If the parameter does not exist, this method returns null. It returns an empty string if an empty value is passed to the servlet. The rest of the statements in the servlet are similar to the ones we have already discussed in SimpleServlet.java.

NOTE: The parameter name specified in the getParameter () method must match to the one that is specified in HTML source code. Also, the parameter names are case sensitive.

Now compile and save the servlet program in the C:\Tomcat6\webapps\examples\WEB-INF\classes directory. After this, open your web browser and type the following URL

https://ecomputernotes.com:8080/servletApp/User_reg.html

To load user_reg. html in the web browser. As a result, the following webpage will be displayed.

             

Enter the firstname, lastname and email id and click on the Submit button. As a result, SimpleServlet.java servlet will be invoked. When you click the Submit but ton, the values you entered in the form are passed as name-value pars in a GET request. This form data will be appended to the end of the specified URL after the question mark as shown

Address: http:localhost:8080/examples/servlet/DisplayUserInfo? fname =Daljeet & lname=Singh & [email protected]

it is clear that name-value pairs are passed with the name and value separated by ‘=’. If there is more than one name-value pair, each pair is separated by ampersand (&).

When the servlet SimpleServlet.java receives the request, it extracts the fname, lname and email parameters from the HTTP request using the getParameter () method of the HttpServletRequest interface. The statement,

String fname = request.getParameter (“fname”);

will extract the parameter named fname in the <FORM> tag of the user-reg.html file and store it in request object. Similarly, we extract the lname and email parameters.

After processing the request, the servlet displays the form data along with an appropriate message.

When the user enter the data in the form displayed in the web browser and click the Submit button, then as in case of get () method, the servlet obtains all the information entered by the user in the form and displays it. But unlike the get () method, the values entered are not appended to the requested URL rather the form data will be sent after the HTTP request headers and a blank line.

The output displayed will be as follows,

               

Mysql LCASE() Function Example Using Java Servlet

By Dinesh Thakur

The function name ‘LCASE’ is used to convert the content or strings in lower case of Column value’s.

Firstly we need to make a table named ’emp’ into a database named ‘dbase’. And after that we have to call the java Packages from java library. now to define a class named ‘JavaServletLCASE’ which is been extend ‘HttpServlet’. and we need to be load the driver for database calling.To getting request we need to define serviceMethod().for whole procedure to produce output need to define some mandatory variables like connection (for making link between frontEnd and BackEnd).Resultset which represents the output table of data resulted from a SELECT query. preparedStatement the object of this statement will use to execute the query like executeQuery() it will return the object to resultset for produced output.preparedStatement will execute written query (Select job,LCASE(job) from emp).at the last step we need to call the doGet() for getting request output on a web browser.

To present Output in Impressive look we use tabular form with the help of ‘HTML’ tags this will show output in table form.

 
Example :
 
JavaServletLCASE.java
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JavaServletLCASE extends HttpServlet
      {
           public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
              {
                 rp.setContentType("text/html");
                 PrintWriter disp = rp.getWriter();
                 String driver = "com.mysql.jdbc.Driver";
                 String url = "jdbc:mysql://localhost/dbase";
                 String uid = "root";
                 String psw = "root";
                 Connection con=null;
                 PreparedStatement ps = null;
                 ResultSet rs;
                 try
                    {
                       Class.forName(driver);
                       con = DriverManager.getConnection(url,uid,psw);
                       ps=con.prepareStatement("Select job,LCASE(job) as UC from emp");
                       rs = ps.executeQuery();
                                String title = "Employee's Job in Lower Case";
                      String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
                        disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                      "<body bgcolor=\"#f4efef\">\n" + "<h3 align=\"center\">" + title + "</h3>\n" + "<ul>\n" +
                                          "<table width=\"20%\" border=\"1\" align=\"center\">\n" + "</body> </html>");
                     while(rs.next())
                        {
                           String jb = rs.getString("UC");
                                     disp.println("<tr><td align=\"center\">"+ jb +          "</td></tr>" );   
                       }     
                            }     
                                    catch(Exception e) 
                                               {
                                                  e.printStackTrace();
                                               }
                                                        disp.close();
             }
                                  public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                   {
                                                 doGet(rq,rp);
                                   }
      }
 
web.xml
 
<servlet>
   <servlet-name>JavaServletLCASE </servlet-name>
   <servlet-class>JavaServletLCASE </servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>JavaServletLCASE</servlet-name>
   <url-pattern>/JavaServletLCASE </url-pattern>
</servlet-mapping>

in operator in mysql Java Servlet example

By Dinesh Thakur

To check a value within a set IN operator is used.

We need to make a table named ‘inq’ into a databse named ‘dbase’. the required fields must be filled with values. After that some kind of packages to be called from java library to catch up java admiration. Here we need to define a class named ‘JavaServletINQuery’ extends the ‘HttpServlet’. this program is been responsible for desired output as required statement from user. here we use the service method()(this method is responsible for calling the doGet() method to getting the request). the variable which are mandatory to use link or present BackEnd and FrontEnd will have to be declared like Connection,ResultSet,preparedStatement all these variables does their required functions or job. like the connection variable will use to make Connection between databse and java code. the drivers are also to be load then created an object of Connection interface. after that preparedStatement will use to represent the Query for output like ‘SELECT emp_id, last_name, salary, manager_id FROM inq WHERE manager_id IN (403, 417, 425)’.the resultset will be define as executeQuery() to execute the query for desired result. and in the last we used doGet() method for fetching result on a web browser.

To see the result in tabular form we use ‘HTML’ tags for an attract looking Output on a web browser.

Example : 
JavaServletINQuery.java
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JavaServletINQuery extends HttpServlet
 {
      public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
        {
           rp.setContentType("text/html");
          PrintWriter disp = rp.getWriter();
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost/dbase";
          String uid = "root";
          String psw = "root";
         Connection con=null;
         PreparedStatement ps = null;
         ResultSet rs;
         try
           {
              Class.forName(driver);
              con = DriverManager.getConnection(url,uid,psw);
              ps=con.prepareStatement("SELECT emp_id, last_name, salary, manager_id FROM inq WHERE manager_id IN (403, 417, 425)");
              rs = ps.executeQuery();
                        String title = "Employee's Info With The Refrence Of Manager Id ";
              String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
                        disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
                         "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Employee Id</th><th>Last Name</th><th>Salary</th><th>Manager Id</th>\n"+ "</body> </html>");
               while(rs.next())
                {
                     int e_id = rs.getInt("emp_id");
                               String l_name = rs.getString("last_name");
                               int sal = rs.getInt("salary");
                                         int m_id= rs.getInt("manager_id");
                     disp.println("<tr><td align=\"center\">"+ e_id +"<td align=\"center\">" + l_name +  "<td align=\"center\">" + sal + 
                      "<td align=\"center\">" + m_id + "</td></tr>" );  
               }     
                    } 
                     catch(Exception e) 
                                          {
                                              e.printStackTrace();
                                          }
                                                disp.close();
    }
                                public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                  {
                                               doGet(rq,rp);
                                  }
 }
 
web.xml
 
<servlet>
   <servlet-name>JavaServletINQuery</servlet-name>
   <servlet-class>JavaServletINQuery</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>JavaServletINQuery</servlet-name>
   <url-pattern>/JavaServletINQuery </url-pattern>
</servlet-mapping>

MySql SELECT BETWEEN Query using Java servlet

By Dinesh Thakur

While using the between operator it must be remembered that both the values will be included in the range.

We have create a table named ‘inq’ in database named ‘dbase’. after that a class is been declared named ‘JavaServletInBeetweenQuery’ extends the ‘HttpServlet’. with that kind of efforts we need to define some methods which does their job for exporting output. after we just declare Service method()(service method does the job of calling doGet method for getting request). some variables also define as Connection,Resultset,PreparedStatement.Connection variable use to link between database and actual code(FrontEnd and BackEnd).preparedStatement will use to send the query to database like (SELECT last_name, salary FROM inq WHERE salary BETWEEN 12000 AND 20000). this statement will work according to condition it shows.now the next method executeQuery() will execute desired query and statement. and in the end doGet() method will be used to fetch the result on a web browser.

To feel look good the result we use a tabular form concept. for this kind of requirement we use  ‘HTML’ coding and a bit of tags to use Output in Designer look to show on a web browser.  

Example : 
 
JavaServletInBeetweenQuery.java
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JavaServletInBeetweenQuery extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
     {
         rp.setContentType("text/html");
        PrintWriter disp = rp.getWriter();
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost/dbase";
        String uid = "root";
        String psw = "root";
        Connection con=null;
        PreparedStatement ps = null;
        ResultSet rs;
        try
         {
             Class.forName(driver);
             con = DriverManager.getConnection(url,uid,psw);
              ps=con.prepareStatement("SELECT last_name, salary FROM inq WHERE salary BETWEEN 12000 AND 20000");
              rs = ps.executeQuery();
                      String title = "Employee's Info With The Refrence Of In Beetween Query ";
              String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
                      disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
              "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
                      "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Last Name</th><th>Salary</th>\n"+ "</body> </html>");
             while(rs.next())
            {
               String l_name = rs.getString("last_name");
                       int sal = rs.getInt("salary");
              disp.println("<tr><td align=\"center\">" + l_name +  "<td align=\"center\">" + sal +"</td></tr>" );  
            }     
               }  
                     catch(Exception e) 
                             {
                               e.printStackTrace();
                            }
                                      disp.close();
    }
                     public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                         {
                                doGet(rq,rp);
                         }
 }
 
web.xml
 
<servlet>
   <servlet-name>JavaServletInBeetweenQuery</servlet-name>
   <servlet-class>JavaServletInBeetweenQuery</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>JavaServletInBeetweenQuery</servlet-name>
   <url-pattern>/JavaServletInBeetweenQuery </url-pattern>
</servlet-mapping>

java mysql select column Example

By Dinesh Thakur

In order to see the data from the table the most common type of SQL statement executed in most database environments is the query, or SELECT statement. Select statements retrieval requests data from tables in a database. You can issue a simple SELECT statement that is designed to retrieve all data from the table.

The SELECT statement is the most commonly used statement in SQL and is used to retrieve information already stored in the database. To retrieve data, you can either select all the column values or name specific columns in the SELECT clause to retrieve data.

Syntax of SELECT statement
SELECT [distinct] <tablename.columname >
FROM <tablename >
[where <condition>]
[group by <columnname(s)>]
[having <condition>]
[order by <expression>] ;

 

The Function Denote The Query ‘Selected Column’ This Will Fetch Record From Table With Selected Columns According To User Requirments.

First we have To Make a Table Named ‘Dept’ In MySql (Php MyAdmin) Into The DataBase Named ‘dbase’. Then We have to call The Packages From java Library.Then We Make a Class Named ‘JavaMySqlSelectedCol’ Extends “HttpServlet”. After Initializing The Class We Declare The Methods Public void Service()(The service method call the doGet() method for a GET request from User) and In That The Objects called “Response Object” and “Request Object Which will Work According To Work. After that We have to Load the Driver and Make Variables Of Resultset, Connection to establish The link between database and Query that Execute The Condition after Calling.After Declaring The Prepared statement We have to put the Query “SELECT dept_id, location_id FROM dept”.In that Query We Will fetch the record of (Dept_Id,Location_id) From the table Department. After that We will Use executeQuery() Method to Extract the Result On a Web Browser.

Now in the Other Hand If we Need to Show Output In tabular Form For Impressive view. We just use The Code of ‘HTML’ Into Java Code After Declaring all the Imp. Code Lines.. In The Last With the Using of Method DoGet() Produce the result on A web Browser..  

Example : 
 
JavaMySqlSelectedCol.java
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JavaMySqlSelectedCol extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
    {
     rp.setContentType("text/html");
     PrintWriter disp = rp.getWriter();
     String driver = "com.mysql.jdbc.Driver";
     String url = "jdbc:mysql://localhost/dbase";
     String uid = "root";
     String psw = "root";
     Connection con=null;
     PreparedStatement ps = null;
     ResultSet rs;
     try
      {
        Class.forName(driver);
        con = DriverManager.getConnection(url,uid,psw);
        ps=con.prepareStatement("SELECT dept_id, location_id FROM dept");
        rs = ps.executeQuery();
                  String title = "Employee's Data With Selective Coloumns";
        String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f4efef\">\n" + "<h3 align=\"center\">" + title + "</h3>\n" + "<ul>\n" +
                            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Department Id</th><th>Location Id</th>\n"+ "</body> </html>");
        while(rs.next())
           {
             String d_id = rs.getString("dept_id");
                                           String l_id = rs.getString("location_id");
                       disp.println("<tr><td align=\"center\">"+ d_id +"<td align=\"center\">" + l_id +"</td></tr>" );        
           }     
               }      
                          catch(Exception e) 
                                     {
                                       e.printStackTrace();
                                     }
                                             disp.close();
            }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                                     doGet(rq,rp);
                           }
}
 
web.xml
 
<servlet>
   <servlet-name>JavaMySqlSelectedCol</servlet-name>
   <servlet-class>JavaMySqlSelectedCol</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>JavaMySqlSelectedCol</servlet-name>
   <url-pattern>/JavaMySqlSelectedCol</url-pattern>
</servlet-mapping>

Html to Servlet Communication

By Dinesh Thakur

A web resource application is a combination of static as well as dynamic web resource programs, images, etc. A static web resource resides in server and is executed in client side web browser, e.g., HTML. A dynamic web resource program resides in server, is executed in context of server and gives response back to the client, e.g., servlet, JSP. In web application, static web resource takes data from client side and takes it to the dynamic web resource as per request. The dynamic web resource processes the data and sends the response back to client in the form of response. [Read more…] about Html to Servlet Communication

What happens when our servlet program gets first or Other than First Request from browser window?

By Dinesh Thakur

1. Servlet container loads our servlet class from WEB-INF\classes folder of deployed web application.

2. Servlet container instantiates (object creation) our servlet class object as Class.forName (“FolderName”).newInstance (); 

             Class.forName (“FolderName”)      // loads our servlet class   

             newInstance ()       // creates object for the loaded class DateSrv    

3. During instantiation process the 0-param constructor of our servlet class executes.

4. Servlet container creates one servlet config object for our servlet class object.

5. Servlet container calls init (-) life cycle method having servlet config object as argument value on our servlet class object.               

Note: 1 to 5 steps completes instantiation and initialization on our servlet class object.

6. Servlet container calls next life cycle method service (-,-) on our servlet class object. This will process the request and generated response goes to browser window as web page through web server.

Other than First Request

 Servlet container checks the availability of our servlet class object.

1. If available, servlet container calls service (-,-) (public) on existing object of our servlet class to process the request and this response goes to browser window.

2. If not available, servlet container performs all operations of first request.

What is the Servlet container raises the life cycle events in servlet program?

By Dinesh Thakur

* Every software and non-software objects life cycle (considering all the operations that are taken place from object birth to object death)

* Our servlet class object life cycle will be managed by servlet container

* Event is an action performed/raised on the object  

                                                                                                                                     

  • Servlet container raises the following life cycle events in the life cycle of our servlet program. They are:
  1. Instantiation Event (raises when servlet container creates our servlet class object)
  2. RequestArrival Event (raises when servlet container takes the browser window generated request)
  3. Destruction Event (raises when servlet container is about to destroy our servlet class object)

When container raises these events on our servlet class object it looks to call certain methods automatically so these methods are called as life cycle methods or container callback methods. They are:

init (ServletConfig cg)

Service (ServletRequest req, ServletResponse res)

Destroy ()

Prototype of servlet life cycle methods

Public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException

Public void init (ServletConfig cg) throws ServletException

Public void destroy ()

* For one life cycle event only one life cycle method will be called by servlet container so init (), service (HttpServletRequest, HttpServletResponse), doXxx () methods are not life cycle methods.

* Servlet container calls init (-) life cycle method for instantiation event.                               

* Servlet container calls service (-,-) life cycle method for RequestArrival event.

* Servlet container calls destroy () life cycle method for destruction event

* The method that is called by underlying container automatically based on the event that is raised on the object is called container callback methods.

* Programmer never calls life cycle methods manually; they will be called by underlying container automatically.

* Servlet API as supplied life cycle methods:

  1. To allow programmer to place his choice logics in the execution of servlet programs.
  2. To supply servlet container created objects to servlet program (also for programmers as parameters of life cycle methods) (like request object, response object, ServletConfig object and etc)

* While overriding super class method in subclass, the method can have same modifier or access modifier

* While overriding protected service () method of predefined HttpServlet class in its subclass we can take either protected or public modifiers for that method.

Public class TestSrc extends HttpServlet

{

      Public void service (here protected method is overridden) (HttpServletRequest,   HttpServletResponse) throws ServletException, IOException

    {

        _______

        _______

        ­­­­_______

    }

}

Service () method-1

Public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException

Service () method-2

Protected void service (HttpServletRequest,   HttpServletResponse) throws ServletException, IOException

* Servlet container is responsible to raise various life cycle events on our servlet class objects so logics placed in life cycle methods are not responsible to raise these events but they are responsible to process these events by executing programmers supplied logic.

Example:- Code which is written in init () life cycle method never creates our servlet class object but programmer places this code as instantiation logic to execute for instantiation event raised by servlet container by creating our servlet class object.

* Life cycle method and its logic are not capable of raising life cycle events on the object but when underlying container raises life cycle events on the objects it automatically calls a relevant life cycle methods.

How to instruct browser window for not storing the output in the buffer?

By Dinesh Thakur

By default every web resource program generated output/response content will be stored in the buffer before it is getting displayed on browser window as web page content. Due to this browser window may show old output collected from the buffer even though the web resource program of web application is capable of generating new and updated output.   

                                                    

* To solve the above problem instruct browser window for not storing the output in the buffer from web resource program through web server by using response headers as shown below.

res. setHeader (“cache-control”, “no-cache”); //for http 1.1 based servers

res. setHeader (“pragma”, “no-cache”); //for http 1.0 based servers

* Buffer is a temporary memory which stores the data for temporary period. Buffer is also called as cache.

Response Status Code in Servlet.

By Dinesh Thakur

* Response status code indicates the status of generated response to display on the browser window.

* Every generated http response contains one http status code, default status code is 200.

* If web resource program generates warnings based web page then the status code is 100-199.   

* If web resource program generates successful web page then the status code is 200-299.

* If request given to one web site is forwarded to another web site then the status code will be 300-399.

* If our web resource program is incomplete or invalid to process the request then the status code will be 400-499.

* If server fails to execute our web application the status code will be 500-599.     

* 400-599 are error status codes, Using them the programmer can debug the problems related       to web application execution and server.

* 100-399 indicates success response status codes that means they display web pages on browser window having output content. So these status codes will not appear on the web pages.

* For related information on http response status codes refer page no 49 and 50.      

* Response headers provide instructions to browser window through web server towards displaying web pages on the browser window.

* The content type we have placed in PW.println statements becomes response body http response.

How to gather miscellaneous information from HttpRequest

By Dinesh Thakur

We can gather the miscellaneous information from HttpRequest by calling various getxxx methods on request object as shown below. [Read more…] about How to gather miscellaneous information from HttpRequest

How many ways we can develop a servlet?

By Dinesh Thakur

The three important resources of servlet API.

1. javax.servlet.Servlet

2. javax.servlet.GenericServlet      (Abstract class)

3. javax.servlet.http.httpServlet    (Abstract class)

• In Java an abstract class can contain only abstract methods or only concrete methods or mix of both.

• The above give predefined HttpServlet class is an abstract class containing no abstract methods.

• If you want to make methods / logics of one java class accessible only through subclass the make that class as abstract class even though that class contains only concrete methods.

              servlet method inheritance

• Every servlet program is a java class that is developed based on servlet api. There are three ways to develop servlet program.

1. Take a java class implementing javax.servlet.Servlet interface and provide implementation for all the five methods of that interface.

2. Take java class extending from javax.servlet.GenericServlet class and provide implementation for service() method.

3. Take java class extending from javax.servlet.http.httpServlet class and override one of the seven doxxx() methods or one of the two service(- -) methods.

• In the above said three approaches the overridden / implemented service (-,-) / doxxx(-) programmer places request processing logic that generates web pages by processing the request. But programmer never calls these methods manually but servlet container calls these methods automatically for every request given by client to servlet program.

• Programmer just supplies his servlet program related java class to servlet container then onwards servlet container is responsible to manage the whole life cycle of servlet program. (From object birth to death every operation will be take care by container).

• For all the request given to servlet program the servlet container creates one object but for every request given to servlet program, the servlet container create one separate request, response objects and calls service(-,-) method by keeping these requests, response objects as argument values.

                Servlet Object

• Servlet program uses request object to read details from the request.

• Servlet program uses response object to send response content to browser window through web server.

• When 10 requests are given to a servlet program from single or different browser windows (clients)

• Servlet container creates 10 threads on servlet program objects representing 10 requests.

• Servlet container creates 10 sets of request, response objects and calls service (-,-) or methods for 10 times having request, response objects as arguments values.

• To make our servlet program java class visible to servlet container the java class must be taken as public class.

 

The javax.servlet.Servlet Interface

 

The javax.servlet.Servlet interface is the basic interface of the Java Servlet API. This provides a standard abstraction for the servlet container to understand the Servlet object created by the user. That means the interface is designed to describe the user-defined Java object to the Servlet container, which encapsulates the application logic to plug into the servlet container for processing the client request. The servlet object must be a subtype of the interface to be managed by the servlet container. The following are the five methods declared in this interface:

 

1. public abstract void init(ServletConfig)

 

2. public abstract void service (Service Request, Service Response) throws servlet Exception, IO Exception

 

3. public abstract void destroy()

 

4. public abstract void ServletConfiggetServletConfig()

 

5. public abstract String getServletlnfo()

 

The javax.servlet.GenericServlet Class

 

The GenericServlet class implements the servlet interface and, for convenience, the ServletConfig interface. Servlet develops typically subclass GenericServlet, or its descendent HttpServlet, unless the servlet needs another class as a parent. (If a servlet does need to subclass another class, the servlet must implement the Servlet interface directly. This would be necessary when, for example, RMI or CORBA objects act as servlets.)

 

The GenericServlet class was created to make writing servlets easier. It provides simple versions of the life-cycle and ini t destroy methods, and of the methods in the ServletConfig interface. It also provides a log method, from the ServletContext interface. The servlet writer must override only the service method, which is abstract. Though not required, the servlet implementer should also override the getServletInfo method, and will want to specialize the ini t and destroy methods if expensive servlet-wide resources are to be managed. The following are the methods residing in GenericServlet class.

 

• public void destroy()

 

• public String getlnitParameter(String name)

 

• public Enumeration getlnitParameterNames()

 

• public ServletConfiggetServletConfig()

 

• public ServletContextgetServletContext()

 

• public String getServletlnfo()

 

• public void init(ServletConfigconfig) throws ServletException

 

• public void init() throws ServletException

 

• public void log (Exception e,Stringmsg)

 

• public void log (String message,Throwable t)

 

• public abstract· void service (ServletRequest req, ServletResponse res)

 

throw Servlet Exception, IOException

 

The javax.servlet.http.HttpServlet Class

 

It is an abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. Because it is an abstract class, servlet writers must subclass it and override at least one method. The methods normally overridden are;

 

• doGet, if HTTP GET requests are supported. Overriding the doGet method automatically also provides support for the HEAD and conditional GET operations. Where practical, the getLastModified method should also be overridden, to facilitate caching the HTTP response data. This improves performance by enabling smarter conditional GET support.

 

• doPost, if HTTP POST requests are supported.

 

• doPut, if HTTP PUT requests are supported.

 

• doDelete, if HTTP DELETE requests are supported.

 

• life cycle methods-in it and destroy, if the servlet writer needs to manage resources that are held for the lifetime of the servlet. Servlets that do not manage resources do not need to specialize these methods.

 

• getServletInfo, To provide descriptive information through a service’s administrative interfaces.

 

Notice that the service method is not typically overridden. The service method, as provided, supports standard HTTP requests by dispatching them to appropriate methods, such as the methods listed above that have the prefix “do”, In addition, the service method also supports the HTTP1.l protocol’s TRACE and OPTIONS methods by dispatching to the doTrace and doOptions methods. The doTrace and doOptions methods are not typically overridden.

 

Servlets typically run inside multi-threaded servers; servlets must be written to handle multiple service requests simultaneously. It is the servlet writer’s responsibility to synchronize access to any shared resources. Such resources include in-memory data such as instance or class variables of the servlet, as well as external components such as files, database and network connections.

Difference between Process and Thread Based Server Side Technology

By Dinesh Thakur

Process based Server Side Technology

• The procedure of transferring control from one process to another process or from one thread to another thread is called as the scheduling based control jumping or context switching.

• Since operating system process are heavy weight process so they take lot of time for control jumping or context switching.

• Due to this when more requests are given CGI based web application more operating system processes will be created on one per request basis and performance of website will be degraded (That means web application becomes non scalable web application).

• If application is giving same performance irrespective of increase or decrease in number of clients / no. of requests is called as scalable application.

           Process based Server Side Technology

Thread based Server Side Technology

Operating System managed process P1 representing the web server startup t1,t2,t3,t4 core threads started on servlet program related object representing request given by clients.

           Thread based Server Side Technology

• The control jumping between threads of a process takes very much less time when compare to control jumping between to separate processes, so we can say thread based server side technology gives better performance when compare to process based server side technologies.

• The web application that is developed based on thread based server side technologies is scalable application.

• servlet program is a single instance multiple threads based java component of java web application as shown above, that means if 100 request are give to single servlet program then the servlet container create only one object for that servlet program class but starts 100 threads on that object representing 100 request as shown above.

Configuration of Tomcat

By Dinesh Thakur

Apache Tomcat is a Open source java based web server software. At present tomcat 7.0 is compatible with jdk1.6/1.7. Tomcat default port no is 8080(changeable).To download tomcat we use www.apache.org.

To install tomcat 6.0 software use apache/ tomat6.0.26 setup file and use can change the default port no, default username and password details during installation. If not changed default port no is “8080”, default username is “admin” default password is “admin”.

Every software installed in a computer will reside in a logical position called software port and every software port will be identified with its port no(communication end point).

After installing tomcat you will get the following folders and files in the installing folder.

                      tomcat directory structure

• To installation folder of tomcat is called as <tomcat_home>

• To start tomcat server use<tomcat_home>/bin/tomcat6.exe file

• To launch home page of tomcat the procedure is

• Open browser windows the type https://ecomputernotes.com:8080 in address bar.

Procedure to change port no. of tomcat server after installation:

• Goto <tomcat_home>/conf/server.xml file modify port attribute value of first <connector> tag then restart the server.

• The browser window keeps every web page in the buffer before display it for end user.

• A buffer is a temporary memory which can hold the data for temporary period.

• While giving new port no to any software service use 1025 to 65535 range numbers because 1 to 1024 range numbers are busy for with OS services.

• Programmer can supply java web application to tomcat server either in the form of directory or war file.

• Programmer uses <tomcat_home>/webApps folder to display web applications.

Architecture of Java Based web Server

By Dinesh Thakur

• Once web server is started one daemon process will be started to listen to clients continuously and to trap and take the client generated Http request.

• The process that runs continuously is called as daemon process.

• Every java application contains two default threads.

   1. Main threads

   2. Garbage collector threads (daemon thread).

• JSP container is the enhancement of servlet container and both containers use JRE/JVM supplied by web server.

• Middle ware services are configurable additional services on the application to make applications executing perfectly in all the situations.

• Security middle ware service protects the application from unauthorized and unauthenticated users.

            Architecture of Java Based web Server

• Transaction Management service executes the logics by applying do everything or nothing principle.

• JDBC connection pool supplies set of ready available JDBC Connection objects.

• Logging service keeps track of the application execution process through conformation statements / messages / log messages.

• Middle ware services are not minimum logics of application development. they are additional or optional services to apply on applications.

• A web application can be there with or without middle ware services.

• Web server automatically activates servlet container and JSP container to execute servlet, JSP programs when they are requested by clients.

• The client side web resource programs of web application goes to browser window for execution whereas the server side programs will be executed by using the containers of web server.

• In web application executing environment browser software is called as client software and web server software is called as server software.

Responsibilities of Web Server

By Dinesh Thakur

• Listens to client request continuously (HTTP Request).

• Traps and takes client generated HTTP Request.

• Passes the HTTP request to an appropriate web resource program of web application (deployed web application).

• provides container software to execute server side programs (web resource programs)

• Gathers output generated by web resource programs.

• Passes output of web resource programs to browser window as http response in the form of web page.

• Provide environment to deploy manage and to undeploy the web application.

• Gives middle ware services and etc.

• A container is a software or software application that can manage the whole life cycle (Object birth to death) of given resource.(like java classes).

• A file or program is called as resource of the application.

• Servlet container takes care of servlet program life cycle.

• JSP container takes care of JSP program lifecycle.

• Applet container (applet viewer) takes care of applet program lifecycle.

• Servlet container, JSP containers are part of web server (java based).

• Container is like a aquarium who can take care of the whole life cycle of given resources called fishes.

• Programmer is not responsible to develop containers and web servers but he is responsible to use them to execute web application.

What is the difference between HttpRequestHeaders and Request Parameters?

By Dinesh Thakur

Both are send input values to target web resource program like servlet program along with the request. The difference are

Http Request Headers

Request Parameters

Holds the browser supplied input values.

Holds the visitor (end user) supplied input values. (from data)

Headers names are fixed but the values are browser specified.

Parameters names and values are user-defined.

Mandatory in every request.

Optional.

Headers names are unique.

Duplicate names are allowed.

Example:- User-agent:

                  Accept:

                  and etc.

Example:- sno=101 & sname=thakur

List of http request headers:

Http Header

Header Values

Accept-Encoding

gzip,deflate

Cookie

ISESSIONID=f73d57hfdn98789654ff8

Connection

keep-alive

Host

Localhost:8080

Referrer

http:// Localhost:8080/project/test

User-agent                   

Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0

If-Modified-since        

Date: Fri, 05 Feb 2014 16:11:54 GMT

Authorization

Authorization: Basic PWxhsdGRpnnjpncGVuIHNlc2FtZQ==

Accept-charset and etc…….

Accept-Charset: utf-8

To gather various details from client generate request being from Servlet program we need to use either ServletRequest object (or) httpServletRequest object. Using httpServletRequest object we can gather all the details from request. Using ServletRequest object we can gather only few details that mean we can’t gather details like header values & some miscellaneous info.  

 1. Different approaches of gathering request parameter values being servlet programs:

Use either ServletRequest object/HttpServletRequest object.

Example request url:

 

https://ecomputernotes.com:8080/project/test1?sno=101 & fname=dinesh & lname=thakur

Approach 1:

String s1=req.getParameter(“sno”); //gives 101

String s2=req.getParameter(“fname”); //gives dinesh

String s3=req.getParameter(“lname”); //gives thakur

Note: 1. we must know parameter name in order to get its value.

          2. If parameter contains multiple values then it gives only one value. (1st value)

Approach 2:              

Enumeration e = request.getParameterNames();

while (e.hasMoreElements()

{

String Pname=(String) e.nextElement();

String Pval=req.getParameter (Pname);

PW.println (Pname +”            ” +Pval);             

}

Approach 3:

String S[]= req.getParameterValues (“sname”);     // (holds dinesh, sandeep as element values)                                       

String S1 = req.getParameterValues (“sname”) [0]; //gives dinesh                                          

String S2 = req.getParameterValues (“sname”) [1]; //gives sandeep

Note:-  This is useful for gather the multiple values of each request parameter.


 If you give any request code then you must write in service (-,-)                                           


2. Different approaches of reading request headers values being from Servlet program:

We must use HttpServletRequest object for this

Approach 1:

String S1=req.getHeader (“user-agent”); //gives browser software name    

String S1=req.getHeader (“accept-language”); //gives en-us

Note: Here we must know header name to get its value. 

 

Approach 2:    

    

Enumeration e=req.getHeaderNames();  

while (e.hasMoreElements())                    

{

  String hname= (String) e.nextElement(); //gives each header name

  String hval=req.getHeader(hname); //gives each header value

  PW.println(hname+”               “ +hval);

}

                                               

Gives all the request heard names and values.

Using browser settings we can change certain header values.

Header values will change based on the browser software we use.

*** We can change accept-language value through browser setting.

Servlets Client HTTP Request

By Dinesh Thakur

• The text that allows non-sequential access through hyper link is called as “hyper text”.

• Protocol http defines set of rules that are required to pass hyper text between browser to server and server to browser.

• Http is application level protocol that runs over network level protocol TCP/IP.

• HTTP is a application level protocol that runs over network level protocol called TCP/IP having set of rules to get communication between browser window and web server.
• Application level protocols defines set of rules that are required to get communication between two softwares or software applications.
Ex. HTTP, JDBC:ODBC, JDBC:Oracle, SMTP and etc…
• Network level protocol defines set of rules to get communication between two physical computers of network.
Ex. TCP/IP

• When browser window generates request to web application the request contains multiple details given by browser window. We can remember this details h2p2 details.

Request URL:

https://ecomputernotes.com:2020/project/test1?sno=101 & sname=thakur (query string)

h2p2 details:

 

H

http request method (GET/POST/…..)

H

http request headers (user-agent, accept language,  …..)

P

path of the requested web resource program (project/test1)

P

request parameters (query string) (s no=101 & s name=thakur)

Generating http request with above set details is the responsibility of browser window.

Block diagram of http request:

                 http request

An example of http request:

                 HTTP basic

How Servlet handling multiple post Requests

By Dinesh Thakur

When four requests are given to a Servlet program.

a) The Servlet container creates one object of that Servlet class.

b) Servlet container starts 4 threads on that object representing 4 requests on per request basis.

c) Servlet container creates 4 sets of request, response objects on one set per each request. (if any change is occur recompile, reload.)

                     Multiple Request

Every thread can be identified through its “thread name”. Every object can be identified with its unique number called “Hashcode”. To get the Hashcode of any object call Hashcode() of an that object.

Can we place only parameterized constructor in our Servlet class?

By Dinesh Thakur

No, Because Servlet container uses 0-param constructor of our Servlet class that create the object of our Servlet class. If 0-param constructor (default constructor) not available then the Servlet container throws: java.lang.InstantiationException.

Note: If there are no constructors in java class then compiler generates 0-param constructor in that class as default constructor during compilation. Otherwise this default constructor will not be generated.

Servlets First Examples

By Dinesh Thakur

Once the Tomcat is installed and configured, you need to perform the following steps to create and run a servlet.

1. Create a directory structure under Tomcat for your application

2. Write the servlet source code

3. Compile your servlet source code

4. Run the Servlet

Creating the Application Directory

When you install Tomcat, several sub directories are automatically created under the Tomcat home directory (in our case c: \ Tomcat6). One of the subdirectory is ‘webApps’ in which you store your web applications. A web application is a collection of web resources such as servlets, html pages, images, multimedia contents, Java Server Pages, XML configuration files, Java support classes and Java support libraries.

A web application has a well-known directory structure in which all the files that are part of the application reside. The web application directory contains a context root – the top level directory for the entire web application. All the servlets, HTML documents, JSPs and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the web application creator and is placed under ‘webApps’ directory. In our case, we create a context root directory named servletApp. Note that this directory name is important as it appears in the URL while accessing the servlet. A separate context root directory is dedicated to each servlet application.

Under the context root directory servletApp, create the src and WEB-INF directories. The src directory is for source files. The WEB-INF directory contains the resources that are not to be directly downloaded to the client (browser). Under the WEB-INF directory, create classes and lib directory. In the classes directory, you place serv1et class files and other utility classes used in a web application. If the classes are part of a package, the complete package directory structure would begin here. In the lib directory, you place Java achieve (JAR) files. The JAR files can contain servlet class files and other supporting class files used in web application.

If you have html files, you put them directly under servletApp directory. All your image files should be placed in the images directory under servletApp directory.

For convience, we are using examples directory under webApps directory for explaining various examples.

Write the Servlet Source Code

To write the servlet, perform the following steps:

1. Open a text editor such as MS-Notepad to edit a new file. Save this file in the working directory (in our case c: \javaprog\).

2. Enter the servlet import statements to include the appropriate packages. Most servlets need access to atleast three packages – javax.servlet, java.servlet.http and java.io. So when you create servlet source code, you start with the following import statements.

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

 

 

 

 

 

 

In addition, you may need additional import statements depending on what other processing your servlet does.

3. Extend the genericServlet class: Since all servlets are required to implement the javax.servlet. Servlet interface and the GenericServlet class provide an implementation of this interface, so our class should extend GenericServlet class.

After the import statements, type class declaration as follows.

public class SimpleServlet extends GenericServlet
{
      …………………………………………………
}

 

 

 

 

 

 

 

The SimpleServlet class extends the GenericServlet class of javax.servlet package. The GenericServlet class provides functionality that makes it easy to handle requests and responses.

4. Write the required servlet methods: After the SimpleServlet class declaration, override the service () method which is inherited from GenericServlet class. Inside service () method, the request is handled and appropriate response is returned. Information about the request is available through a ServletRequest object and the response is returned via a ServletResponse object. Since the service () method can throw two exceptions (javax.servlet. ServletException and java.io.IOException), so you must throw them in the method declaration.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleServlet extend GenericServlet
{
     public void service (ServletRequest request, ServletResponse response)
     throw ServletException, IOException
    {
         .........................
    }
         .........................
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5. Get the request information (if any) and generate the appropriate response: In this step, we will write the code that displays a message Welcome to Servlet on the client’s web browser when the browser issues a request to the servlet.

The source code for SimpleServlet.java is as follows,

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimpleServlet extends GenericServlet
 {
   public void service (ServletRequest request, ServletResponse response) throws     IOException, ServletException
    {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<b>Welcome to Servlet</b>");
      out.close();
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The first line of the code in the service () method

response.setContentType(“text/html”);

sets the content type for the response. The client’s browser uses this information to know how to treat the response data. Since we are generating HTML output, the content type is being set to text/html”.

Then the statement,

printWriter out = response.getWriter();

calls the getWriter () method that returns a PrintWriter object (out)for sending character text in the response. Finally, printIn () method of the PrintWriter object is used to write the servlet response (Welcome to Servlet in bold form).

Now edit the web.xml file

<servlet> 
   <servlet-name>SimpleServlet </servlet-name>
   <servlet-class>SimpleServlet </servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>SimpleServlet </servlet-name>
   <url-pattern>/SimpleServlet </url-pattern>
</servlet-mapping>

 

 

 

 

 

 

 

 

Compile Your Source Code

In this step, compile the servlet source code file C:\javaprog\SimpleServlet. java. For this, change the directory to your working directory, c: \javaprog and compile your file,

C:\javaprog>javac SimpleServlet.java

On successful compilation, SimpleServlet.class is created. Now copy this class file into the directory that Tomcat uses

C:\Tomcat6\webApps\examples\WEB-INF\classes

so as to run your servlet.

Run the Servlet

Before running the servlet, you need to start the Tomcat if it is not running. Now start a web browser and type

https://ecomputernotes.com:8080/examples/servlet/SimpleServlet

in the URL. The result will be shown as follows

Welcome to Servlet

What is Servlet Container?

By Dinesh Thakur

In Java, Servlet container (also known as aWeb container) generates dynamic web pages. So servlet container is the essential part of the web server that interacts with the java servlets. Servlet Container communicates between client Browsers and the servlets.

Servlet Container managing the life cycle of servlet. Servlet container loading the servlets into memory, initializing and invoking servlet methods and to destroy them. There are a lot of Servlet Containers like Jboss, Apache Tomcat, WebLogic etc.

How does this Servlet Container work?

Servlet Container

• A client browser accesses a Web server or HTTP server for a page.

• The Web server redirects the request to the servlet container (Servlets are HTTP listeners that run inside the servlet container).

• The servlet container redirects the request to the appropriate servlet.

• The servlet is dynamically retrieved and loaded into the address space of the container, if it is not in the container.

• The servlet container invokes servlet init () method once when the servlet is loaded first time for initialization.

• The servlet container invokes the service () methods of the servlet to process the HTTP request, i.e., read data in the request and formulate a response. The servlet remains in the container’s address space and can process other HTTP requests.

• Web servlet generates data (HTML page, picture …) return the dynamically generated results to the correct location.

Java Servlet Life Cycle

By Dinesh Thakur

Java Servlet life cycle consists of a series of events that begins when the Servlet container loads Servlet, and ends when the container is closed down Servlet. A servlet container is the part of a web server or an application server that controls a Servlet by managing its life cycle. Basically there are three phases of the life cycle.

First, the Servlet container loading Servlet in the memory, creating a servlet object and initializes it. Second, Servlet object services requests mapped it by the Servlet container. Thirdly Servlet container shuts down Servlet and Java Virtual Machine (JVM), which is the environment that runs Java applications, freeing the computer resources that the Servlet.

Three of the five methods defined by the Servlet interface — init (), service () and destroy () —‘s life cycle methods.

The init() method:

The Servlet container running a Servlet’s init () method, which initializes Servlet, once in the Servlet life cycle, after loading the Servlet and create a Servlet object. The init method definition looks like this:

public void init(ServletConfig config) throws ServletException {
  // Initialization code...
}

 

 

 

 

 

 

When instantiating the servlet container passes an argument to the init() method a ServletConfig object for loading specific configuration settings to the servlet.

If an error occurs upon calling the init () method, it throws an exception of type and ServletException servlet is not initialized.

The service () method

The container runs the Servlet service () method for each request from a client, a web browser. The service method definition looks like this:

public void service(ServletRequest request, 
                    ServletResponse response)
      throws ServletException, IOException{
}

 

 

 

 

 

 

 

 

The ServletRequest and ServletResponse objects are automatically passed as a parameter to the service () method by the container.

The destroy () method

The Servlet container running a servlet’s destroy () method once in a lifetime to close the Servlet. The destroy method definition looks like this:

public void destroy() { 
    // Finalization code...
  }

 

 

 

 

 

 

 

The destroy ( ) method waits until all threads started by the service () method before terminating the execution of the servlet.

Note– The init() and destroy() method only once called during its servlet life cycle.

Architecture Diagram of Servlet Life Cycle:

                     Architecture Diagram of Servlet Life Cycle

 

The servlet is loaded at server startup or when the first request. The servlet is instantiated by the server. The init ( ) method is invoked by the container. In the first application, the container creates specific Request and Response objects to the query.

The service () method is called for each request in a new thread. The Request and Response objects are passed as parameters. Through the Request object, the service () method will be able to analyze information from the client With the Response object, the service () method will provide a response to the client.

This method can be executed by multiple threads; there should be exclusion for the use of certain resources processes.

The destroy () method is called when unloading the servlet, that is to say when it is no longer required by the server. The servlet is then reported to the garbage collector.

Types of Servlets

By Dinesh Thakur

There is a possibility of developing ‘n’ types of servlets, like httpservlet, ftpservlet, smtpservlet etc. for all these protocol specific servlet classes GenericServlet is the common super class containing common properties and logics. So, GenericServlet is not a separate type of servlet.

As of now Servlet API is giving only one subclass to GenericServlet i.e HttpServlet class because all web servers are designed based on the protocol http.

                               Type of Servlet
Generic servlets extend javax.servlet.GenericServlet – It is protocol independent servlet. Generic Servlet is a base class servlet from which all other Servlets are derived. Generic Servlet supports for HTTP, FTP and SMTP protocols. It implements the Servlet and ServletConfig interface. It has only init() and destroy() method of ServletConfig interface in its life cycle. It also implements the log method of ServletContext interface.

HTTP servlets extend javax.servlet.HttpServlet – HTTPServlet is HTTP dependent servlet. The HTTP protocol is a set of rules that allows Web browsers and servers to communicate.  When Web browsers and servers support the HTTP protocol, Java-based web applications are dependent on HTTP Servlets.HttpServlet is Extended by Generic Servlet. It provides an abstract class for the developers for extend to create there own HTTP specific servlets.

Server side Web Technology

By Dinesh Thakur

Server side web technology is used to develop dynamic web resource programs that having the capability to generate dynamic web pages. Server side web technologies are two types.

1. Process based                

2. Thread based   

Process based Technologies are CGI and thread based technologies are Servlet, JSP, ASP.net.

A light weight sub process is called Thread. Operating system controls processes but threads can be controlled through java programming using JRE support.

Transferring control between two processes (or) between two threads is called as “Context switch” (or) “Control jumping” (or) “scheduling”. The scheduling on processes takes more time compare to the scheduling on threads.

Understanding CGI Environment:

Understanding CGI Environment

Since processes based scheduling takes more time, the CGI web applications performance will be degraded when multiple requests are given simultaneously. This makes the CGI web applications as non-scaleable web applications (If application gives good performance respective of increase (or) decrease in request count then that application is called as “Scaleable applications”).

Understanding Servlet/JSP Environment:

Understanding Servlet/JSP Environment

Since, scheduling on threads takes less time the above diagram based web application gives good performance in all situations. This makes web applications as “scaleable applications.” It is recommended to use thread based server side technologies in web application development for better performance.

Every servlet program is a “Single instance multiple threads component” that means when multiple requests are given to servlet program. The servlet container creates only one object for that servlet program class but multiple threads will be started on that object representing multiple request. As shown above diagram.

Servlet vs. other Technologies

By Dinesh Thakur

Client side programs can be written using different client side technologies. These are given to develop client side web resources such as html (Web), JavaScript (Netscape), VBScript (Microsoft), AJAX (asynchronous JavaScript and xml) programming languages.

Server side web resource programs can be written using different server-side web resource technologies, such as.

Technologies

Software license

Based

Servlets

Sun Microsystems (Oracle corp.)

Java

JSP

Sun Microsystems (Oracle corp.)

Java

PHP

Apache Foundation

Non-Java

Cold Fusion

Open Community

Java

ASP (Active Server Page)

Microsoft

Non-Java

ASP.Net             

Microsoft

Non-Java

SSJS (Server Side JavaScript)             

Netscape

Non-Java

The Web /Http server software that helps to deliver web content that can be accessed through the Internet. There are many Web/Http server software’s to serve different forms of data.

Software

Software license

Based

Tomcat

Apache

Java

Resin

Caucho Technology

Java

Jetty

Apache

Java

PWS (Personal web server)

Microsoft

Non-Java

Apache HTTP Server

Apache

Non-Java

IIS (Internet Information server)         

Microsoft

Non-Java

Oracle HTTP Server

Oracle

Non-free proprietary

Application Server that handles all app operations between users. With application Server, you can easily share business logic or database. There are many Application Server software’s to share business logic data. Application Server s/w is enhancement of web server s/w.

Software

Software license

WebLogic

Oracle

WebSphere

IBM

JBoss

Red Hat

GlassFish

Sun Microsystems

JRun

Macromedia

Oracle Application Server 10g

Oracle

Note:  All application server software’s are Java based server software’s.

Database application software used for storing, organizing and managing information, that application software interact with the user, applications, and the database itself to capture and analyze data. The Database software designed to allow the definition, creation, querying, update, and administration of databases. There is much database software such as.

Database

Software license

Oracle

Oracle

MS-Access           

Microsoft

Sybase

Open Community

DB2            

IBM

MySql

Sun Microsystems

SQL Server           

Microsoft

To develop& execute java based web application:

1. Choose any browser Software.

2. Choose one (or) more client side technologies to develop client-side web resource program.

3. Choose any database Software.

4. Choose java based web server/Application server.

5. Choose java based server side technologies. To develop server side web resource programs. (Servlet, JSP programs) 

 Procedure to develop and execute PHP based web application:

1. Choose any browser Software.

2. Choose one (or) more client side technologies to develop client-side web resource program.

3. Choose any database Software.

4. Use Apache web server.

5. Use PHP to develop server-side web resource programs.

What is SERVLET API?

By Dinesh Thakur

Before creating the first servlet, you need to understand the Servlet API and Tomcat Servlet container. The Servlet API provides interfaces and classes that are required to built servlets. These interfaces and classes are group into the following two packages :

• javax.servlet

• javax.servlet.http

One should remember that these packages are not part of Java core packages, instead they are standard extension provides by Tomcat. Therefore, they are not included with Java SE 6. First, we shall discuss in detail javax.servlet package, its classes and interfaces and then javax.servlet.http package.

javax.servlet PACKAGE

The javax.Servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The classes and interface in this package are protocol independent. The Fig. shows classes and interfaces in this package.

 Classes and Interfaces of javax.servlet PACKAGE

The javax. servlet package contains many interfaces and classes. Some of the interfaces and classes  are listed in table.

 

Interfaces

Description

Servlet

Declares life cycle methods that all servlets must implement.

ServletConfig

Allows servlets to get initialization parameters

ServletContext

Allows servlets to communicate with its servlet container.

ServletRequest

Provides client request information to a servlet.

ServletResponse

Assist a servlet in sending a response to the client.

 

Classes

Description

GenericServlet

Provides a basic implementation of the Servlet interface for protocol independent servlets

ServletlnputStream

Provides an input stream for reading binary data from a client request.

ServletOutputStream

Provides an output stream for sending binary data to the client.

ServletException

Defines a general exception, a servlet can throw when it encounters difficulty.

UnavailableException

Indicates that a servlet is not available to service client request.

Servlet INTERFACE

The Servlet interface defines the basic structure of a servlet. This interface specifies the contract between the servlet container and a servlet. In other words, it is the interface that container use to reference servlets. All servlets implement this interface, either directly or indirectly by extending either the GenericServlet or HttpServlet class which implements the Servlet interface. This interface defines methods that provide basic servlet functionality – to initialize a servlet, to receive and respond to client requests and to destroy a servlet and its resources. These methods are invoked by the servlet container. The Servlet interface defines the following methods:

• void init (ServletConfig config) throws ServletException: It is called to initialize the servlet. This method is called only once automatically by the servlet container when it loads the servlet. This method can be used to perform one-time activities such as creating database connections, read initialization parameters etc. The container pass an object of type ServletConfig which can be used to obtain initialization parameters.

• ServletConfig getServletConfig () : It returns the ServletConfig object passed to the servlet during init () method.

• String getServletlnfo () : It returns a String object containing information about the servlet such as author, creation date, version and copyright etc.

• void service(ServletRequest request, ServletResponse response) throws ServletException, IOException : This is the entry point for executing application logic in a servlet. It is called by the servlet container to process a request from a client. A servlet receives request information via the ServletRequest object and sends the data back to the client via ServletResponse object.

• void destroy () : This method is called by the servlet container before removing a servlet out of service. This may occur if the web server is being shutdown or the servlet container needs to free some memory. Resources used by the servlet such as open database connections, open files should be deallocated here.

ServletConfig INTERFACE

The ServletConfig interface is implemented by the server. Servers use ServletConfig object to pass configuration information to servlets. The configuration information contains initialization parameters, the name of the servlet and a ServletContext object which gives servlet information about the container. The methods declared in this interface are

Methods

Description

String getlnitParameter

(String name)

It returns a String containing the value of a named initialization parameter or null if specified parameter does not exist.

String getServletName()

It returns the name assigned to a servlet in its deployment descriptor.

If no name is specified, this returns the servlet class name instead.

ServletContext

getServletContext()

It returns a reference to the ServletContext object for the associated servlet, allowing interaction with the server.

Enumeration

getlnitParameterName()

It returns the name of the servlet’s initialization parameters as an enumeration of String objects or an empty Enumeration if no initialization parameters are specified.

ServletContext INTERFACE

The ServletContext interface provides a means for servlets to communicate with its servlet container. This communication includes finding path information, accessing other servlets running on the server, writing to the server log, getting MIME type of a file and so on. There is one context per web application per Java Virtual Machine.

The ServletContext object is a container within the ServletConfig object which the web server provides to the servlet when the servlet is initialized ..

The ServletContext interface specifies the following methods:

Methods

Description

Object setAttribute(String name)

It sets the servlet container attribute with the given name or null if the attribute doesnot exist.

String getMimeType(String fileName)

It returns the MIME type of a specified file or null if it is not known.

String getRealPath(String vpath)

It returns the real path (on the server file system) that corresponds to the virtual path vpath.

String getServerlnfo()

It returns the name and version of the servlet container separated by a forward slash (f).

void setAttribute(String

name, Object obj)

It binds a specified object to a given attribute name in this servlet context.

void log (String msg)

It writes the specified message to a servlet log file usually an

event log.

void log(String msg, Throwable t)

It writes the specified message msg and a stack trace for a specified Throwable exception t to the servlet log file.

ServletRequest INTERFACE

The ServletRequest interface defines an object that encapsulates information about a single client request. The servlet container creates a ServletRequest object and passes it as an argument to the servlet’s service () method. Data provided by the object generally includes parameter names and values, implementation specific attributes and an input stream for reading binary data from the request body. Some of the methods specified in it are given below :

Methods

Description

Object getAttribute(String name)

It returns the value of the named attribute as an object, or null if the named attribute does not exist.

Enumeration getAttributeNames()

It returns an enumeration of all attributes contained in the request.

int getContentLength()

It returns the length (in bytes) of the content being sent via the

input stream or -1 if the length is not known.

String getContentType()

It request the MIME type of the body of the request or null if the type is not known.

ServletlnputStream getlnputStream()

It retrieves the body of the request as binary data using

Servletlnputstream object.

String getparameter (String name)

It returns the value of the specified parameter or null if the

parameter does not exists or without a value.

Enumeration getParameterNames()

It returns all the parameter names as enumeration of String

objects.

String [] getParameterValues(String name)

It returns an array of String objects containing all the values of the specified parameter or null if the parameter does not exist.

String getprotocol()

It returns the name and version of the protocol used by the request.

String getParameterAddr()

It returns the IP address of the client that sent the request.

String getRemoteHost()

It returns the name of the client that send the request.

String getScheme()

It returns the name and the scheme used to make the request.

For example : http, ftp,https etc.

String getServerName()

It returns the name of the server that receives the request.

int getServerport()

It returns the port number on which the request was received.

BufferedReader getReader()

It retrieves the body of the request as character data.

ServletResponse INTERFACE

The ServIetResponse interface is the response counterpart of the ServIetRequest object. It defines an object to assist a servlet in sending MIME encoded data back to the client. Theservlet container create a ServIetResponse object and passes it as an argument to the servlet’s service () method.

Some of the most commonly used methods of this interface are as follows:

Methods

Description

void setContentType(String type)

It sets the MIME type of the response being sent to the client. For example, in case of HTML, the MIME type should be set to “text/HTML”.

void setContentLength(int Ien)

It sets the length of the content being returned by the server. In HTTP servlets, this method sets the HTTP content -length header.

ServIetOutputStream getOutputStream()

It returns a ServIetOutStream object than can be used for writing binary data into the response.

printWriter getWriter()

It returns a PrintWriter object that can send character text in the response.

String getCharacterEncoding()

It returns the name of the charset used for the MIME body sent in the response.

SingleThreadModel INTERFACE

SingIeThreadModel is a special marker interface with no methods. If a servlet implement this interface, the servlet container ensures that the servlet handles only one request at a time. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet’s service () method.

Servlet container implements this functionality by maintaining a pool of servlet instances. For each incoming request, the container allocates a servlet instance from the pool and once the service is completed, the container returns the instance to the pool. This interface provides easy thread safety but at the cost of increased resource requirements as more servlet instances are loaded at any given time.

GenericServlet CLASS

The GenericServlet class provides a basic implementation of the Servlet interface. This is an abstract class and all subclasses should implement the service () method. This class implements both Servlet as well as ServletConfig interface. It has the following methods in addition to those declared in Servlet and ServletConfig interfaces.

Methods

Description

void init ()

It is similar to init (ServletConfig config). This method is provided as a convenience so that servlet developers do not have to worry about storing the ServletConfig object.

void log (String msg)

It writes the specified message msg to a servlet log file.

void log(String msg, Thowable t)

It writes the name of the servlet, the specified message msg and the stack trace t to the servlet log file.

ServletInputStream CLASS

The ServletlnputStream class extends InputStream. It provides input stream for reading binary data from a client request. A servlet obtains a ServletlnputStream object from the getlnputStream () method of ServletRequest. It defines the default constructor which does nothing. In addition, it also contains the following method:

• int readLine (byte [] buf, int off, int len) : This method reads bytes from the input stream into the byte array buf, starting at the specified offset off. It stops reading when it encounters an ‘\n’ or it has read len number of bytes. The method returns the actual number of bytes read or -1 if an end of the stream is reached.

ServletOutputStream CLASS

The ServletOutputStream class extends OutputStream. It provides an output stream for sending binary data back to the client. A servlet obtains a ServletOutputStream object from the getOutputStream () method of ServletResponse. It also has a default constructor that does nothing. In addition, it also includes a range of print () and println () methods for sending text or HTML. It takes the following form

• void print(type v)

• void println(type v)

Here, type specifies the datatype int, char, float, long, String, double, boolean and v specifies the data to be written.

ServletException CLASSES

The javax.Servlet defines two exception classes ServletException and UnavailableException. The ServletException is a generic exception which can be thrown by servlets encountering difficulties. UnavailableException is a special type of servlet exception which extends the ServletException class. The purpose of this class is to indicate to the servlet container that the servlet is either temporarily or permanently unavailable to service client requests.

What is difference between SERVLET and CGI?

By Dinesh Thakur

The Common Gateway Interface (CGI) is the first technology used to generate dynamic contents. It allows a web client to pass data to the application running on the web server so that a dynamic web page can be returned to the client according to the input data. For example, when you use a search engine, buy a book at an online store; get a stock quote etc., your browser uses CGI to communicate with a server side application. [Read more…] about What is difference between SERVLET and CGI?

« Previous Page
Next Page »

Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW