Sunday, December 24, 2017

javax.servlet.ServletConfig interface detail

ServletConfig is an interface of servlet API. Implementation of which is provided by vendors. An object of type ServletConfig is created by the server for each servlet.
This object has following use:
1- It is used by the server to provide Servlet specific initialization parameter to
    Servlets. 
2- It is used by the server to provide reference of the ServletContext object to the Servlet.


2.2- ServletConfig object is created for the Servlet.
2.3- <init-param> (if define for the Servlet) are read and store in it.
2.4- Reference of ServletContext is saved in it.
3.0- Server call the init() method of Servlet and provide the reference of ServletConfig.

Method of javax.servlet.ServletConfig interface:

1- getServletContext():
                                      Is used to obtain reference of ServletContext object.
    public ServletContext getServletContext();

2- getInitParameter():
                                      Is used to obtain the values of initialization parameter.
    public String getInitParameter(String PName);

3- getInitParameterNames():
                                      Is used to obtain the name of initialization parameters.
    public Enumeration getInitParameterNames();

Example 1- program to access ServletConfig initialization parameter (Which is Servlet scope) 

Program save with Name: index.html

<html>
<head><title>Login Page</title></head>
<body>
<form method="get" action="loginServlet">
UserId : <input type="text" name="txtUserId"><br>
Password : <input type="password" name="txtPassword"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Program save with Name: LoginServlet.java

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

public class LoginServlet extends HttpServlet
{
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          {
                   try
                   {
                   response.setContentType("text/html");
                   PrintWriter out=response.getWriter();
                   String id=request.getParameter("txtUserId");
                   String pwd=request.getParameter("txtPassword");
                   ServletConfig cnf=getServletConfig();
                   /* First get ServletConfig object reference Because
                      ServletConfig object contains the Servlet scope initilization parameter <init-param> */
                   Class.forName(cnf.getInitParameter("driverName"));
                   Connection con=DriverManager.getConnection(cnf.getInitParameter("url"),cnf.getInitParameter("userName"),cnf.getInitParameter("password"));
                   PreparedStatement stmt=con.prepareStatement("select * from userInfo where id=? and password=?");
                   stmt.setString(1,id);
                   stmt.setString(2,pwd);
                   ResultSet rset=stmt.executeQuery();
                   if(rset.next())
                   {
                             out.println("<b>Welcome, "+rset.getString(2)+"</b>");
                   }
                   else
                   {
                             out.println("<b> Invalid UserId or Password....<b><br>");
                             RequestDispatcher rd=request.getRequestDispatcher("/index.html");
                             rd.include(request,response);
                   }
                   con.close();
                   out.close();
                   }
                   catch(Exception e)
                   {
                             System.out.println(e);
                   }
          }
}
Program save with Name: web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>LoginServlet</servlet-class>

<init-param>
<param-name>driverName</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>

<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>

<init-param>
<param-name>userName</param-name>
<param-value>system</param-value>
</init-param>

<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>loginServlet</url-pattern>
</servlet-mapping>

</web-app>
Output :

If valid userId and password then display:      
Welcome, rupendra

If invalid userId or password then display:      
Invalid UserId or Password....
and include index.html page



javax.servlet.ServletContext interface detail


ServletContext is an interface of Servlet API. Implementation of it provided by the vendors. An object of type ServletContext is created by the server per application at the time of application deployment.
This object has following use:
1- It is used by the server to store application specific initialization parameters.
2- It is used by the Servlet to share information among them self in the form of
    attributes.

3- It is used by the Servlet to interact with the server that is it has interface of the server.


1.1- ServletContext object is created by the server for the application.
1.2- <context-param> defined in web.xml are read and stored in ServletContext 
    object.
1.3- Server provides its own reference to the ServletContext object.
2.0- Servlet read application scope initialization parameters.
2.1- Servlet share information among themselves across requests as attributes.
2.2- Servlets use ServletContext object as interface of the server i.e. information is requested from the server with the help of ServletContext object. 

Method of javax.servlet.ServletContext interface:

1- getInitParameter():
                                      Is used to obtain the values of initialization parameter.
    public String getInitParameter(String PName);

2- getInitParameterNames():
                                      Is used to obtain the name of initialization parameters.
    public Enumeration getInitParameterNames();

3- setAttribute():
                          Is used to store an attribute in the application scope.
    public void setAttribute(String name, Object value);

4- getAttribute():
                            Is used to obtain the value of an attribute.
    public Object getAttribute(String name);

