TestController.java

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(Model model)
{
  Person objPerson = new Person();
  objPerson.setName("Mugil");
  objPerson.setAddress("Sample Address");
  objPerson.setAge("27");

  model.addAttribute("objPerson", objPerson);
  return "display";
}

display.jsp

Person Name : ${objPerson.name}
Person Location : ${objPerson.location}
Person Age : ${objPerson.age}
Person Address : ${objPerson.address}
public class Person 
{
 private String Name;
 private String Location;
 private String Age;
 private String Address;

 public String getName() {
	return Name;
 }
 public void setName(String name) {
	Name = name;
 }
 public String getLocation() {
	return Location;
 }
 public void setLocation(String location) {
	Location = location;
 }

 .
 .
 .
}

How to Design Spring MVC for View Page

  1. Have a isSuccess attribute in the bean
  2. Use when and choose to decide whether to form element or form value based on the value set in the isSuccess
  3. When isSuccess is set to true the show the form Value or show the form element else display the form element
  4. When adding a new values in through the form the bean would be set to isSuccess true
  5. Next time when the page gets loaded the form values filled before the click of the submit will be displayed a s form values.

How to access the bean values where the bean has sub bean

class Student
{
 String Name;
 Address houseAddress;
 .
 .
}

For accessing values in Student bean the form elements should be

path=Name value="${student.Name}"

For accessing values in Student Address bean the form elements should be

path=Address.houseAddress value="${Student.Address.StreetName}" 

ServletConfig

  1. ServletConfig is one of the pre-defined interface.
  2. ServletConfig object is used for developing flexible servlets.
  3. ServletConfig objct exist one per servlet program.
  4. An object of ServletConfig created by the container during its initialization phase.
  5. An object of ServletConfig is available to the servlet during its execution, once the servlet execution is completed, automatically ServletConfig interface object will be removed by the container.
  6. An object of ServletConfig interface contains details at web.xml, of a particular servlet.
  7. The moment when we are using an object of ServletConfig, we need to configure the web.xml by writing tag under tag of web.xml.
  8. When ever compiler executes init() mehod then the ServletConfig will be created in general.
  9. An object of ServletConfig contain the data in the form of key,value pairs, here the keys represents init param names and values are its values, which are represented in the web.xml file

How to Get ServletConfig Object into Servelt
Method1

ServletConfig conf = getServletConfig();

Method2
ServletConfig object will be available in init() method of the servlet.

public void init(ServletConfig config)
{
// …………………
}

How to Retrieve Data from ServletConfig Interface Object

public String getInitParameter(“param name”);
public Enumeration getInitParameterNames();

web.xml

<web-app> 
  <servlet>
     <servlet-name>onServletConfig</servlet-name>
     <servlet-class>java4s.OnServletConfig</servlet-class> 
     <init-param>
        <param-name> n1 </param-name>
        <param-value> 100 </param-value>
     </init-param>
    .
    .
</web-app>

Test.java

ServletConfig conf=getServletConfig(); 
String s1=conf.getInitParameter("n1");
 

ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

Methods of ServletContext interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the attribute for the specified name.
  5. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.

web.xml

    <web-app>  
     ......  
          
      <context-param>  
        <param-name>parametername</param-name>  
        <param-value>parametervalue</param-value>  
      </context-param>  
     ......  
    </web-app>  

Test.java

  ServletContext context=getServletContext();    

  //Getting the value of the initialization parameter and printing it  
  String driverName=context.getInitParameter("parametername");  

Which HTTP method is non-idempotent?
An idempotent operation can be repeated an arbitrary number of times and the result will be the same as if it had been done only once. In arithmetic, adding zero to a number is idempotent.

A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

For example, to access an HTML page or image, we should use GET because it will always return the same object but if we have to save customer information to database, we should use POST method. Idempotent methods are also known as safe methods and we don’t care about the repetitive request from the client for safe methods.

