The below code reads a Sample.txt file and places the content in a newly created Html file Sample.html.

The file from which the content should be read is placed in a project directory which is printed in the console using the below java code.

System.out.println("Working Directory = " + System.getProperty("user.dir"));

The above code prints the current project directory in console.

package com.mugil.servlets;

import java.awt.Desktop;
import java.io.*;

class GenerateHTML 
{
    public static void main(String[] args) throws Exception 
    {    	
    	System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));
        File f = new File("source.htm");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("<html>");
        bw.write("<body>");
        bw.write("<h1>ShowGeneratedHtml source</h1>");

        String line;
        while ((line=br.readLine())!=null) {
            bw.write(line);
            bw.newLine();
        }        
        bw.write("</body>");
        bw.write("</html>");

        br.close();
        bw.close();

        Desktop.getDesktop().browse(f.toURI());
    }
}

executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

For setting the Bean value in struts-config.xml we should use the form-beans tag.The form-beans tag might contain any number of bean property defined within form-bean as below.

Defining a Simple Bean Property

<form-beans>
 <form-bean name="userBean" type="org.apache.struts.action.DynaActionForm">
   <form-property name="userName" initial="This is Bean Value" type="java.lang.String" />	
 </form-bean>
</form-beans>

In the above code I am creating a userBean and setting its value is initialized to This is Bean Value.

Now in the action mapping part of the struts-config.xml I am going to map the above created bean to path as said below

<action-mappings>
 <action path="/showBeanValue" type="org.apache.struts.actions.ForwardAction" parameter="/showBeanValue.jsp"/>				
 <action name="userBean" path="/Login" />		
</action-mappings>

In the first line I am defining action path as showBeanValue and it is going to forward to page showBeanValue.jsp when some one access the showBeanValue.do in url.

In the second statement I am creating a dummy form since the the html form action should not be empty.

 
  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>     
  <html:form action="/Login">
    <bean:write name="userBean" property="userName"></bean:write>
    <bean:write name="userBean" property="userAge"></bean:write>
  </html:form>

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

Add the JSTL Library as below

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Populating a Text Box

  <input name="txtUserName" id="txtUserName" type="text" value='<c:out value="${User.userName}"></c:out>'>

Populating a Dropdown List
Type 1

 <select name="cboAge" id="cboAge">
  <c:forEach begin="20" end="60" var="i">
    <option value="${i}" <c:if test="${i == User.age}">Selected</c:if>>${i}</option>    			
  </c:forEach>
 </select>

Type 2

 <select name="cboLocation" id="cboLocation">
   <option value="Chennai">Chennai</option>
   <option value="Bangalore">Bangalore</option>
   <option value="Mumbai">Mumbai</option>
  </select>

Javascript Code

$('document').ready(function(){
  $('#cboLocation').val('<c:out value="${User.location}"></c:out>');
});

Populating Radio buttons

<input name="rdoGender" type="radio" id="rdoMale" value="1" <c:out value="${User.gender == 1?'checked':''}"></c:out>><label for="rdoMale">Male</label>
<input name="rdoGender" type="radio" id="rdoFemale" value="0" <c:out value="${User.gender == 0?'checked':''}"></c:out>><label for="rdoFemale">Female</label>

Populating Check boxes

 <input name="chkSkills" type="checkbox" id="chkJava" value="Java" <c:if test="${fn:contains(User.skills, 'Java')}">Checked</c:if>><label for="chkJava">Java</label>    	
Posted in JSP.

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>