5- getAttributeNames():
                                       Is used to obtain the name of attributes.
    public Enumeration getAttributeNames();

6- removeAttribute():
                                  Is used to remove the attribute from the application scope.   
    public boolean removeAttribute(String name);

7- getContext():
                          Is used to obtain reference of ServletContext object of the given
    application.
    public ServletContext getContext(String AppName);

8- getRequestDispatcher():
                             Is used to obtain a RequestDispatcher object.
    public RequestDispatcher getRequestDispatcher (String URL);


Example 1- program to access ServletContext initialization parameter (Which is Application scope)  

NOTE: This is first use of ServletContext object
Program save with Name: index.html

<html>
<head><title>Login Page</title></head>
<body>
<form method="get" action="loginServlet">
UserId : <input type="text" name="txtUserId"><br>
Password : <input type="password" name="txtPassword"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Program save with Name: LoginServlet.java

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

public class LoginServlet extends HttpServlet
{
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          {
                   try
                   {
                   response.setContentType("text/html");
                   PrintWriter out=response.getWriter();
                   String id=request.getParameter("txtUserId");
                   String pwd=request.getParameter("txtPassword");
                   ServletContext ctx=getServletConfig().getServletContext();
                   /* First get ServletConfig object reference and then get ServletContext                           object Because ServletConfig object contain the reference of 
                          ServletContext object and ServletConfig object reference is
                          provided to Servlet by the server in initilization time init()  */
                   Class.forName(ctx.getInitParameter("driverName"));
                   Connection con=DriverManager.getConnection(ctx.getInitParameter("url"),ctx.getInitParameter("userName"),ctx.getInitParameter("password"));
                   PreparedStatement stmt=con.prepareStatement("select * from userInfo where id=? and password=?");
                   stmt.setString(1,id);
                   stmt.setString(2,pwd);
                   ResultSet rset=stmt.executeQuery();
                   if(rset.next())
                   {
                             out.println("<b>Welcome, "+rset.getString(2)+"</b>");
                   }
                   else
                   {
                             out.println("<b> Invalid UserId or Password....<b><br>");
                             RequestDispatcher rd=request.getRequestDispatcher("/index.html");
                             rd.include(request,response);
                   }
                   con.close();
                   out.close();
                   }
                   catch(Exception e)
                   {
                             System.out.println(e);
                   }
          }
}
Program save with Name: web.xml

<web-app>

<context-param>
<param-name>driverName</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>

<context-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</context-param>

<context-param>
<param-name>userName</param-name>
<param-value>system</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>loginServlet</url-pattern>
</servlet-mapping>

</web-app>
Output :

UserId :
Password :

If valid userId and password then display:      
Welcome, rupendra

If invalid userId or password then display:      
Invalid UserId or Password....
UserId :
Password :



Initialization Parameters in servlet

Initialization parameter represents variable textual information that is define by application developer in web.xml file and is made available to the Servlets by the web server. 


Initialization parameter can be of 2 types:
1- Application specific
2- Servlet specific

1- Application specific:
                                     
Application specific initialization parameters represent textual information that is to be made available to all the Servlet of the application.
<context-param> xml element is used for defining application specific initialization parameter in web.xml.

<web-app>

<context-param>*
<param-name>ParameterName</param-name>
<param-value>ParameterValue</param-value>
</context-param>

------------------------
------------------------

<servlet>*
-------------------------
-------------------------
</servlet>

<servlet-mapping>*
-----------------------
------------------------
</servlet-mapping>

--------------------------------------
--------------------------------------
</web-app>
Note:
* denotes optional


2- Servlet specific:
                             Servlet specific initialization parameter represent information that is to be make available only to a single Servlet for which it is define.
<init-param> sub element of Servlet is used to define Servlet specific initialization parameter in web.xml.

<web-app>
---------------------------
---------------------------
<servlet>*
<servlet-name>UniqueIdentifier</servlet-name>
<servlet-class>ServletClassName</servlet-class>
<init-param>*
<param-name>ParameterName</param-name>
<param-value>ParameterValue</param-value>
</init-param>
</servlet>

<servlet-mapping>*
<servlet-name> UniqueIdentifier</servlet-name>
<url-pattern>UrlPatternRequestedByUser</url-pattern>
</servlet-mapping>

----------------------------
----------------------------
</web-app>
Note:
* denotes optional


Note:
Let us know how server provides these initialization parameters to Servlets?
Answer is, with the help of following interfaces:
1- ServletContext   (Application Scope)
2- ServletConfig     (Servlet Scope)