What is ServletContext object?

  1. javax.servlet.ServletContext interface provides access to web application parameters to the servlet.
  2. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using element.
  3. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.
    @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException 
       {
                HttpSession session = request.getSession(true);
                ServletContext context = session.getServletContext();
       }
    

ServletConfig vs ServletContext

Servlet Config Servlet Context
Servlet config object represent single servlet It represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servlet Its like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope ServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config object getServletContext() method is used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet config To get the MIME type of a file or application session related information is stored using servlet context object.

What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

  1. RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.
  2. forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.
  3. forward() is handled internally by the container whereas sednRedirect() is handled by browser.
  4. We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.
  5. In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.

Difference between web server, web container and application server
Web server: serves content to the web using http protocol.
Web container also known as a Servlet container is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

Application server: hosts and exposes business logic and processes.
An application server is a server that hosts the business logic for a system. It often hosts both long running/batch processes and/or a interop services not meant for human consumption (REST/JSON services, SOAP, RPC, etc).
An application server is typically designed and deployed to facilitate longer running processes that will also be more resource intensive.

Real World Scenarios
Web server
You have an online store with only a web server and no application server. The site will provide a display where you can choose a product from. When you submit a query, the site performs a lookup and returns an HTML result back to its client. The web server sends your query directly to the database server (be patient, I will explain this one in our next nugget) and waits for a response. Once received, the web server formulates the response into an HTML file and sends it to your web browser. This back and forth communication between the server and database server happens every time a query is run.

Application server
if the query you want to run has already been done previously and no data has changed since then, the server will generate the results without having to send the request to the database server. This allows a real-time query where a second client can access the same info and receive real time, reliable information without sending another duplicate query to the database server. The server basically acts as an intermediate between the database server and the web server. This allows the information pulled to be reusable while in the first scenario, since this info is embedded in a particular and “customized” HTML page, this is not a reusable process. A second client will have to request the info again and receive another HTML embedded page with the info requested -highly inefficient.

How to make sure a servlet is loaded at the application startup?
Usually servlet container loads a servlet on the first client request but sometimes when the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use load-on-startup element with servlet configuration in web.xml file or use WebServlet annotation loadOnStartup variable to tell container to load the servlet on system startup.

<servlet>
	<servlet-name>foo</servlet-name>
	<servlet-class>com.foo.servlets.Foo</servlet-class>
	<load-on-startup>5</load-on-startup>
</servlet> 

If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.

How to get the actual path of servlet in server?

getServletContext().getRealPath(request.getServletPath())

Why is _jspService() method starting with an ‘_’ while other life cycle methods do not?

_jspService() cannot be overridden where as other methods jspInit(), jspDestroy() can be overridden.

Difference between Filter and Listener in Servlet
Servlet Filter is used for monitoring request and response from client to the servlet, or to modify the request and response, or to audit and log.

Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example HttpSessionListener.

JSP lifecycle phases

  1. Translation of JSP to Servlet code.
  2. Compilation of Servlet to bytecode.
  3. Loading Servlet class.
  4. Creating servlet instance.
  5. Initialization by calling jspInit() method
  6. Request Processing by calling _jspService() method
  7. Destroying by calling jspDestroy() method

