Sunday, December 24, 2017

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 :



No comments:

Post a Comment

Java Functional Interface

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