Login Authentication program (Demonstrate the use RequestDispatcher and its method such as include() and forward() )



Create Table with following field:
TableName: USERINFO
id                    name                 password
101                 rupendra            a@b.com
102                 rahul                  x@y.com

Program save with Name: index.html

<html>
<head><title>Login Page</title></head>
<body>
<form method="get" action="loginServlet">
UserId : <input type="text" name="txtUserId"><br>
Password : <input type="password" name="txtPassword"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Program save with Name: LoginServlet.java

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

public class LoginServlet extends HttpServlet
{
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          {
                   try
                   {
                   response.setContentType("text/html");
                   PrintWriter out=response.getWriter();
                   String id=request.getParameter("txtUserId");
                   String pwd=request.getParameter("txtPassword");
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
                   PreparedStatement stmt=con.prepareStatement("select * from userInfo where id=? and password=?");
                   stmt.setString(1,id);
                   stmt.setString(2,pwd);
                   ResultSet rset=stmt.executeQuery();
                   if(rset.next())
                   {
                             out.println("<b>Welcome, "+rset.getString(2)+"</b>");
                   }
                   else
                   {
                             out.println("<b> Invalid UserId or Password....<b><br>");
                             RequestDispatcher rd=request.getRequestDispatcher("/index.html");
                                    rd.include(request,response);
                   }
                   con.close();
                   out.close();
                   }
                   catch(Exception e)
                   {
                             System.out.println(e);
                   }
          }
}

Program save with Name: web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>loginServlet</url-pattern>
</servlet-mapping>

</web-app>
Output :
UserId :
Password :

If valid userId and password then display:      
Welcome, rupendra

If invalid userId or password then display:      
Invalid UserId or Password....
UserId :
Password :

RequestDispatcher interface

RequestDispatcher is a interface of Servlet API. Implementation of which provided by vendors. This interface provides methods for including contents of a resource (Such as Servlet/html page etc.) to the response of current Servlet or forward the request to another web resource(Such as Servlet/html page etc.).

Methods:
1- getRequestDispatcher():
                                              
Method of ServletRequest interface is used to obtain a RequestDispatcher object.
public RequestDispatcher getRequestDispatcher(String URL of Resource);

RequestDispatcher interface provides include() and forward() method for including contents of a resource and to forward the request to another response respectively.

I) include():
                  Is used to include the content of the resource to the response of the current Servlet.
public void include(ServletRequest, ServletResponse) throws ServletException, IOException;

II) forward():
                     
Is used to forward request to another resource.
public void forward(ServletRequest, ServletResponse) throws ServletException, IOException;


Note:
Real life example (Cases for request handling):
Assume counselor is acts as a Servlet
Case1:
Self give result if any one ask about course CourseName/fee/CourseDuration.
Case2:
For Some technical Enquiry (such as version of hibernate) ask the Technical Trainer ( Take a Help of another person on same enquiry)  and then give the information (result).
Case3:
Forward the call direct to the Trainer (Now information (result) is produce by Trainer) .

Program to access word and Excel document (Demonstrate the use of ServletRequest and ServletResponse methods such as setContentType())

Program save with Name: index.html

<html>
<head><title>Downloading Program</title></head>
<body>
<a href="wordServlet">Ms-Word-Document</a><br>
<a href="excelServlet">Ms-Excel-Document</a>
</body>
</html>

Program save with Name: WordServlet.java

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

public class WordServlet extends HttpServlet
{
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          {
                   response.setContentType("application/msword");
                   PrintWriter out=response.getWriter();
                   out.println("This document is dynamically generated by the servlet");
                   out.println("Its purpose to demostrate the use of content type.");
                   out.close();
          }
}
Program save with Name: ExcelServlet.java

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

public class ExcelServlet extends HttpServlet
{
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          {
                   response.setContentType("application/vnd.ms-excel");
                   PrintWriter out=response.getWriter();
                   out.println("Name\t Job\t Salary");
                   out.println("Aman\t Trainer\t 5000");
                   out.println("Deepak\t Excutive\t 5000");
                   out.println("Rahul\t Mnage\t 5000");
                   out.println("\t Total Salary\t=sum(c2:c4)");
                   out.close();
          }
}
Program save with Name: web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WordServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>wordServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>ExcelServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>excelServlet</url-pattern>
</servlet-mapping>

</web-app>
Output :
Click on Hyperlink to access or download word and excel document.

Java Functional Interface

Java Lambda expression Lambda expression came to enable to use functional programming feature in java. It provides the facility t...