JSP lifecycle methods

  1. jspInit() method-What is jspInit() method
    Once a JSP file is successfully compiled into a class file, jsp engine calls jspInit() method to initialize class file. This method is called by the container only once during the lifecycle. jspInit() method can be overridden by the author to initialize resources such as database and network related connections.

    public void jspInit() {
      // initialization code or something needs to be called before JSP page
      // starts serving the requests.
     }
    

    Now the question arises why we shouldn’t use constructor instead of init method of jsp or servlet ?. Of course ! we can use constructor instead of init() method, there is nothing to stop us. In previous versions of java it was not possible to dynamically call constructor with arguments. This does no longer applied, but servlet containers still looks for an no-argument constructor. So we won’t have access to a ServletConfig or ServletContext if we use constructor instead of init() method.

  2. _jspService() method – _jspService() method is called every time a request comes to jsp during its lifecycle. The (_) underscore sign indicates that this method is generated by Container and hence cannot be overriden. The jsp code written by us goes in _jspService() because this is implicitly implemented. In case we tries to override it explicitly, JSP compliler will give an error saying “the method is already implemented and cannot override’.
  3. jspDestroy() method
    jspDestroy() method is called when servlet(jsp) is no longer in use, with the call of this method jsp lifecycle is ended and jsp submits itself to garbage collection.

    public void jspDestroy() {
      // code related to release resources like database ot network
      // connections.
     }
    

    We can always call jspDestroy() at any stage of its lifecycle but it does not make sense because even if you called jspDestroy() in the beginning, it doesn’t stops the JSP to execute the _jspService() method and sending the response back to the client. This is one of the lifecycle method which is invoked by the JSP Container when the jsp instance is removed.

Implicit objects in JSP – Objects created by web container and contain information regarding a particular request, application or page are called Implicit Objects.

Implicit object is the object that is created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

  1. response
  2. request
  3. exception
  4. application
  5. session
  6. pageContext
  7. page
  8. config
  9. out

Is JSP technology extensible?
Yes, JSP is easily extensible by use and modification of tags, or custom actions, encapsulated in tag libraries.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
requestDispatcher – forward() method

  1. When we use forward method, request is transfer to other resource within the same server for further processing.
  2. In case of forward, web container handle all process internally and client or browser is not involved.
  3. When forward is called on requestdispatcher object we pass request and response objects so our old request object is present on new resource which is going to process our request.
  4. Visually we are not able to see the forwarded address, it is transparent.
  5. Using forward () method is faster then send redirect.
  6. When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.

HttpServletResponse.sendRedirect() method

  1. In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.
  2. When you use sendRedirect, container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
  3. In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.
  4. In address bar, we are able to see the new redirected address. It’s not transparent.
  5. sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.
  6. But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.

Which one is good?
If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect. Generally, forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

How HttpServletResponse.sendRedirect() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with Location: other.jsp header
  3. Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  4. Server sends a HTTP response back with content of other.jsp.

How RequestDispatcher.forward() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with content of other.jsp.

How can a thread safe JSP page be implemented?
It can be done by having them implemented by the SingleThreadModel Interface. Add <%@page isThreadSafe=”false” %> directive in the JSP page.

How do I prevent the output of my JSP or Servlet pages from being cached?

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

How do we configure init params for JSP?
We can configure init params for JSP similar to servlet in web.xml file, we need to configure JSP init params with servlet and servlet-mapping element.

What is Scriptlet, Expression and Declaration in JSP?

A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the _jspService() method. For example;

<%
Date d = new Date();
System.out.println("Current Date="+d);
%>

Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.

<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as

<%! public static int count=0; %>

Use of pageContext Object

  1. pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.This object is intended as a means to access information about the page while avoiding most of the implementation details.
  2. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
  3. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
  4. important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute (“attrName”) removes the attribute from all scopes, while the following code only removes it from the page scope
pageContext.removeAttribute("attrName", PAGE_SCOPE);

Other Example

ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

JSP Action Elements or Action Tags
JSP action elements or action tags are HTML like tags that provide useful functionalities such as working with Java Bean, including a resource, forwarding the request and to generate dynamic XML elements. JSP action elements always starts with jsp: and we can use them in JSP page directly without the need to import any tag libraries or any other configuration changes. Some of the important action elements are jsp:useBean, jsp:getProperty, jsp:setProperty, jsp:include and jsp:forward.

Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element’s attribute.
jsp:body Defines dynamically defined XML element’s body.
jsp:text Use to write template text in JSP pages and documents.

difference between include directive and jsp:include action?
The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.

Another difference is that in JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.

When included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.

What are JSP EL implicit objects and how it’s different from JSP implicit Objects?
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. Note that these are different from JSP implicit objects and contains only the attributes in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.

