Unit III: Java for Server Side Programming - Web Technologies II - BCA Notes (Pokhara University)

Breaking

Saturday, August 10, 2019

Unit III: Java for Server Side Programming - Web Technologies II

Java Servlets:

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Using Servlets, we can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). 

Servlets Offer Several Advantages In Comparison With The CGI.
1. Performance is significantly better.
2. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
3. Servlets are platform-independent because they are written in Java.
4. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
5. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that we have seen already.

Advantages Of a Java Servlet:

1. Servlet is faster than CGI as it does not involve the creation of a new process for every new request received.

2. Servlets as written in Java is platform-independent.

3. Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance which handles all requests concurrently. This also saves memory and allows a Servlet to easily manage client state.

4. It is a server-side component, so Servlet inherits the security provided by the Web server.

5. The API designed for Java Servlet automatically acquires the advantages of Java platform such as platform-independent and portability. Besides, it obviously can use the wide range of APIs created on Java platform such as JDBC to access the database.

Servlets Architecture:

The following diagram shows the position of Servlets in a Web Application.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Servlets Perform the Following Major Tasks:

1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web the page or it could also come from an applet or a custom HTTP client program.

2. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.

3. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

4. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

5. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Servlets Life Cycle:

A servlet life cycle can be defined as the entire process from its creation until the destruction. The following are the paths followed by a servlet.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

1. The init() Method:

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but we can also specify that the servlet is loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init Method Definition Looks Like This:
public void init() throws ServletException {
   // Initialization code...
}

2. The service() Method:

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here Is The Signature Of This Method:
public void service(ServletRequest request, ServletResponse response)
   throws ServletException, IOException {
}

The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are the most frequently used methods within each service request. Here is the signature of these two methods.

3. The doGet() Method:

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code
}

4. The doPost() Method:

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code
}

5. The destroy() Method:

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. After the destroy() method is called, the servlet object is marked for garbage collection.

The destroy() Method Definition Looks Like This:
public void destroy() {
   // Finalization code...
}

Architecture Diagram:

The following figure depicts a typical servlet life-cycle scenario.
1. First the HTTP requests coming to the server are delegated to the servlet container.
2. The servlet container loads the servlet before invoking the service() method.
3. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

Sample Code:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

   private String message;

   public void init() throws ServletException {
      // Do required initialization
      message = "Hello World";
   }

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
     
      // Set response content type
      response.setContentType("text/html");

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
   }

   public void destroy() {
      // do nothing.
   }
}

The Servlet Container:

Servlet container, also known as Servlet Engine is an integrated set of objects that provide run time environment for Java Servlet components.

In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Services Provided By The Servlet Container:

1. Network Services:
Loads a Servlet class. The loading maybe from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.

2. Decode And Encode MIME Based Messages:
Provides the service of decoding and encoding MIME-based messages.

3. Manage the Servlet Container:
Manages the lifecycle of a Servlet.

4. Resource Management:
Manages the static and dynamic resource, such as HTML files, Servlets and JSP pages.

5. Security Service:
Handles authorization and authentication of resource access.

6. Session Management:
Maintains a session by appending a session ID to the URL path.

What is CGI (Common Gateway Interface)?

CGI is actually an external application which is written by using any of the programming languages like C or C++ and this is responsible for processing client requests and generating dynamic content.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

In CGI application, when a client makes a request to access dynamic Web pages, the Web server performs the following operations:
1. It first locates the requested web page i.e. the required CGI application using URL.
2. It then creates a new process to service the client’s request.
3. Invokes the CGI application within the process and passes the request information to the server.
4. Collects the response from CGI application.
5. Destroys the process prepares the HTTP response and sends it to the client.

Difference Between Servlet and CGI:

Servlet
CGI (Common Gateway Interface)
Servlets are portable and efficient.
CGI is not portable
In Servlets, sharing of data is possible.
In CGI, sharing of data is not possible.
Servlets can directly communicate with the web server.
CGI cannot directly communicate with the webserver.
Servlets are less expensive than CGI.
CGI is more expensive than Servlets.
Servlets can handle the cookies.
CGI cannot handle the cookies.

Servlets API’s:

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet API. The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and classes that are responsible for Http requests only.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Interfaces in javax.servlet Package:

There are many interfaces in javax.servlet package. They are as follows:
a. Servlet
b. ServletRequest
c. ServletResponse
d. RequestDispatcher
e. ServletConfig
f. ServletContext
g. SingleThreadModel
h. Filter
i. FilterConfig
j. FilterChain
k. ServletRequestListener
l. ServletRequestAttributeListener
m. ServletContextListener
o. ServletContextAttributeListener

Classes in javax.servlet Package:

There are many classes in javax.servlet package. They are as follows:
a. GenericServlet
b. ServletInputStream
c. ServletOutputStream
d. ServletRequestWrapper
e. ServletResponseWrapper
f. ServletRequestEvent
g. ServletContextEvent
h. ServletRequestAttributeEvent
i. ServletContextAttributeEvent
j. ServletException
k. UnavailableException

Interfaces in javax.servlet.http Package:

There are many interfaces in javax.servlet.http package. They are as follows:
a. HttpServletRequest
b. HttpServletResponse
c. HttpSession
d. HttpSessionListener
e. HttpSessionAttributeListener
f. HttpSessionBindingListener
g. HttpSessionActivationListener
h. HttpSessionContext (deprecated now)

Classes in javax.servlet.http Package:

There are many classes in javax.servlet.http package. They are as follows:
a. HttpServlet
b. Cookie
c. HttpServletRequestWrapper
d. HttpServletResponseWrapper
e. HttpSessionEvent
f. HttpSessionBindingEvent
g. HttpUtils (deprecated now)

Parameter Data:

Parameters may come into our application from the client request, or maybe configured through deployment descriptor (web.xml) elements or their corresponding annotations. When we submit a form, form values are sent as request parameters to a web application. In case of a GET request, these parameters are exposed in the URL as name-value pairs and in case of POST, parameters are sent within the body of the request. 
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Servlet init parameters and context init parameters are set through the deployment descriptor (web.xml) or their corresponding annotations. All parameters are read-only from the application code. We have methods in the Servlet API to retrieve various parameters. 

Attributes are objects that are attached to various scopes and can be modified, retrieved or removed. Attributes can be read, created, updated and deleted by the web container as well as our application code. We have methods in the Servlet API to add, modify, retrieve and remove attributes. When an object is added to an attribute in any scope, it is called binding as the object is bound into a scoped attribute with a given name.

Important Differences Between Attributes And Parameters In JSP/Servlets Are:

a. Parameters are read-only, attributes are read/write objects. 
b. Parameters are String objects, attributes can be objects of any type.

Servlet API Methods To Manipulate Parameters:

The API Methods To Retrieve The Request Parameters Are:
1. ServletRequest.getParameterValues(String parmName): returns a string array with all values present, or null if no value exists for the parameter name.

2. ServletRequest.getParameter(String parmName): returns the first value for the given parameter.

3. ServletRequest.getParameterNames(): returns an Enumeration of String objects representing the names of all the parameters in the request. If there are no parameters Enumeration will be empty.

4. ServletRequest.getParameterMap(): returns a java.util.Map object, where the keys in the map are of type String (and represent each unique parameter name) and the values in the map of type String array (representing the values for the parameter).

