A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and “jump” out of the method block, hereby ignoring the remnant of the code. For example:

protected void doPost() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you’re thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you’re afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doPost() 
{
    if (someCondition) 
    {
        sendRedirect();
        return;
    }
    forward();
}

… or to introduce an else block.

protected void doPost() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doPost() 
{
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don’t write to the response in the servlet. That’s the responsibility of the JSP. You just set a request attribute like so request.setAttribute(“data”, “some string”) and then print it in JSP like so ${data}

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}
  1. The Way aspect function calls are made are through proxy classes internally
  2. Internally the Spring framework creates proxy classed and calls to the code generated as per the xml are run in proxy class methods before the actual class are called
  3. In the below example in DrawingApp.java I try to create a object for the class circle by invoking factoryService getBean Method
  4. This method returns a Object of class ShapeServiceProxy with the custom methods for xml code added

ShapeService.java

package com.mugil.shapes;

public class ShapeService {
	private Circle objCircle;
	private Triangle objTriangle;
		
	public Circle getObjCircle() {
		return objCircle;
	}
	public void setObjCircle(Circle objCircle) {
		this.objCircle = objCircle;
	}
	public Triangle getObjTriangle() {
		return objTriangle;
	}
	public void setObjTriangle(Triangle objTriangle) {
		this.objTriangle = objTriangle;
	}	
}

ShapeServiceProxy.java

package com.mugil.shapes;

public class ShapeServiceProxy extends ShapeService {
	
	public Circle getObjCircle() {
		new LoggingAspect().getLogMessage();
		return super.getObjCircle();
	}
}

DrawingApp.java

package com.mugil.shapes;

public class DrawingApp
 {
	public static void main(String[] args) 
        {
		FactoryService objFactSer = new FactoryService();
		ShapeService objSS = (ShapeService)objFactSer.getBean("ShapeService");
		objSS.getObjCircle();
	}
}

FactoryService.java

package com.mugil.shapes;

public class FactoryService {
	
	public Object getBean(String className)
	{
		if(className.equals("Circle"))
			return new Circle();
		else if(className.equals("Triangle"))
			return new Triangle();
		else if(className.equals("DrawingApp"))
			return new DrawingApp();
		else if(className.equals("ShapeService"))
			return new ShapeServiceProxy();
			
		return null;
	}
}
getParameter() getAttribute()
getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource
the return type for a parameter is a String The return type for attributes is an Object
The Scope of parameter is per individual request attribute is a server variable that exists within a specified scope
application, available for the life of the entire application
session, available for the life of the session
request, only available for the life of the request
page (JSP only), available for the current JSP page only
request.getParameter(“parameterName”) in java is used for accessing variable from JSP or HTML RequestDispatcher.forward(request, response) in java and request.getAttribute(“attributeName”) in jsp are used for accessing variables
Posted in JSP.

StringEquals.java

package com.apryll.package1;

public class StringEquals 
{
  public static void main(String[] args) 
  {
	jack();
	jill();
  }

  public static void jack() 
  {
	String s1 = "hill5";
	String s2 = "hill" + "5";
	System.out.println(s1 == s2);
  }

  public static void jill() 
  {
	String s1 = "hill5";
	String s2 = "hill" + s1.length();
	System.out.println(s1 == s2);
  }
}

Output

true
5
false

Reason
Because, when a string object is instantiated it cross checks with a memory pool if that String is already created. If it is already created then it maps the new variable to the already existing variable. Therefore both these variables are same objects. In jack() at compile time java knows that both the object are same and uses the same instance for referring to it.

In jill First “hill” is created as a String object, then a new StringBuilder object is created which will help in concatenating two values. After the concatenation is done then it is converted back to a new String object. Real values are known at runtime only.

————————————————————————-

StringClass.java

public class StringClass 
{
	public static void main(String[] args) 
	{
		int a = 10 + 20;
		System.out.println(a);
	}

}

class String 
{
	private final String str;

	public String(String str) 
	{
		this.str = str;
	}

}

Output

Error: Main method not found in class StringClass, please define the main method as:
   public static void main(String[] args)
...

Reason
We do not have a main method with the expected signature. “main” method should have a String array as argument, but in our code the String array is compiled to be our custom String class and not the “java.lang.String” class. Therefore we get the error as main method missing.

Fix
Change the main method signature as public static void main(java.lang.String[] args).

————————————————————————-

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.