JSP EL Implicit Objects Type Description
pageScope Map A map that contains the attributes set with page scope.
requestScope Map Used to get the attribute value with request scope.
sessionScope Map Used to get the attribute value with session scope.
applicationScope Map Used to get the attributes value from application scope.
param Map Used to get the request parameter value, returns a single value
paramValues Map Used to get the request param values in an array, useful when request parameter contain multiple values.
header Map Used to get request header information.
headerValues Map Used to get header values in an array.
cookie Map Used to get the cookie value in the JSP
initParam Map Used to get the context init params, we can’t use it for servlet init params

What is JSP Standard Tag Library, provide some example usage?
JSP Standard Tag Library or JSTL is more versatile than JSP EL or Action elements because we can loop through a collection or escape HTML tags to show them like text in response.JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container.

What is difference between JspWriter and Servlet PrintWriter?
PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.

<%@ include is a static include, The include directive:

<%@ include file="header.html" %>

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

standard action:

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like , but it’s more powerful and flexible: unlike the other two includes, the url can be from outside the web Container!

Preludes and codas:
Static preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding and elements respectively within a element in the Web application web.xml deployment descriptor.

How can one Jsp Communicate with Java file.

<%@ page import="market.stock.*” %>

What is web.xml
The /WEB-INF/web.xml file is the Web Application Deployment Descriptor of your application. This file is an XML document that defines everything about your application that a server needs to know except the context path.

whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded.

Defining like this 1 is also known as pre-initialization of servlet means now the servlet for which we have defined this tag has been initialized in starting when context is loaded before getting any request.

Simple Controller Example
TestController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
  @RequestMapping("/Control2")	
  public String TestMe()
  {
    return "hello";
  }
}

hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   Hi Dear!
</body>
</html>

Fibonacci(without using recursion)

public class Test
{
  public static void main(String[] args)
  {
     int a=0 , b=0 , c=1;
     System.out.println(a);
     System.out.println(b);

     for(int i=0;i<15;i++)
     {
        a=b;
        b=c;
        c=a+b;
        System.out.println(c);
     }
   }
}

Fibonacci(using recursion)

7

Reverse array without Temp Array