The API Methods To Retrieve The ServletContext Initialization Parameters From a ServletContext Object Are:
1. ServletContext.getInitParameterNames(): will always return an enumeration of names.
2. ServletContext.getInitParameter(String paramName): will return a String or null.

The API Methods To Retrieve The ServletConfig Initialization Parameters From a ServletConfig Object Are:
1. ServletConfig.getInitParameterNames(): returns an enumeration of all the parameter names available to the servlet.

2. ServletConfig.getInitParameter(String paramName): return a parameter value.
Both the methods are implemented in the GenericServlet abstract class.

Servlet API Methods To Manipulate Attributes:

The attribute manipulation methods for request, session and application scopes are identical and differ only on the interfaces they are defined. They are:
a. public void setAttribute(String name, Object value)
b. public Object getAttribut(String name)
c. public Enumeration getAttributeNames()
d. public void removeAttribute(String name)

Note:

1. If the object passed has a value of null, it has the same effect as calling removeAttribute() for that attribute.

2. If any of the attribute manipulation functions are invoked in session scope when the session is invalid, IllegalStateException will be thrown.

3. Null is returned if no attribute of the given name exists.

4. If we call getAttributeNames() when no attributes are there, an empty enumeration will be returned. However, since some attributes will be always supplied by the web container during the application context, the enumeration returned by getAttributeNames() will never be empty in the application scope.

5. There is no guarantee of the order of the attributes within the enumeration returned by the getAttributeNames() method.

Example:

GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submits button. We are going to use the same Servlet HelloForm to handle this input.
<html>
   <body>
      <form action = "HelloForm" method = "GET">
         First Name: <input type = "text" name = "first_name">
         <br />
         Last Name: <input type = "text" name = "last_name" />
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When we would access http://localhost:8080/Hello.htm, here is the actual output of the above form.

Try to enter First Name and Last Name and then click submit button to see the result on our local machine where tomcat is running. Based on the input provided, it will generate a similar result as mentioned in the above example.

Here is a simple URL which will pass two values to HelloForm program using GET method.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
     
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
        
      out.println(docType +
         "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor = \"#f0f0f0\">\n" +
               "<h1 align = \"center\">" + title + "</h1>\n" +
               "<ul>\n" +
                  "  <li><b>First Name</b>: "
                  + request.getParameter("first_name") + "\n" +
                  "  <li><b>Last Name</b>: "
                  + request.getParameter("last_name") + "\n" +
               "</ul>\n" +
            "</body>" +
         "</html>"
      );
   }
}

POST Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submits button.
<html>
   <body>
      <form action = "HelloForm" method = "POST">
         First Name: <input type = "text" name = "first_name">
         <br />
         Last Name: <input type = "text" name = "last_name" />
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

Let us do little modification in the above servlet so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {

   // Method to handle GET method request.
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
     
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " +
         "transitional//en\">\n";
        
      out.println(docType +
         "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor = \"#f0f0f0\">\n" +
               "<h1 align = \"center\">" + title + "</h1>\n" +
               "<ul>\n" +
                  "  <li><b>First Name</b>: "
                  + request.getParameter("first_name") + "\n" +
                  "  <li><b>Last Name</b>: "
                  + request.getParameter("last_name") + "\n" +
               "</ul>\n" +
            "</body>"
         "</html>"
      );
   }

   // Method to handle POST method request.
   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      doGet(request, response);
   }
}

Difference Between GET and POST:

Basis
GET
POST
Bookmarked
Can be bookmarked.
Cannot be bookmarked.
BACK Button/
Re-Submit Behaviour
GET requests are re-executed but may not be re-submitted to server if the HTML is stored in the browser cache.
The browser usually alerts the user that data will need to be re-submitted.
Parameters
Can send but the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K
Can send parameters, including uploading files, to the server.
Hacked
Easier to hack for script kiddies
More difficult to hack
Restrictions On Form Data Type
Yes, only ASCII characters allowed.
No restrictions. Binary data is also allowed.
Security
GET is less secure compared to POST because data sent is part of the URL. So it's saved in browser history and server logs in plaintext.
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs.
Restrictions On Form Data Length
Yes, since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server.
No restrictions
Usability
GET method should not be used when sending passwords or other sensitive information.
POST method used when sending passwords or other sensitive information.
Visibility
GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.
POST method variables are not displayed in the URL.
Cached
Can be cached
Not cached

Managing Session in Servlets:

We all know that HTTP is a stateless protocol. All requests and responses are independent. But sometimes you need to keep track of the client's activity across multiple requests. For example, when a user logs into our website, no matter on which web page he/she visits after logging in, his/her credentials will be with the server, until he/she logs out. So this is managed by creating a session.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Session Management is a mechanism used by the Web container to store session information for a particular user. There are four different techniques used by Servlet application for session management. They are as follows:
1. Cookies
2. URL Rewriting
3. HttpSession
4. Hidden form field

The session is used to store everything that we can get from the client from all the requests the client makes.

How Session Works?

Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page
The basic concept behind the session is, whenever a user starts using our application, we can save unique identification information about him, in an object which is available throughout the application, until it’s destroyed. So wherever the user goes, we will always have his information and we can always manage which user is doing what. Whenever a user wants to exit from our application, destroy the object with his information.

1. Cookies:

Cookies are small pieces of information that are sent in response from the webserver to the client. Cookies are the simplest technique used for storing client state. Cookies are stored on the client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Using Cookies for storing client state has one shortcoming though if the client has turned of Cookie saving settings in his browser then, client state can never be saved because the browser will not allow the application to store cookies.

Servlet: Cookies API:
Cookies are created using Cookie class present in Servlet API. Cookies are added to the response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to the response object.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Example Demonstrating Usage Of Cookies:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Below Mentioned Files Are Required For The Example:
index.html
<form method="post" action="validate">
    Name:<input type="text" name="user" /><br/>
    Password:<input type="text" name="pass" ><br/>
    <input type="submit" value="submit">
</form>

web.xml
<web-app...>
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
   
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
   
</web-app>

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

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
       
        if(pass.equals("1234"))
        {
            Cookie ck = new Cookie("username", name);
            response.addCookie(ck);
            response.sendRedirect("First");
        }
    }
}

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

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+ cks[0].getValue());
    }
}

2. URL Rewriting:

If the client has disabled cookies in the browser then session management using cookie won’t work. In that case, URL Rewriting can be used as a backup. URL rewriting will always work. In URL rewriting, a token(parameter) is added at the end of the URL. The token consists of a name/value pair separated by an equal(=) sign.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

For Example:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

When the user clicks on the URL having parameters, the request goes to the Web Container with an extra bit of information at the end of the URL. The Web Container will fetch the extra part of the requested URL and use it for session management. The getParameter() method is used to get the parameter value at the server-side.

Example Demonstrating Usage Of URL Rewriting:
index.html
<form method="post" action="validate">
    Name:<input type="text" name="user" /><br/>
    Password:<input type="text" name="pass" ><br/>
    <input type="submit" value="submit">
</form>

web.xml
<web-app...>
   
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
   
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
   
</web-app>

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

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
       
        if(pass.equals("1234"))
        {
            response.sendRedirect("First?user_name="+ name);
        }
    }  
}

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

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String user = request.getParameter("user_name");
        out.println("Welcome "+user);
    }
}

3. HttpSession:

