load-on-startup is a tag element which appear inside servlet tag in web.xml.load-on-startup tells the web container about loading of a particular servlet. if you don’t specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connection which contribute network latency or time consuming job.

 <servlet>
   <servlet-name>StartUpServlet</servlet-name>
   <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>

Points to remember

  • If load-on-startup value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
  • If load-on-startup is 0 or negative integer than Servlet will be loaded when Container feels to load them.
  • load-on-startup guarantees loading, initialization and call to init() method of servlet by web container.
  • If there is no load-on-startup element for any servlet than they will be loaded when web container decides to load them.

Lower the value of load-on-startup, servlet will be loaded first.

Use during Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache, clearing pipelines and loading important data in memory

Filters are helpful in performing filter functionality in Java web application Application. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

A filter is used to perform a particular task either before or after the actual functionality of a web application is performed. For example, if a request is made for a particular resource such as a Servlet in web application and a filter is used, the filter code may execute and then pass the user on to the Servlet. The filter may run a check before letting the user to the actual page.The filter checks the user permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Below is a code which shows the filter in web.xml file

web.xml

 <webapp>
  <filter>
    <filter-name>SampleFilter</filter-name>
    <filter-class>com.mugil.filter.TestFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SampleFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  </web-app>

Filter code is java is as below
TestFilter.java

public class TestFilter implements Filter 
{
  public void init(FilterConfig fConfig) throws ServletException 
  {
     System.out.println("Filter Initialized");
  }
  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
  {	
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("Filter Executed");		
     chain.doFilter(request, response);
  }

  public void destroy() 
  {
    System.out.println("Filter Destroyed");
  }
}

The init() method will be executed every time the server starts.The doFilter method is executed every time a Servlet or JSP page is accessed in the context.Filter destroy() method is called when the server is stopped.

context – circumstances that form the setting for an event.For our scenario context represents virtual host within which our web application runs.The environment where the WAR file is deployed.

Below is an Example of File which stores variable in context.xml and is available for the whole application.The context.xml file contains the default Context element used for all web applications in the system.

context.xml

  <Context>      
     <Parameter name="companyName" value="My Company, Incorporated"/>
  </Context>

The same thing can be defined in the web.xml file as below
web.xml

  <context-param>
     <param-name>companyName</param-name>
     <param-value>My Company, Incorporated</param-value>
   </context-param>

To access the context variable in Servlet you can use the following code in doGet() Method as below
Test.java

 
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
  ServletContext servletContext = getServletContext();		  
  PrintWriter out = response.getWriter();
  out.print(servletContext.getInitParameter("companyName"));  
}

Case1: The context variable in web.xml will have highest priority than context.xml in server and application if override attribute is set to true or if it is undefined.

Case2: Defining a context variable in $CATALINA_BASE/conf/context.xml and context.xml file inside your application the former will have more privilege.

Declaring context attributes in web.xml is better since they will work when you deploy your app in other App Servers other than Tomcat.

What is Context Path
A web applications context path is the directory that contains the web applications WEB-INF directory.It points to WebContent directory in your project.

Server context path is the one which tells the location where the WebContent directory is placed during project deployment in server.The following code tells you how to find server context path.

Test.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
{	
   ServletContext servletContext = getServletContext();		
   String contextPath = servletContext.getRealPath(File.separator);
   PrintWriter out = response.getWriter();
   out.println("<br/>Context path: " + contextPath);
}  

The above code outputs some directory within tomcat folder like one below
Output

Context path:  D:\Tomcat\wtpwebapps\CustomTag\ 

In my case D:\Tomcat\ is where my tomcat is installed and wtpwebapps\ is the context where my project
\CustomTag\ is deployed

CustomTags.java
This is the File which defines the Property of the Tag

package com.mugil.custTags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class CustomTags extends TagSupport  
{
  private static final long serialVersionUID = 1L;
	
  public int doStartTag() throws JspException 
  {		
     StringBuffer SamBuffer = new StringBuffer();
     SamBuffer.append("Sample Message");
		
     try
     {
	pageContext.getOut().write(SamBuffer.toString());
     }
     catch (IOException e)
     {
	e.printStackTrace();
     }
		
  	return EVAL_PAGE;
   }
	
   public int doEndTag() throws JspException 
   {
      return EVAL_PAGE;
   }
}

DisplayName.tld
This xml file creates the Relation between the tag and the property of the tag as defined in the java file.

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <shortname>Example TLD</shortname>
  <tag>
    <name>Hello</name>
    <tagclass>com.mugil.custTags.CustomTags</tagclass>
    <bodycontent>empty</bodycontent>
  </tag>