public static int[] reverseArrayWithoutTempArray(int[] array) 
{
    int i = 0, j = array.length - 1;
 
    for (i = 0; i < array.length / 2; i++, j--) 
    {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

Iterate random integer array and print the values greater than the current value

class Main 
{
 static void printNGE(int arr[]) 
 {
  int highestVal = 0, i, j;

  for (i = 0; i < arr.length; i++) 
  {
       if (arr[i] > highestVal) 
       {
        System.out.println(arr[i]);
        highestVal = arr[i];
       }
  }
 }

 public static void main(String args[]) 
 {
  int arr[]= {11, 13, 21, 3, 45};
  printNGE(arr);
 }
}

Inheritance program with Class and Interface.Find and print the Area and Perimeter for Rectangle,Square and Circle

  1. Interface Shape
  2. Rectangle class implements Shape
  3. Circle class extends Rectangle
interface Shape 
{
 void input();
 void area();
}

class Circle implements Shape 
{
 int r = 0;
 double pi = 3.14, ar = 0;
 
 @Override
 public void input() 
 {
  r = 5;
 }
 
 @Override
 public void area() 
 {
  ar = pi * r * r;
  System.out.println("Area of circle:" + ar);
 }
}

class Rectangle extends Circle 
{
 int l = 0, b = 0;
 double ar;

 public void input() 
 {
  super.input();
  l = 6;
  b = 4;
 }

 public void area() 
 {
  super.area();
  ar = l * b;
  System.out.println("Area of rectangle:" + ar);
 }
}

public class Demo 
{
 public static void main(String[] args) 
 {
  Rectangle obj = new Rectangle();
  obj.input();
  obj.area();
 }
}
Area of circle:78.5
Area of rectangle:24.0

Types (Hierarchy) of Java Class Loaders
Java class loaders can be broadly classified into below categories:

Bootstrap Class Loader
Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.

Extensions Class Loader
JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

System Class Loader
Java classes that are available in the java classpath are loaded using System class loader.

Why you need class Loaders
Applications written in statically compiled programming languages, such as C and C++, are compiled into native, machine-specific instructions and saved as an executable file. The process of combining the code into an executable native code is called linking – the merging of separately compiled code with shared library code to create an executable application. This is different in dynamically compiled programming languages such as Java. In Java, the .class files generated by the Java compiler remain as-is until loaded into the Java Virtual Machine (JVM) — in other words, the linking process is performed by the JVM at runtime. Classes are loaded into the JVM on an ‘as needed’ basis. And when a loaded class depends on another class, then that class is loaded as well.

When a Java application is launched, the first class to run (or the entry point into the application) is the one with public static void method called main(). This class usually has references to other classes, and all attempts to load the referenced classes are carried out by the class loader.

java.lang.ClassLoader
The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don’t explicitly specify a parent, the virtual machine’s system class loader will be assigned as the default parent.

  1. Include directive includes the file at translation time (the phase of JSP life cycle where the JSP gets converted into the equivalent servlet) whereas the include action includes the file at runtime.
  2. If the included file is changed but not the JSP which is including it then the changes will reflect only when we use include action tag. The changes will not reflect if you are using include directive as the JSP is not changed so it will not be translated for request processing and hence the changes will not reflect.
  3. When using include action tag we can also pass the parameters to the included page by using param action tag but in case of include directive it’s not possible.
    <jsp:include page="file_name" />
     <jsp:param name="parameter_name" value="parameter_value" />
    </jsp:include>
    

JSP Include Action tag

<html>
<head>
<title>JSP include Action example</title>
</head>
<body>
<jsp:include page="display.jsp" />
</body>
</html>

JSP Include Directive

<html>
<head>
<title>JSP include Directive example</title>
</head>
<body>
<%@ include file="display.jsp" %>
</body>
</html>
Posted in JSP.

SessionId is used to keep track of request coming from the same client during a time duration.

URL rewriting
URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies. If you need to track Session from JSP pages, then you can use tag for URL-rewriting. It automatically encodes session identifier in URL.

Cookies
A cookie is a small amount of information sent by a servlet to a Web browser. A cookie is saved by the browser and later sent back to the server in subsequent requests. A cookie has a name, a single value, expiration date and optional attributes. A cookie’s value can uniquely identify a client. Since a client can disable cookies, this is not the most secure and fool-proof way to manage the session. If Cookies are disabled then you can fallback to URL rewriting to encode Session id e.g. JSESSIOINID into the URL itself.

Hidden Form fields
Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

HTTPS and SSL
Web browsers that support Secure Socket Layer communication can use SSL’s support via HTTPS for generating a unique session key as part of the encrypted conversation. Modern days online internet banking website, ticket booking websites, e-commerce retailers like Amazon and e-bay all use HTTPS to security transfer data and manage the session.

  1. The difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock.
  2. Class level lock is one for each class and represented by class literal e.g. String.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java
  3. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block.
  4. One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance.
  5. Synchronized block provide granular control over lock(“very detailed control”, meaning you can control a lot of specific aspects), as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword or class level lock, if its static synchronized method.
  6. Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.
  7. In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.
public class SycnronizationExample 
{

	public synchronized void lockedByThis()
        {
        System.out.println(" This synchronized method is locked by current" instance of object i.e. this");
        }

	public static synchronized void lockedByClassLock() 
        {
	System.out.println("This static synchronized method is locked by class level lock of this class i.e. SychronizationExample.class");
	}

	public void lockedBySynchronizedBlock()
        {
           System.err.println("This line is executed without locking");     
           Object obj = String.class; //class level lock of Stirng class
     
          synchronized(obj)
          {
            System.out.println("synchronized block, locked by lock represented using obj variable");
          }
         }
}