What is Event
Changing the state of an object is known as an event.We can perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in users, creating tables of the database at time of deploying the project, creating database connection object etc.

Event Types

  1. ServletRequestEvent – ServletRequestListener
  2. ServletContextEvent – ServletContextListener
  3. ServletRequestAttributeEvent – ServletRequestAttributeEvent
  4. ServletContextAttributeEvent – ServletContextAttributeListener
  5. HttpSessionEvent – HttpSessionListener
  6. HttpSessionBindingEvent – HttpSessionAttributeListener

Listener Types

The most basic difference is the association
Listener is associated with Event Source (Ex: key board)
Handler is associated with an Event (Ex: keydown)

A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.The handler is responsible for dealing with the event.

What is Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request.

It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.

The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don’t need to change the servlet.

Filter interface
Filter interface contains three methods

  1. public void init(FilterConfig config)init() method is invoked only once. It is used to initialize the filter.
  2. public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
  3. public void destroy()This is invoked only once when filter is taken out of the service.

How to define a Filter
web.xml

<web-app>        
	<filter>  
		<filter-name>...</filter-name>  
		<filter-class>...</filter-class>  
	</filter>         
	<filter-mapping>  
		<filter-name>...</filter-name>  
		<url-pattern>...</url-pattern>  
	</filter-mapping>        
</web-app>  

Example of Filter
web.xml


<web-app>
        <servlet>
		<servlet-name>AdminServlet</servlet-name>
		<servlet-class>AdminServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>AdminServlet</servlet-name>
		<url-pattern>/servlet1</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>f1</filter-name>
		<filter-class>MyFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>f1</filter-name>
		<url-pattern>/servlet1</url-pattern>
	</filter-mapping>
</web-app>  

MyFilter.java

public class MyFilter implements Filter 
{
  public void init(FilterConfig arg0) throws ServletException 
  {
  }

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
	throws IOException, ServletException {
  PrintWriter out = resp.getWriter();
  out.print("filter is invoked before");

  chain.doFilter(req, resp);// sends request to next resource
  out.print("filter is invoked after");
}

  public void destroy() 
  {
  }
}

HelloServlet.java

public class HelloServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.print("<br>welcome to servlet<br>");
	}
}

Whenever the /Servlet1is accessed it will go through the filter before and after processing the actual java page HelloServlet.java

How to access Init param in filter
web.xml

.
<filter>
	<filter-name>f1</filter-name>
	<filter-class>MyFilter</filter-class>
	<init-param>
		<param-name>construction</param-name>
		<param-value>no</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>f1</filter-name>
	<url-pattern>/servlet1</url-pattern>
</filter-mapping>  
.
.

MyFilter.java

public class MyFilter implements Filter 
{
	FilterConfig config;

	public void init(FilterConfig config) throws ServletException 
	{
		this.config = config;
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {

		PrintWriter out = resp.getWriter();

		String s = config.getInitParameter("construction");

		if (s.equals("yes")) {
			out.print("This page is under construction");
		} else {
			chain.doFilter(req, resp);// sends request to next resource
		}
	}

	public void destroy() {
	}
}

Context path
The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Typically a URL in a Java servlet server is of the format http://hostname.com/contextPath/servletPath/pathInfo, where each of the path elements can be zero or more / separated elements.

How to get ContextPath

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

parent.jsp

<c:forEach var="instanceVar" items="${instanceList}">
    <jsp:include page="child.jsp">
        <jsp:param name="myVar" value="${instanceVar}"/>
    </jsp:include>
</c:forEach>

child.jsp

<c:out value="${param.myVar}"/>

Another alternative is using JSTL tag c:set and request scope.

<c:set var="instance" value="${your.value}" scope="request"/>
<jsp:include page="instance.jsp"/>

instance.jsp
You should take out the variable from request Scope

<c:out value="${instance}"/>
Posted in JSP.

Exception Handling in JSP