HttpSession object is used to store an entire session with a specific client. We can store, retrieve and remove the attribute from the HttpSession object. Any servlet can have access to HttpSession object throughout the getSession() method of the HttpServletRequest object.

How HttpSession Works?
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

1. On the client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container.

2. The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from.

3. The Web Container uses this ID finds the matching session with the ID and associates the session with the request.

HttpSession Interface:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page
Some Important Methods of Servlet HttpSession:
Methods
Description
long getCreationTime()
Returns the time when the session was created, measured in milliseconds since midnight January 1, 1970, GMT.
String getId()
Returns a string containing the unique identifier assigned to the session.
long getLastAccessedTime()
Returns the last time the client sent a request associated with the session
int getMaxInactiveInterval()
Returns the maximum time interval, in seconds.
void invalidate()
Destroy the session
boolean isNew()
Returns true if the session is new else false
void setMaxInactiveInterval(int interval)
Specifies the time, in seconds, after the servlet container will invalidate the session.

Complete Example Demonstrating Usage of HttpSession:
index.html
<form method="post" action="Validate">
    User: <input type="text" name="user" /><br/>
    Password: <input type="text" name="pass" ><br/>
    <input type="submit" value="submit">
</form>

web.xml
<web-app..>
   
    <servlet>
        <servlet-name>Validate</servlet-name>
        <servlet-class>Validate</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Welcome</servlet-name>
        <servlet-class>Welcome</servlet-class>
    </servlet>
  
    <servlet-mapping>
        <servlet-name>Validate</servlet-name>
        <url-pattern>/Validate</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Welcome</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

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

public class Validate extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
       
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
       
        if(pass.equals("1234"))
        {
            //creating a session
            HttpSession session = request.getSession();
            session.setAttribute("user", name);
            response.sendRedirect("Welcome");
        }
    }
}

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

public class Welcome extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String user = (String)session.getAttribute("user");
        out.println("Hello "+user);
    }
}

4. Hidden Form Field:

A hidden form field can also be used to store session information for a particular client. In case of a hidden form field, a hidden field is used to store client state. In this case, user information is stored in hidden field value and retrieved from another servlet.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Advantages:
a. Does not have to depend on the browser whether the cookie is disabled or not.
b. Inserting a simple HTML Input field of type hidden is required. Hence, it’s easier to implement.

Disadvantage:
a. Extra form submission is required on every page. This is a big overhead.

Example Demonstrating Usage Of Hidden Form Field For Session:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Below Mentioned Files Are Required For The Example:
index.html
<form method="post" action="validate">
  Name:<input type="text" name="user" /><br/>
  Password:<input type="text" name="pass" ><br/>
  <input type="submit" value="submit">
</form>

web.xml
<web-app...>
   
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
   
    <servlet>
        <servlet-name>Second</servlet-name>
        <servlet-class>Second</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Second</servlet-name>
        <url-pattern>/Second</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
   
</web-app>

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

public class First extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
       
      //getting value submitted in form from HTML file
        String user = request.getParameter("user");
       
        //creating a new hidden form field
        out.println("<form action='Second'>");
        out.println("<input type='hidden' name='user' value='"+user+"'>");
        out.println("<input type='submit' value='submit' >");
        out.println("</form>");
    }
}

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

public class Second extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
       
        //getting parameter from the hidden field
        String user = request.getParameter("user");
        out.println("Welcome "+user);
    }
}

Like we created a hidden field in First Servlet, populated the value of the user, and sent it to the Second Servlet, now the Second servlet also has the user information. Similarly, we will have to keep sending this information, wherever we need this, using hidden fields.

Data Storage:

To start with the basic concept, let us create a simple table and create few records in that table as follows:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Create Table:

To create the Employees table in the TEST database, use the following steps:

Step 1:
Open a Command Prompt and change to the installation directory as follows:
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2:
Login to database as follows:
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

Step 3:
Create the table Employee in the TEST database as follows:
mysql> use TEST;
mysql> create table Employees (
   id int not null,
   age int not null,
   first varchar (255),
   last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records:

Finally, we create a few records in Employee table as follows:
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)

mysql>

Accessing a Database:

Here is an example which shows how to access TEST database using Servlet.
// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DatabaseAccess extends HttpServlet{

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  
      // JDBC driver name and database URL
      static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
      static final String DB_URL="jdbc:mysql://localhost/TEST";

      //  Database credentials
      static final String USER = "root";
      static final String PASS = "password";

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Database Result";
     
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
     
      out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" +
         "<h1 align = \"center\">" + title + "</h1>\n");
      try {
         // Register JDBC driver
         Class.forName("com.mysql.jdbc.Driver");

         // Open a connection
         Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

         // Execute SQL query
         Statement stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, first, last, age FROM Employees";
         ResultSet rs = stmt.executeQuery(sql);

         // Extract data from result set
         while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            out.println("ID: " + id + "<br>");
            out.println(", Age: " + age + "<br>");
            out.println(", First: " + first + "<br>");
            out.println(", Last: " + last + "<br>");
         }
         out.println("</body></html>");

         // Clean-up environment
         rs.close();
         stmt.close();
         conn.close();
      } catch(SQLException se) {
         //Handle errors for JDBC
         se.printStackTrace();
      } catch(Exception e) {
         //Handle errors for Class.forName
         e.printStackTrace();
      } finally {
         //finally block used to close resources
         try {
            if(stmt!=null)
               stmt.close();
         } catch(SQLException se2) {
         } // nothing we can do
         try {
            if(conn!=null)
            conn.close();
         } catch(SQLException se) {
            se.printStackTrace();
         } //end finally try
      } //end try
   }
}

Now let us compile above servlet and create following entries in web.xml
....
<servlet>
   <servlet-name>DatabaseAccess</servlet-name>
   <servlet-class>DatabaseAccess</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>DatabaseAccess</servlet-name>
   <url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....

Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display the following response:

Database Result:

ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal

JSP (Java Server Page):

Java Server Pages (JSP) is a technology for developing Webpages that supports dynamic content. This helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

A Java Server Pages component is a type of Java servlet that is designed to fulfil the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, we can collect input from users through Webpage forms, present records from a database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages, and sharing information between requests, pages etc.

Why Use JSP?

Java Server Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.

1. Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having separate CGI files.

2. JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.

3. Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.

4. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

Finally, JSP is an integral part of Java EE, a complete platform for enterprise-class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

JSP v/s Servlet:

a. JSP provides an easier way to code dynamic web pages.
b. JSP does not require additional files like java class files, web.xml etc.
c. Any change in the JSP code is handled by Web Container (Application server like tomcat) and doesn't require recompilation.
d. JSP pages can be directly accessed, and web.xml mapping is not required like in servlets.

Advantages of JSP:

Following table lists out the other advantages of using JSP over other technologies:

1. vs. Active Server Pages (ASP):

The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.

2. vs. Pure Servlets:

It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML.

3. vs. Server-Side Includes (SSI):

SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

4. vs. JavaScript:

JavaScript can generate HTML dynamically on the client but can hardly interact with the webserver to perform complex tasks like database access and image processing etc.

5. vs. Static HTML:

Regular HTML, of course, cannot contain dynamic information.

The Architecture of JSP:

The web server needs a JSP engine, i.e. a container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

JSP Processing:

The following steps explain how the webserver creates the Webpage using JSP:
1. As with a normal page, our browser sends an HTTP request to the webserver.

2. The webserver recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.

3. The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code. This code implements the corresponding dynamic behaviour of the page.

4. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.

5. A part of the webserver called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format. The output is further passed on to the webserver by the servlet engine inside an HTTP response.

6. The webserver forwards the HTTP response to our browser in terms of static HTML content.

7. Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response exactly as if it were a static page.

All The Above Mentioned Steps Can Be Seen In The Following Diagram:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with the other scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.

JSP Life Cycle:

A JSP life cycle is defined as the process from its creation until the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into the servlet. The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. 
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

1. JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

The Compilation Process Involves Three Steps:
a. Parsing the JSP.
b. Turning the JSP into a servlet.
c. Compiling the servlet.

2. JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method.
public void jspInit(){
   // Initialization code...
}

Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files and create lookup tables in the jspInit method.

3. JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response) {
   // Service handling code...
}

The _jspService() method of a JSP is invoked on a request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

4. JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() Method Has The Following Form:
public void jspDestroy() {
   // Your cleanup code goes here.
}

Elements of JSP:

Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

1. The Scriptlet:

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet:
<% code fragment %>

We can write the XML equivalent of the above syntax as follows:
<jsp:scriptlet>
   code fragment
</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html>
   <head><title>Hello World</title></head>
  
   <body>
      Hello World!<br/>
      <%
         out.println("Your IP address is " + request.getRemoteAddr());
      %>
   </body>
</html>

2.JSP Declarations:

A declaration declares one or more variables or methods that we can use in Java code later in the JSP file. We must declare the variable or method before we use it in the JSP file.

Following Is The Syntax For JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>

We Can Write The XML Equivalent Of The Above Syntax As Follows:
<jsp:declaration>
   code fragment
</jsp:declaration>

Following Is An Example For JSP Declarations:
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

3. JSP Expression:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because of the value of an expression is converted to a String, we can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.

Following Is The Syntax Of JSP Expression:
<%= expression %>

We Can Write The XML Equivalent Of The Above Syntax As Follows:
<jsp:expression>
   expression
</jsp:expression>

Following Example Shows A JSP Expression:
<html>
   <head><title>A Comment Test</title></head>
  
   <body>
      <p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
   </body>
</html>

4. JSP Comments:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out", a part of your JSP page.

Following Is The Syntax Of The JSP Comments:
<%-- This is JSP comment --%>

Following Example Shows The JSP Comments:
<html>
   <head><title>A Comment Test</title></head>
  
   <body>
      <h2>A Test of Comments</h2>
      <%-- This comment will not be visible in the page source --%>
   </body>
</html>
 
There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:
S.No.
Syntax & Purpose
1
<%-- comment --%>
A JSP comment. Ignored by the JSP engine.
2
<!-- comment -->
An HTML comment. Ignored by the browser.
3
<\%
Represents static <% literal.
4
%\>
Represents static %> literal.
5
\'
A single quote in an attribute that uses single quotes.
6
\"
A double quote in an attribute that uses double-quotes.

5. JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>

There Are Three Types Of Directive Tag:
S.No.
Directive & Description
1
<%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
2
<%@ include ... %>
Includes a file during the translation phase.
3
<%@ taglib ... %>
Declares a tag library, containing custom actions, used in the page

6. JSP Actions:

JSP actions use constructs in XML syntax to control the behaviour of the servlet engine. We can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.

There Is Only One Syntax For The Action Element, As It Conforms To The XML Standard:
<jsp:action_name attribute="value" />

Action elements are basically predefined functions. Following table lists out the available JSP Actions:
S.No.
Syntax & Purpose
1
jsp:include
Includes a file at the time the page is requested.
2
jsp:useBean
Finds or instantiates a JavaBean.
3
jsp:setProperty
Sets the property of a JavaBean.
4
jsp:getProperty
Inserts the property of a JavaBean into the output.
5
jsp:forward
Forwards the requester to a new page.
6
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
7
jsp:element
Defines XML elements dynamically.
8
jsp:attribute
Defines dynamically-defined XML element's attribute.
9
jsp:body
Defines dynamically-defined XML element's body.
10
jsp:text
Used to write template text in JSP pages and documents.

7. JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These variables are:
S.No.
Object & Description
1
request
This is the HttpServletRequest object associated with the request.
2
response
This is the HttpServletResponse object associated with the response to the client.
3
out
This is the PrintWriter object used to send output to the client.
4
session
This is the HttpSession object associated with the request.
5
application
This is the ServletContext object associated with the application context.
6
config
This is the ServletConfig object associated with the page.
7
pageContext
This encapsulates the use of server-specific features like higher performance JspWriters.
8
page
This is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
9
Exception
The Exception object allows the exception data to be accessed by designated JSP.

8. Control-Flow Statements:

We can use all the APIs and building blocks of Java in our JSP programming including decision-making statements, loops, etc.

a. Decision-Making Statements:
The if...else block starts out as an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between the Scriptlet tags.
<%! int day = 3; %>
<html>
   <head><title>IF...ELSE Example</title></head>
  
   <body>
      <% if (day == 1 || day == 7) { %>
         <p> Today is weekend</p>
      <% } else { %>
         <p> Today is not weekend</p>
      <% } %>
   </body>
</html>

Now look at the following switch...case block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %>
<html>
   <head><title>SWITCH...CASE Example</title></head>
  
   <body>
      <%
         switch(day) {
            case 0:
               out.println("It\'s Sunday.");
               break;
            case 1:
               out.println("It\'s Monday.");
               break;
            case 2:
               out.println("It\'s Tuesday.");
               break;
            case 3:
               out.println("It\'s Wednesday.");
               break;
            case 4:
               out.println("It\'s Thursday.");
               break;
            case 5:
               out.println("It\'s Friday.");
               break;
            default:
               out.println("It's Saturday.");
         }
      %>
   </body>
</html>

b. Loop Statements:
We can also use three basic types of looping blocks in Java: for, while, and do…while blocks in your JSP programming.

Let Us Look At The Following For Loop Example:
<%! int fontSize; %>
<html>
   <head><title>FOR LOOP Example</title></head>
  
   <body>
      <%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
         <font color = "green" size = "<%= fontSize %>">
            JSP Tutorial
      </font><br />
      <%}%>
   </body>
</html>

Above Example Can Be Written Using The While Loop As Follows:
<%! int fontSize; %>
<html>
   <head><title>WHILE LOOP Example</title></head>
  
   <body>
      <%while ( fontSize <= 3){ %>
         <font color = "green" size = "<%= fontSize %>">
            JSP Tutorial
         </font><br />
         <%fontSize++;%>
      <%}%>
   </body>
</html>

9. JSP Operators:

JSP supports all the logical and arithmetic operators supported by Java. Following table lists out all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

Within an expression, higher precedence operators will be evaluated first.