</taglib>

Sample.jsp
JSP File in which the custom tag is Used.

<%@taglib prefix="DisplayName" uri="/WEB-INF/tld/DisplayName.tld"%>
.
.
.
.
<body>
 <h1>
    <DisplayName:Hello/>
 </h1>
</body>
.
.
.

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0">
   <servlet>
     <servlet-name>TestServlet</servlet-name>
     <servlet-class>com.mugil.custTags.TestServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>TestServlet</servlet-name>
     <url-pattern>/TestServlet/</url-pattern>
   </servlet-mapping>
  </web-app>

Output

OP

c:forEach

 <body>
   <c:forEach var="i" begin="1" end="100">
     <c:out value="${i}"/><br/>
   </c:forEach>
 </body>

Accessing Value in Bean
SampleMenu.java(bean)

  public class SampleMenu
  {
    String name;
  
    public String getName()
    {
      return name;
    }
	
    public void setName(String name)
    {
      this.name = name;
    }
  }

MenuList.java

   List<SampleMenu> arrMenuList = new ArrayList<SampleMenu>();		
   SampleMenu objSampleMenu     = new SampleMenu();

   objSampleMenu.setName("Link1");
   arrMenuList.add(objSampleMenu); 

   objSampleMenu.setName("Link2");
   arrMenuList.add(objSampleMenu);

   objSampleMenu.setName("Link3");
   arrMenuList.add(objSampleMenu);

   request.setAttribute("arrMenuList", arrMenuList);
   RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
   dispatcher.forward(request, response);

Sample.java

 
   <body>
     <c:forEach	var="i" items="${arrMenuList}">
	     <c:out value="${i.name}"/>
     </c:forEach>
   </body>

Output
Link1 Link2 Link3

If Else

 
<c:if test="${user.userGender eq 1}">Male</c:if>
<c:if test="${user.userGender eq 0}">Female</c:if>

(or)

 
  <c:choose>
    <c:when test="${user.userGender eq 1}">Male</c:when>
    <c:otherwise>Female</c:otherwise>
  </c:choose>

Alternative to If Else Statement

 
 <c:out value="${user.userGender eq 1 ? 'Male': 'Female'}"/>

If Else If

<c:choose>
    <c:when test="${empty example1}"> 
        <!-- do stuff -->
    </c:when> 
    <c:otherwise> 
        <c:choose>
            <c:when test="${empty example2}"> 
                <!-- do different stuff -->
            </c:when> 
            <c:otherwise> 
                <!-- do default stuff -->
            </c:otherwise>
        </c:choose>
    </c:otherwise> 
</c:choose>

If Else If

<c:choose>
    <c:when test="${empty example1}">
    </c:when>
    <c:when test="${empty example2}">
    </c:when>
    <c:otherwise>
    </c:otherwise>              
</c:choose>

Passing a Variable from Java to JSP Page By SetAttribute

Sample.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
  request.setAttribute("Name", "Mugil Vannan");
  RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
  dispatcher.forward(request, response);
}

Sample.jsp

  <body>
    <c:out value="${Name}"/>
  </body>

Web.xml

  <servlet>
     <servlet-name>Sample</servlet-name>
     <servlet-class>com.sponsor.infonovum.MenuList</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>Sample</servlet-name>
     <url-pattern>/Sample/</url-pattern>
  </servlet-mapping>
protected void doGet(HttpServletRequest request, 
                     HttpServletResponse response) 
                     throws ServletException, IOException 
{	
   int lngCookieSet    = 0;
   String strCookieVal = "";
   String cookieName   = "Name";
	
   Cookie[] cookies = request.getCookies();
		
   if(cookies != null && cookies.length > 0)
   {
      for(int i=0;i<cookies.length;i++)
      {
        if(cookieName.equals(cookies[i].getName()))
        {
          lngCookieSet = 1;
          strCookieVal = cookies[i].getValue();
        }
      }
   }	
		
   if(lngCookieSet == 1)
   {
     PrintWriter prw = response.getWriter();	
     prw.print(strCookieVal);
   }
   else
   {
     Cookie cook = new Cookie("Name", "Mugil");
     cook.setMaxAge(24*60*60*365);//1 Year
     response.addCookie(cook);	
   }
}

Notes
1. check cookies != null otherwise the compiler will generate null pointer exception
2. The new Cookie constructor will take Cookie Name and Value as Parameter.
3. The addCookie Will add cookie to response Header to set cookie on Client Side