JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com





Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








ServletConfig And ServletContext

ServletConfig
  • This is an interfae
  • It is used to provide initialization information to the servlet.
  • There is one servletconfig for one servlet.
  • It has these Mthods
    • public java.lang.String getServletName()
    • public ServletContext getServletContext() 
    • public Enumeration getInitParameterNames() 
    • public String getInitParameter(String name)
  • Servlet get its Initilialization Information from web.xml
  • Inside the <servlet> tag for the given servlet in web.xml  :
    • Add <init-param> tag
  • For each <init-param> tag
    there is one <param-name> and <param-value>
                        
<init-param> 
       <param-name>myName</param-name>
       <param-value>myValue</param-value>
 </init-param>

In the Servlet Code
get this parameter value by the getInitParameter(param-name) method.

String myValue = getServletConfig().getInitParameter("myName");


Example

  • In the given example  we are getting the name and age value from the web.xml
  • It is easy to change the value in the web.xml.
  • If the variable value is given in the servlet file it will require compilation every time.
  • But it can be changed easily in the web.xml
  • Changing in web.xml  doesnot require any compilation.

  • First we will create a servlet file.
  • Save it as UserInfo.java
  • Add the two instance variable name and age.
  • Get these values in init() method

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

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

public class UserInfo extends HttpServlet {
  private static final long serialVersionUID = 1L;

  String name;
  String age;

  @Override
  public void init(ServletConfig configthrows ServletException {
    name = config.getInitParameter("name1");
    age = config.getInitParameter("age1");

  }

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
        
    out.print("name is " + name);
    out.print("<br>age is " + age);
  }

}


  • Now create web.xml file inside WEB-INF folder.
  • Inside the <servlet> atg after <servlet-class>

    add the <init-param> tag
    then add the <param-name> and <param-value> as shown below
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>UserInfo</servlet-name>
    <servlet-class>UserInfo</servlet-class>
 
    <init-param>
    <param-name>name1</param-name>
    <param-value>sohan</param-value>
    </init-param>
 
    <init-param>
    <param-name>age1</param-name>
    <param-value>22</param-value>
    </init-param>
 
  </servlet>
 
  <servlet-mapping>
    <servlet-name>UserInfo</servlet-name>
    <url-pattern>/UserInfo</url-pattern>
  </servlet-mapping>
</web-app>

  • Now run the servlet.
  • It fetches the value from the web.xml.





Now we will chnage the value for each parameter.


<init-param>
    <param-name>name1</param-name>
    <param-value>rohan</param-value>
</init-param>
 
<init-param>
    <param-name>age1</param-name>
    <param-value>32</param-value>
</init-param>


Then run the servlet again.
It will give the chnaged value.






getInitParameterNames()

  • This method returns the all parameter names from the web.xml
  • It returns the values in the form of Enumeration.
  • These names can be retrieved  using hasNext() method.
  • Using getParameter() method  all values can also be retrieved.

Example

  • Create one servlet
  • Save it as AllInfo.java
  • Add the code to get all the parameter names from the web.xml
  • Add the code to retrieve all values using getInitParameter() method.