Category
Operator
Associativity
Postfix
() [] . (dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicative
* / %
Left to right
Additive
+ -
Left to right
Shift
>> >>> <<
Left to right
Relational
> >= < <=
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
^
Left to right
Bitwise OR
|
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %= >>= <<= &= ^= |=
Right to left
Comma
,
Left to right

10. JSP Literals:

The JSP expression language defines the following literals:
a. Boolean − true and false
b. Integer − as in Java
c. Floating point − as in Java
d. String − with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
e. Null − null

Database Access:

To start with the basic concept, let us create a table and create a few records in that table as follows:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

1. Create Table:

To create the Employees table in the EMP database, use the following steps:

Step 1:
Open a Command Prompt and change to the installation directory as follows:
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2:
Login to the database as follows:
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

Step 3:
Create the Employee table in the TEST database as follows:
mysql> use TEST;
mysql> create table Employees
   (
      id int not null,
      age int not null,
      first varchar (255),
      last varchar (255)
   );
Query OK, 0 rows affected (0.08 sec)
mysql>

2. Create Data Records:

Let us now create a few records in the Employee table as follows:
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)

mysql>

3. SELECT Operation:

Following example shows how we can execute the SQL SELECT statement using JTSL in JSP programming:
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>
   <head>
      <title>SELECT Operation</title>
   </head>

   <body>
      <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
         url = "jdbc:mysql://localhost/TEST"
         user = "root"  password = "pass123"/>

      <sql:query dataSource = "${snapshot}" var = "result">
         SELECT * from Employees;
      </sql:query>

      <table border = "1" width = "100%">
         <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
         </tr>
        
         <c:forEach var = "row" items = "${result.rows}">
            <tr>
               <td><c:out value = "${row.id}"/></td>
               <td><c:out value = "${row.first}"/></td>
               <td><c:out value = "${row.last}"/></td>
               <td><c:out value = "${row.age}"/></td>
            </tr>
         </c:forEach>
      </table>

   </body>
</html>

4. INSERT Operation:

Following example shows how we can execute the SQL INSERT statement using JTSL in JSP programming:
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>
   <head>
      <title>JINSERT Operation</title>
   </head>
  
   <body>
      <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
         url = "jdbc:mysql://localhost/TEST"
         user = "root"  password = "pass123"/>
         <sql:update dataSource = "${snapshot}" var = "result">
         INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
      </sql:update>

      <sql:query dataSource = "${snapshot}" var = "result">
         SELECT * from Employees;
      </sql:query>

      <table border = "1" width = "100%">
         <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
         </tr>
        
         <c:forEach var = "row" items = "${result.rows}">
            <tr>
               <td><c:out value = "${row.id}"/></td>
               <td><c:out value = "${row.first}"/></td>
               <td><c:out value = "${row.last}"/></td>
               <td><c:out value = "${row.age}"/></td>
            </tr>
         </c:forEach>
      </table>

   </body>
</html>

5. DELETE Operation:

Following example shows how we can execute the SQL DELETE statement using JTSL in JSP programming:
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>
   <head>
      <title>DELETE Operation</title>
   </head>
  
   <body>
      <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
         url = "jdbc:mysql://localhost/TEST"
         user = "root" password = "pass123"/>

      <c:set var = "empId" value = "103"/>

      <sql:update dataSource = "${snapshot}" var = "count">
         DELETE FROM Employees WHERE Id = ?
         <sql:param value = "${empId}" />
      </sql:update>

      <sql:query dataSource = "${snapshot}" var = "result">
         SELECT * from Employees;
      </sql:query>

      <table border = "1" width = "100%">
         <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
         </tr>
           
         <c:forEach var = "row" items = "${result.rows}">
            <tr>
               <td><c:out value = "${row.id}"/></td>
               <td><c:out value = "${row.first}"/></td>
               <td><c:out value = "${row.last}"/></td>
               <td><c:out value = "${row.age}"/></td>
            </tr>
         </c:forEach>
      </table>

   </body>
</html>

6. UPDATE Operation:

Following example shows how we can execute the SQL UPDATE statement using JTSL in JSP programming:
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>
   <head>
      <title>DELETE Operation</title>
   </head>
  
   <body>
      <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
         url = "jdbc:mysql://localhost/TEST"
         user = "root" password = "pass123"/>

      <c:set var = "empId" value = "102"/>

      <sql:update dataSource = "${snapshot}" var = "count">
         UPDATE Employees SET WHERE last = 'Ali'
         <sql:param value = "${empId}" />
      </sql:update>

      <sql:query dataSource = "${snapshot}" var = "result">
         SELECT * from Employees;
      </sql:query>

      <table border = "1" width = "100%">
         <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
         </tr>
           
         <c:forEach var = "row" items = "${result.rows}">
            <tr>
               <td><c:out value = "${row.id}"/></td>
               <td><c:out value = "${row.first}"/></td>
               <td><c:out value = "${row.last}"/></td>
               <td><c:out value = "${row.age}"/></td>
            </tr>
         </c:forEach>
      </table>

   </body>
</html>

Database Programming using JDBC:

JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC (Open Database Connectivity). JDBC is a standard API specification developed to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e. it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Why JDBC Came Into Existence?

As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, Core Java and as we know above languages (except Java and some part of Python) are platform dependent. Therefore to remove dependence, JDBC was developed by database vendor which consisted of classes and interfaces written in Java.

Steps For Connectivity Between Java Program And Database:

1. Loading the Driver:
To begin with, we first need to load the driver or register it before using it in the program. Registration is to be done once in our program. We can register a driver in one of the two ways mentioned below:

a. Class.forName():
Here we load the driver’s class file into memory at the runtime. No need of using new or creation of an object .The following example uses Class.forName() to load the Oracle driver.
 Class.forName(“oracle.jdbc.driver.OracleDriver”);

b. DriverManager.registerDriver():
DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver() to register the Oracle driver.
 DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

2. Create the Connections:
After loading the driver, establish connections using:
 Connection con = DriverManager.getConnection(url,user,password)

a. user: username from which our SQL command prompt can be accessed.
b. password: password from which our SQL command prompt can be accessed.
c. con: is a reference to Connection interface.
d.url: Uniform Resource Locator.

It can be created as follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used, @localhost is the IP Address where the database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred from the final code.

3. Create a Statement:
Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from our database.

Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Here, con is a reference to Connection interface used in the previous step.

4. Execute the Query:
Now comes the most important part i.e. executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows:
a. Query for updating/inserting table in a database.
b. Query for retrieving data.

The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.

The executeUpdate(sql query) method of Statement interface is used to execute queries of updating/inserting.

Example:
int m = st.executeUpdate(sql);
if (m==1)
    System.out.println("inserted successfully : "+sql);
else
    System.out.println("insertion failed");

Here, sql is SQL query of the type String.

5. Close the Connections:
So finally we have sent the data to the specified location and now we are at the verge of completion of our task. By closing connection, objects of Statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Example:
 con.close();

Implementation:

importjava.sql.*;
importjava.util.*;
class Main
{
    public static void main(String a[])
    {
        //Creating the connection
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "system";
        String pass = "12345";
 
        //Entering the data
        Scanner k = new Scanner(System.in);
        System.out.println("enter name");
        String name = k.next();
        System.out.println("enter roll no");
        int roll = k.nextInt();
        System.out.println("enter class");
        String cls =  k.next();
 
        //Inserting data using SQL query
        String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
        Connection con=null;
        try
        {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
 
            //Reference to connection interface
            con = DriverManager.getConnection(url,user,pass);
 
            Statement st = con.createStatement();
            int m = st.executeUpdate(sql);
            if (m == 1)
                System.out.println("inserted successfully : "+sql);
            else
                System.out.println("insertion failed");
            con.close();
        }
        catch(Exception ex)
        {
            System.err.println(ex);
        }
    }
}