  1. By Using Error Page
  2. By Using PageContext
  3. By Using Try…Catch Block
  4. Specifying default error page in the web.xml

Using Error Page
To set up an error page, use the <%@ page errorPage="xxx" %> directive

<%@ page errorPage="ShowError.jsp" %>
<html>
<head>
   <title>Error Handling Example</title>
</head>
<body>
<%
   // Throw an exception to invoke the error page
   int x = 1;
   if (x == 1)
   {
      throw new RuntimeException("Error condition!!!");
   }
%>
</body>
</html>

Error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP compiler to generate the exception instance variable.

<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>

Using JSTL tags in PageContext

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<table width="100%" border="1">
<tr valign="top">
<td width="40%"><b>Error:</b></td>
<td>${pageContext.exception}</td>
</tr>
<tr valign="top">
<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>
</table>

Using Try Catch Block:

<html>
<head>
   <title>Try...Catch Example</title>
</head>
<body>
<%
   try{
      int i = 1;
      i = i / 0;
      out.println("The answer is " + i);
   }
   catch (Exception e){
      out.println("An exception occurred: " + e.getMessage());
   }
%>
</body>
</html>

Specifying default error page in the web.xml
web.xml

<error-page>
   <error-code>404</error-code>
   <location>/error404.html</location>
</error-page>

Sample.jsp

<%@ page errorPage="error.jsp" %>  
<%  
   String s=null;
   s.length();
%>

error.jsp

<%@ page isErrorPage="true" %>
<%= exception.getMessage() %>
Posted in JSP.

tag
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP.

JSP Syntax

<jsp:useBean
        id="beanInstName"
        scope="page | request | session | application"       
        class="package.class"    
        type="package.class"
</jsp:useBean>

Example

  <jsp:useBean id="stock" scope="request" class="market.Stock" />

Accessing Values

<jsp:useBean id="date" class="java.util.Date" /> 
<p>The date/time is <%= date %>

Using getPropertyName() and setPropertyName()

<jsp:useBean id="students" 
                    class="com.tutorialspoint.StudentsBean"> 
   <jsp:setProperty name="students" property="firstName"
                    value="Zara"/>   
</jsp:useBean>

<p>Student First Name: 
   <jsp:getProperty name="students" property="firstName"/>
</p>

Setting Request Scope

PersonBean myBean = (PersonBean)request.getAttribute("myBean");

if(myBean == null)
{
   myBean = new PersonBean();
   request.setAttribute("myBean", myBean);
}

Accessing in JSP

<jsp:useBean id="myBean" class="PersonBean" scope="request" />
Posted in JSP.

The path with reference to root directory is called absolute. The path with reference to current directory is called relative.

Completely relative:

 <img src="kitten.png"/>   

Absolute in all respects:

<img src="http://www.foo.com/images/kitten.png">
Posted in JSP.

TestController.java

@RequestMapping(value="/Control2/{personId}")		
public String TestMe(@PathVariable("personId") Long personIdVal)
{
  System.out.println(personIdVal);
  return "hello";
}

Input

http://localhost:8089/Test2/Control1/Control2/152

Output

152

DAOService.java

public class DAOService 
{
	private List<Person> arrPersons = new ArrayList<Person>(); 
			
	public DAOService()
	{
		
		Person objPerson = new Person();
		objPerson.setName("Person 1");
		objPerson.setLocation("Teynampet");
		
		arrPersons.add(objPerson);
		
		Person objPerson2 = new Person();
		objPerson2.setName("Person 2");
		objPerson2.setLocation("TNagar");
		
		arrPersons.add(objPerson2);
	}

	public List getList()
	{
		return this.arrPersons;
	}
}

ListPerson.java

@Controller
@RequestMapping("/List")
public class ListPerson 
{	
	@Autowired
	private DAOService objDAOService;
	
	@RequestMapping("/PersonList")
	public String listPersons(Model model)
	{
		DAOService objDAOService = new DAOService();
		
		model.addAttribute("personList", this.objDAOService.getList());
		
		return "display_list";
	}
}

display_list.jsp

<title>Insert title here</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>	
	<table>
		<c:forEach items="${personList}" var="objPerson"> 
			<tr>
				<td>${objPerson.name}</td>
				<td>${objPerson.location}</td>
			</tr>
		</c:forEach>
	</table>
</body>

applicationContext.xml

<bean name="DAOService" class="com.mugil.controls.DAOService"></bean>

pom.xml

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Method Arguments in Controller

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe(HttpSession session, HttpServletRequest request)
	{
		request.setAttribute("name", "Mugil Vannan");
		session.setAttribute("Test", "TestValue");
		System.out.println("1");
		return "hello";
	}
	
	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2(HttpSession session, HttpServletRequest request)
	{
		System.out.println(session.getAttribute("Test"));
		System.out.println(request.getParameter("cboArea"));		
		return "display";
	}
}

Alternate of HttpServletRequest request

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(HttpSession session, @RequestParam("cboArea") String Area)
{
  System.out.println(session.getAttribute("Test"));
  System.out.println(Area);		
  return "display";
}