01 import java.io.IOException;
02 import java.io.PrintWriter;
03 import java.util.Enumeration;
04 
05 import javax.servlet.ServletConfig;
06 import javax.servlet.ServletException;
07 import javax.servlet.http.HttpServlet;
08 import javax.servlet.http.HttpServletRequest;
09 import javax.servlet.http.HttpServletResponse;
10 
11 public class AllInfo extends HttpServlet {
12   private static final long serialVersionUID = 1L;
13 
14   protected void doGet(HttpServletRequest request,
15       HttpServletResponse responsethrows ServletException, IOException {
16 
17     PrintWriter out = response.getWriter();
18     response.setContentType("text/html");
19 
20     ServletConfig sc = getServletConfig();
21 
22     Enumeration<String> en = sc.getInitParameterNames();
23 
24     while (en.hasMoreElements()) {
25       String st = en.nextElement();
26       out.print("<br>" + st + "------" + sc.getInitParameter(st));
27     }
28 
29   }
30 
31 }

web.xml


01   <servlet>
02     <servlet-name>AllInfo</servlet-name>
03     <servlet-class>AllInfo</servlet-class>
04     <init-param>
05       <param-name>Disease</param-name>
06       <param-value>Fever</param-value>
07     </init-param>
08     <init-param>
09       <param-name>medicine</param-name>
10       <param-value>Paracetamol</param-value>
11     </init-param>
12   </servlet>
13 
14   <servlet-mapping>
15     <servlet-name>AllInfo</servlet-name>
16     <url-pattern>/AllInfo</url-pattern>
17   </servlet-mapping>


output




Output
Download the eclipse zip code


ServletContext

  • This is an interface.
  • It is used to communicate with ServletContainer.
  • Due to this there is on;y one servletContext for the whole project/application.
  • It is used to
    • set the attribues for application level
    • and get the initialization parameter values from web.xml
  • It is used to
    • get the MIME type of a file
    • get dispatch requests
    • and  write to a log file

Context init parameters

  • Like servletconfig paramter there is servlet context parameter .
  • This is called as contextParameter.
  • These parameters are defined in the web.xml.

It  can send configuration information to all servlets in a web application


Configuration in the web.xm
l

  • Outside all the <servlet> tag
  • Add the <context-param>
    • Inside <context-param> tag add the
      <param-name>
      <param-value>

<context-param>
    <param-name>myName</param-name> 
      <param-value>myValue</param-value>
</context-param

In any Servlet
  • get this value by the getInitParameter() method.

String myValue =getServletContext().getInitParameter("myName");

                ServletConfig paramter  vs. contextInit parameters

Servlet init parameters are:

  • Defined within a <servlet> tag
  • Written within an<init-param> tag
  • Retrieved from a ServletConfig object, which you get by calling getServletConfig()
  • Read from the ServletConfig object by calling getInitParameter(name)
Context init parameters are:

  • Defined outside all <servlet> tags
  • Written within a <context-param> tag
  • Retrieved from a ServletContext object, which you get by calling getServletContext()
  • Read from the ServletContext object by calling getInitParameter(name)

Methods of the ServletContext

Public ServletContext methods

  • String getInitParameter(String name)
  • Enumeration getInitParameterNames()
  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • void setAttribute(String name, Object object)
  • void removeAttribute(String name)
  • String getRealPath(String path)<input type="hidden" name="sessionID" value="..."><input type="hidden" name="sessionID" value="...">
  • RequestDispatcher getRequestDispatcher(String path)

Example

  • In the given example we are retrieving the init parameter values from  web.xml.
  • This is done with getInitParameter() method.
  • We have added one attribute capital with attribute value as  new delhi.
  • context.setAttribute() sets the value to application scope.
  • This attribute value can be retrieved from any  servlet
  • This is done with the cotext.getAttribute() method..

MyContext1.java

  • Create one servlet.
  • Save it as MyContext1.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyContext1 extends HttpServlet {

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException,
IOException 
{

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    ServletContext sc = getServletContext();
    sc.setAttribute("capital""new delhi ");
    out.print("<br>country name is " + sc.getInitParameter("country"));

    out.print("<br>company name is " + sc.getInitParameter("cname"));

  }
}
Download Code

web.xml

  • Create web.xml inside the WEB-INF
  • Add the <context-param> tag after th <web-app> tag.
  • Inside the <context-param> tag
    add the <param-name> and <param-value>
<web-app>
<context-param>
    <param-name>country</param-name>
    <param-value>india</param-value>
  </context-param>
  <context-param>
    <param-name>cname</param-name>
    <param-value>HCL</param-value>
</context-param>
 <servlet>
    <display-name>MyContext1</display-name>
    <servlet-name>MyContext1</servlet-name>
    <servlet-class>MyContext1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyContext1</servlet-name>
    <url-pattern>/MyContext1</url-pattern>
  </servlet-mapping>
 
</web-app>




Output

  • Run the MyContext1 Servlet
  • It retrieves the value from the web.xml and sets the attribute value..





getInitParameterNames()

  • This method returns the all parameter names from the web.xml
  • It returns the values in the form of Enumeration.
  • These names can be retrieved  using hasNext() method.
  • Using getParameter() method  all values can also be retrieved.

In this example we are retrieving all the values from the web.xml.
We also get the value that has been set by the setAttribute() method
   in the MyConetxt1.java
ContextValues.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;

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

public class ContextValues extends HttpServlet {

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
throws 
ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    ServletContext sc = getServletContext();

    Enumeration e1 = sc.getInitParameterNames();

    while (e1.hasMoreElements()) {
      Object obj = e1.nextElement();
      out.print("<br>" + obj + "  =======   "
          + sc.getInitParameter(obj.toString()));

    }
out.println("capital is " + sc.getAttribute("capital"));
      }

}
OutPut




Download Zip Code






Another Example

Mydata.java

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

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

public class Mydata extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Statement st;
    Connection con;
    ResultSet rs;

    ServletContext sc = getServletContext();

    String driver = sc.getInitParameter("driver");
    String url = sc.getInitParameter("url");
    String user = sc.getInitParameter("user");
    String password = sc.getInitParameter("password");

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, user, password);
      st = con.createStatement();
      rs = st.executeQuery("select * from stud");

      while (rs.next()) {
        out
            .println("<br>" + rs.getInt(1"  "
                + rs.getString("name"));
      }

    catch (SQLException e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      // 
    }

  }

}
Download code

web.xml
<web-app>
<context-param>
    <param-name>driver</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>user</param-name>
    <param-value>system</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>manager</param-value>
  </context-param>
</web-app>


Download Zip code

Output

Fetching data from database dynamically into the servlet...