Performing Database Operations in Java:

Although the target database system is Oracle Database, the same techniques can be applied to other database systems as well because of the query syntax used is standard SQL is generally supported by all relational database systems.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Prerequisites:

a. JDK
b. Oracle Database (Download Oracle Database Express Edition 11g release 2)
c. JDBC driver for Oracle Database (Download Oracle Database 11g release 2 JDBC drivers).We need to add ojdbc6.jar to project library.

Creating A User In Oracle Database And Granting Required Permissions:

a. Open oracle using cmd. For that type sqlplus in cmd and press Enter.
b. Create a user-id protected by a password. This user-id is called child user.
create user  identified by ;
c. Grant required permissions to child user. For simplicity, we grant database administrator privilege to child user.
conn / as sysdba;
grant dba to ;

Create A Sample Table With Blank Fields:

CREATE TABLE userid(
    id varchar2(30) NOT NULL PRIMARY KEY,
    pwd varchar2(30) NOT NULL,
    fullname varchar2(50),
    email varchar2(50)
);

Principal JDBC Interfaces And Classes:

Let’s take an overview look at the JDBC’s main interfaces and classes which we’ll use in this article. They are all available under the java.sql package:

1. Class.forName():
Here we load the driver’s class file into memory at the runtime. No need of using new or creation of an object.
Class.forName("oracle.jdbc.driver.OracleDriver");

2. DriverManager:
This class is used to register driver for a specific database type (e.g. Oracle Database in this tutorial) and to establish a database connection with the server via its getConnection() method.

3. Connection:
This interface represents an established database connection (session) from which we can create statements to execute queries and retrieve results, get metadata about the database, close connection, etc.
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

4. Statement and PreparedStatement:

These interfaces are used to execute a static SQL query and parameterized SQL query, respectively. The statement is the super interface of the PreparedStatement interface. Their commonly used methods are:
a. boolean execute(String sql):
Executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.

b. int executeUpdate(String sql):
Executes an INSERT, UPDATE or DELETE statement and returns an updated account indicating the number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected).
Statement stmt = con.createStatement();
      String q1 = "insert into userid values
      ('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')";
      int x = stmt.executeUpdate(q1);

c. ResultSet executeQuery(String sql):
Executes a SELECT statement and returns a ResultSet object which contains results returned by the query.
Statement stmt = con.createStatement();
      String q1 = "select * from userid WHERE id = '" + id + "'
      AND pwd = '" + pwd + "'";
      ResultSet rs = stmt.executeQuery(q1);

d. ResultSet:
Contains table data returned by a SELECT query. Use this object to iterate over rows in the result set using the next() method.

e. SQLException:
This checked exception is declared to be thrown by all the above methods, so we have to catch this exception explicitly when calling the above classes’ methods.

Connecting To The Database:

The Oracle Database server listens on the default port 1521 at localhost. The following code snippet connects to the database name userid by the user login1 and password pwd1.
// Java program to illustrate 
// Connecting to the Database
import java.sql.*;
 
public class connect 
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
             
            // Establishing Connection
            Connection con = DriverManager.getConnection(
             "jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
 
            if (con != null)             
                System.out.println("Connected");            
            else           
                System.out.println("Not Connected");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Note:
Here oracle in database URL in getConnection() method specifies SID of Oracle Database. For Oracle database 11g it is orcl and for oracle database 10g it is xe.

Implementing Insert Statement:

// Java program to illustrate 
// inserting to the Database
import java.sql.*;
 
public class insert1
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1";
        String fullname = "geeks for geeks";
        String email = "geeks@geeks.org";
         
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
             
            // Inserting data in database
            String q1 = "insert into userid values('" +id+ "', '" +pwd+ 
                                  "', '" +fullname+ "', '" +email+ "')";
            int x = stmt.executeUpdate(q1);
            if (x > 0)            
                System.out.println("Successfully Inserted");            
            else           
                System.out.println("Insert Failed");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Implementing Update Statement:

// Java program to illustrate 
// updating the Database
import java.sql.*;
 
public class update1 
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1"; 
        String newPwd = "newpwd";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
         
            // Updating database
            String q1 = "UPDATE userid set pwd = '" + newPwd + 
                    "' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
            int x = stmt.executeUpdate(q1);
             
            if (x > 0)            
                System.out.println("Password Successfully Updated");            
            else           
                System.out.println("ERROR OCCURED :(");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Implementing Delete Statement:

// Java program to illustrate 
// deleting from Database
import java.sql.*;
 
public class delete 
{
    public static void main(String args[])
    {
        String id = "id2";
        String pwd = "pwd2";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
                  
            // Deleting from database
            String q1 = "DELETE from userid WHERE id = '" + id + 
                    "' AND pwd = '" + pwd + "'";
                     
            int x = stmt.executeUpdate(q1);
              
            if (x > 0)            
                System.out.println("One User Successfully Deleted");            
            else
                System.out.println("ERROR OCCURED :(");  
           
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Implementing Select Statement:

// Java program to illustrate 
// selecting from Database
import java.sql.*;
 
public class select 
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
                    jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
             
            // SELECT query
            String q1 = "select * from userid WHERE id = '" + id + 
                                    "' AND pwd = '" + pwd + "'";
            ResultSet rs = stmt.executeQuery(q1);
            if (rs.next())
            {
                System.out.println("User-Id : " + rs.getString(1));
                System.out.println("Full Name :" + rs.getString(3));
                System.out.println("E-mail :" + rs.getString(4));
            }
            else
            {
                System.out.println("No such user id is already registered");
            }
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Note:
Here the column index here is 1-based, the first column will be at index 1, the second at index 2, and so on.

Studying Javax.sql.* Package:

The java.sql package provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language. This API includes a framework whereby different drivers can be installed dynamically to access different data sources. Although the JDBC API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. The reader/writer facility, available through the javax.sql.RowSet group of interfaces can be customized to use and update data from a spreadsheet, flat file, or any other tabular data source.

java.sql Package Contains:

The java.sql package contains API for the following:

1. Making A Connection With A Database Via The DriverManager Facility:
a. DriverManager class: makes a connection with a driver.
b. SQLPermission class: provides permission when code running within a Security Manager, such as an applet, attempts to set up a logging stream through the DriverManager.
c. Driver interface: provides the API for registering and connecting drivers based on JDBC technology ("JDBC drivers"); generally used only by the DriverManager class.
d. DriverPropertyInfo class: provides properties for a JDBC driver; not used by the general user.

2. Sending SQL Statements To A Database:
a. Statement: used to send basic SQL statements.
b. PreparedStatement: used to send prepared statements or basic SQL statements (derived from Statement).
c. CallableStatement: used to call database stored procedures (derived from PreparedStatement).
d. Connection interface: provides methods for creating statements and managing connections and their properties.
e. Savepoint: provides savepoints in a transaction.

3. Retrieving And Updating The Results Of A Query:
a. ResultSet interface

4. Standard Mappings For SQL Types To Classes And Interfaces In The Java Programming Language:
a. Array interface: mapping for SQL ARRAY
b. Blob interface: mapping for SQL BLOB
c. Clob interface: mapping for SQL CLOB
d. Date class: mapping for SQL DATE
e. NClob interface: mapping for SQL NCLOB
f. Ref interface: mapping for SQL REF
g. RowId interface: mapping for SQL ROWID
h. Struct interface: mapping for SQL STRUCT
i. SQLXML interface: mapping for SQL XML
j. Time class: mapping for SQL TIME
k. Timestamp class: mapping for SQL TIMESTAMP
l. Types class: provides constants for SQL types

5. Custom Mapping An SQL User-Defined Type (UDT) To A Class In The Java Programming Language:
a. SQLData interface: specifies the mapping of a UDT to an instance of this class.
b. SQLInput interface: provides methods for reading UDT attributes from a stream.
c. SQLOutput interface: provides methods for writing UDT attributes back to a stream.

6. Metadata:
a. DatabaseMetaData interface: provides information about the database.
b. ResultSetMetaData interface: provides information about the columns of a ResultSet object.
c. ParameterMetaData interface: provides information about the parameters to PreparedStatement commands.

7. Exceptions:
a. SQLException: thrown by most methods when there is a problem accessing data and by some methods for other reasons.
b. SQLWarning: thrown to indicate a warning.
c. DataTruncation: thrown to indicate that data may have been truncated.
d. BatchUpdateException: thrown to indicate that not all commands in a batch update executed successfully.

Accessing a Database From a JSP Page:

Java Server Pages has Standard Tag Library which includes the number of actions for the database access to improve the simple database-driven Java Server Page applications. Basically, these actions are used to provide the following features:
a. Using a connection pool for better performance and scalability.
b. The features are to support the queries, updates, and insertion process.
c. To handle the most common data-type conversions.
d. To Support a combination of databases.
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

The Data Source Interface and JDBC Drivers:

Applications get access to the database through an instance of the Java Database Connectivity interface named javax.sql.DataSource. The DataSource interface is the part of Java 2 Standard Edition (J2SE) 1.4, and for prior versions of the Java2 Standard Edition. Opening a new database connection is very time-consuming. A nice thing with a DataSource is that it can represent something which is called a connection pool. Using the connection pool, a connection to the database is opened once and uses it again and again. Basically, a database action needs a connection; it gets it from the pool through the DataSource object and uses it to perform one or extra (Structure Query Language) SQL statements. In that position when the action closes the connection, the connection is returned to the pool where it can be used by the next action that needs it.

The DataSource, the Java Database Connectivity Application Programming Interface contains other classes and interfaces used by Java applications to process SQL statements in a database-independent way. For every database engine, an implementation of the interfaces defined by the Java Database Connectivity Application Programming Interface translates the generic calls to a format specific to the engine. This implementation is also called a JDBC driver. Through different drivers which provides the same interface allows us to develop our application on one platform (for illustration, in the following program a Personal Computer with an Access database), and then install the application on another platform (for illustration, a Solaris or Linux server with an Oracle database).

Illustrations show how to handle the embedded quotes in a string value, and how to deal with the input and output of date and time values, semantics for certain data types, and creation of unique numbers. The Java Server Pages Standard Tag Library actions take care of some of these, like as the string quoting and the date/time string format, so if we use these actions and stick to American National Standard Institute SQL, we should be able to voyage from one database to alternative database without too much modification. Basically, we should always read our database and documentation very judiciously and attempt to stay away from the proprietary things. So to be prepared, spend at least some time to read the prerequisite to interchange the application from one DB to another.

The context parameter of the value that contains four pieces of information is separated by commas: a JDBC URL, a JDBC driver class name, a database account name, and the account password.\

The Java Database Connectivity URL identifies a specific database. The different JDBC drivers use different Uniform Resource Locator syntax as per requirement. All the JDBC URLs starts with jdbc: and followed by a JDBC driver identifier [In JSP program we are discussing this], such as (Open database connectivity) odbc: for the JDBC-ODBC bridge driver and the MySQL for the most ordinarily used MySQL driver. The URL identifies the database instance in a driver-dependent way. If we use an Access database, we need to create a system DSN for the database using the Open database connectivity. In the Windows Control Panel, we must create a system DSN as opposed to a user DSN.

Point to be remembered that the web server that executes our JSP Pages usually runs as a different user account than the account you use for development. If you specify a user DSN with your development account, the web container will not be able to find it.

System Data Source Name definition Window And Working Process Are Given Below Step By Step:

a. At first, go to Control Panel and Open Administrative Tool.
b. After that Open ODBC driver by using double click on it.
c. Then click on the add button.

Figure 1: Add Data Source Window:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Figure 2: Provide Data Source Name “sgc” As Shown In The Figure:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Figure 3: Enter Database Name And Path Selection:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Figure 4: Set Data Source:
Java for Server Side Programming, Java Servlets, Servlet architecture, Servlet lifecycle, Parameter data, What is CGI (Common Gateway Interface)? Managing Session in Servlets, Cookies, URL Rewriting, HttpSession, Hidden form field Data storage, JSP technology, Introduction to JSP, JSP and servlet, Database Access, Database Programming using JDBC, Studying Javax.sql.* package, Accessing a Database from a JSP Page

Following the above process user can easily setup the DSN and this DSN is implemented at the program segment like the following
 Connection con=DriverManager.getConnection("jdbc:odbc:sgc","","");

Example Of Database Program Using JSP:

Here we will now discuss three sample examples like registerinsert.jsp, updateprogram.jsp and registrationsearch.html. These three programs are used for inserting record in the database, updating record in the database, searching record in the database. Here we are using a DSN process which we have already discussed above. Here we have also used MS Access database through which we set the DSN name “sgc”.

Listing 1: Sample Showing registerinsert.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Example of Java Server Page with JDBC</title>
    </head>
    <body>
<%
String u=request.getParameter("userid");
String p=request.getParameter("password");
String n=request.getParameter("sname");
String e=request.getParameter("eid");
String a=request.getParameter("addr");
try
{
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con=DriverManager.getConnection("jdbc:odbc:sgc","","");
/* Passing argument through the question mark */
      PreparedStatement ps=con.prepareStatement("insert into login values(?,?,?,?,?)") ;          ps.setString(1,u);
      ps.setString(2,p);
      ps.setString(3,n);
      ps.setString(4,a);
      ps.setString(5,e);
      int i=ps.executeUpdate(); /*Set the Update query command */
      if(i!=0)
     {                     
                  response.sendRedirect("index.jsp?msg=Thank You for registering with us in Mrbool !");
       }
     else
       {
                  response.sendRedirect("registerinsert.jsp?msg=Insertion Failed!! Please try again!!!   ");
     }
         con.close();
    }
    catch(Exception ex)
    {
        out.println(ex);
     }
%>
  </body>
</html>

Code Explanation:
a. The above code is used to insert a record into the database. Here we are accessing data from the entry form. After entering the data, the user can easily access the record through the get parameter method.

b. After that, we set odbc driver and through the DSN (Which is already discussed above) we link to the database.

c. Now the prepareStatement is used to pass the DML insert command. This command is used to store the record in the database.

d. Now we set the string at the particular database filed.

Listing 2: Sample Showing updateprogram.php
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
  <%
        String uid=(String)session.getAttribute("userid");
        String p=request.getParameter("password1");
        String n=request.getParameter("name1");
        String e=request.getParameter("eid");
        String a=request.getParameter("address");
        try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:sgs","","");
            PreparedStatement ps=con.prepareStatement("update login set password1=?,name1=?,eid=?,address=? where userid=?");
        ps.setString(1,p);
        ps.setString(2,n);
        ps.setString(3,e);
        ps.setString(4,a);
        ps.setString(5,uid);
        int i=ps.executeUpdate();
            if(i!=0)
            {
                response.sendRedirect("index.jsp?msg=Mrbool Profile Updated Successfully!!!!!!!");
            }
            else
            {
                response.sendRedirect("pUpdate.jsp?msg=Mrbool  Profile Updation Failed Please Try again!!!!");
            }
     con.close();
        }
    catch(Exception ex){
        out.println(ex);
        }
    %>
    </body>
</html>

Code Explanation:
a. This program mostly works as per the previous system procedure model. Through this program model we can develop a data uploading structure.

b. Here we use the update command. This update command passes data through a unique value.

c. After that, if the updating is executed successfully, and then it will redirect the page.

This is the searching program. Through this program model, we can search for all the data that is already present in the database.

Listing 3: Sample Showing registrationsearch.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page import="java.sql.*,java.util.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Photo gallery</title>
<link rel="stylesheet" type="text/css" href="style.css" />

</head>
<body>
<div id="Layer9">
<%
  String msg=request.getParameter("msg"); 
 
  if(msg!=null)
  {
     out.print("<h1>"+"Welcome "+(String)session.getAttribute("u")+"</h1>");
      out.print(msg);
      }
  %>
</div>
<div id="wrap">
<%
     String uid=(String)session.getAttribute("u");
             if(uid==null)
              {  
    %> <div class="header">
                  <div class="logo"><a href="index.jsp"><img class='imagem_artigo' src="images/pg.gif" width="294" height="73" /></a></div>           
        <div id="menu">
            <ul>                                                                      
            <li class="selected"><a href="index.jsp" class="style12">home</a></li>
            <li><a href="aboutus.jsp" class="style12">about us</a></li>
            <li><a href="gallery.jsp" class="style12">Gallery</a></li>
           
            <li><a href="myaccount.jsp" class="style12">log in</a></li>
            <li><a href="register.jsp" class="style12">register</a></li>
            <li></li>
            <li></li>
          
            </ul>
        </div>    
        <%}
      else
          {
     %>    <div class="header">
                  <div class="logo"><a href="index.jsp"><img class='imagem_artigo' src="images/pg.gif" alt="" title="" border="0" /></a></div>
        <div id="menu">
            <ul>                                                                      
            <li class="selected"><a href="index.jsp" class="style12">home</a></li>
            <li><a href="aboutus.jsp" class="style12">about us</a></li>
            <li><a href=" gallery.jsp" class="style12">Gallery</a></li>
            <li><a href="photoFormupdate.jsp" class="style12"> Upload iamges </a></li>
            <li><a href="pUpdate.jsp"><span class="style12">Update Profil</span>e</a></li>
            <li><a href="logOut.jsp" class="style12">logout</a></li>
            <li></li>
            </ul>
        </div>
<%
   }
%>           
       </div>
            <div class="center_content">
         <div id="Layer2">         </div>
         <div id="Layer8">
             <div class="footer"></div>
       </div>      
         <div class="new_products"></div>
           <div class="clear"></div>
  </div>
 
<div class="clear"></div>
</div>
<div id="Layer4">
 <h1>Photo Gallery</h1>
</div>
<div id="Layer5">

   <span class="style4"><font face="Algerian" size="5">Images By Category</font></span> 
    ::<br />
<font size="3" face="Courier" color="#CC0033" align="center">
</font><font size="3" color="#CC0033" align="center"><span class="style12"><a href=" registrationsearch.jsp?Category=Nature">Nature</a><br />
<a href=" registrationsearch.jsp?Category=Sports">Sports</a><br />
<a href=" registrationsearch.jsp?Category=Baby">Baby</a><br />
<a href="search.jsp?Category=Animals">Animals</a></span></font><font size="3" face="Courier" color="#CC0033" align="center"><br />
 </font></div>
<div id="Layer7">
<% 
      String cat=request.getParameter("Category");
   int i=0;
    ArrayList ar=new ArrayList();  // This part is used for creating new array list.
    ArrayList pi=new ArrayList();           
                try{
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    Connection cn=DriverManager.getConnection("jdbc:odbc:sgc","","");
    
                  PreparedStatement ps=cn.prepareStatement("select * from photoDetails where pct=?");
                    ps.setString(1,cat);
                    ResultSet rs=ps.executeQuery();
                    while(rs.next())
{
                      i++;
                        String pUrl02=rs.getString(5).trim();
                        String pUrl2=pUrl02.substring(pUrl02.lastIndexOf("\\")+1);
                        ar.add(pUrl2);
                       pi.add(rs.getString(1));
                     }
    out.print(i+cat);
                        cn.close(); /*Close the connection*/
                }
                catch(Exception e){
                    out.println(e);
                    }
 %>
     <table bgcolor="orange" border="5" width="550" height="220">
               <%  int j=0,k=0,t=0;
                while(k<4)
                {  %>
                       <tr>
                        <%
                        j=0;
                        while(j<3 && j+t<i)
                        { %>
                        <td> <a href="index.jsp?msg=<%=pi.get(j+t)%>"><img class='imagem_artigo' src="<%=(String)ar.get(j+t)%>" alt=""  height="200" width="200"/></a>
                                               <%
                      
                        j++;
                        }
                        %>
                       
                    </tr>
             <%
                  t+=3;
                
                  k++;
                   }
                  %>
  </table>
</div>
</body>
</html>

Listing 4: CSS
#Layer1 {
      position:absolute;
      width:200px;
      height:115px;
      z-index:1;
      left: 751px;
      top: 186px;
      background-color: #993399;
}
#Layer2 {
      position:absolute;
      width:897px;
      height:1174px;
      z-index:1;
      left: 261px;
      top: 181px;
      background-color: #9900CC;
}

#Layer4 {
      position:absolute;
      width:891px;
      height:132px;
      z-index:3;
      left: 264px;
      top: 182px;
      background-color: #009900;
}
#Layer5 {
      position:absolute;
      width:217px;
      height:266px;
      z-index:4;
      left: 939px;
      top: 318px;
      background-color:  #FC3;
}
#Layer6 {
      position:absolute;
      width:678px;
      height:508px;
      z-index:5;
      left: 145px;
      top: 334px;
}
#Layer7 {
      position:absolute;
      width:673px;
      height:1038px;
      z-index:5;
      left: 263px;
      top: 316px;
      background-color: #CCCCCC;
}
#Layer8 {
      position:absolute;
      width:898px;
      height:107px;
      z-index:6;
      left: 262px;
      top: 1240px;
      background-color: #EFEFEF;
}
#Layer9 {
      position:absolute;
      width:429px;
      height:79px;
      z-index:7;
      left: 421px;
      top: 232px;
}

.style2 {
      font-family: Algerian;
      color: #000000;
}
.style4 {color: #000000}
.style12 {font-family: algerian}

Code Explanation:
a. This is the searching program.

b. Select query is used here for searching the record. Here we are searching picture wise.

c. rs is the ResultSet in the program segment. Through the result set process, we can easily search the record.

No comments:

Post a Comment

If you have any doubt, then don't hesitate to drop comments.