Spring Interview Question

Spring :

  • It is open source enterprise development application framework.
  • It provides container to create and manage objects and also provide enterprise service to those object
  • It is primary based on IOC and DI design pattern
  • It provides the ready component for different tier of application eg : web,data access,business and middle tier
  • Layered Architecture

Why Spring :

  • Light Weight
  • IOC
  • AOP
  • Container
  • Framework

Inverse of control and Dependency Injection :

  • It is design pattern.
  • It is used to give control to the assembler of classes

Example :

Generally, if a class wants to use another class, it instantiates desired class. But using this design pattern, the instantiation control is provided to the assembler. Assembler instantiates the required class and injects it in using class

Different Type of DI / IOC :

  • Setter Injection
  • Constructor Injection
  • Interface Injection

Different Modules in Spring :

  • Spring Core
  • Spring Context
  • Spring web
  • Spring web MVC
  • Spring ORM
  • Spring DAO
  • Spring AOP

IOC container in Spring :

  • Instantiates the Object
  • Inject the object in each other
  • Provide enterprise service [Ex : AOP and Transaction Management] to those object

BeanFactory Interface :

1. It provides configuration framework for object creation and basic functionality around object management

ApplicationContext Interface :

  • It is build around Spring’s BeanFactory
  • It provides enterprise centeric features eg AOP, message resouring, event propogating and application-layer-specific context to application

Difference Between BeanFactory and ApplicationContext :

  • BeanFactory is used for core configution and provide basic centric functionality to application
  • ApplicationContext provides enterprise centric functionality to application

What is your preference BeanFactory or ApplicationContext? Why?

ApplicationContext. It provides all features provided by BeanFactory and enterprise centric more features, which may be required by application in future

How to instantiates the IOC container ?

Common Implementation of ApplicationContext:

  • classPathXmlApplicationContext
  • fileSystemXmlApplicationContext
  • xmlWebApplicationContext

ex :


ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

How does a web application use Spring’s configuration xmls?

1. Spring container/configuration xmls can be integrated with web application through web.xml

Following entries in web.xml can integrate Spring container with web container.


 <context-param>
 <description>
 Context parameter to integrate Spring and Web containers
 </description>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 classpath: services.xml,classpath: daos.xml
 </param-value>
 </context-param>

 <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>

How to integrate multiple bean configuration xmls?

Multiple bean configuration xmls are created to separate configurations according to layers so that it becomes easy to    manage and maintain them. These configuration xmls can be imported in single xml to combine all of them.


 <beans>
 <import resource="services.xml"/>
 <import resource="daos.xml"/>

 <bean id="bean1"/>
 <bean id="bean2"/>
 </beans>

Lazily-instantiated beans :

1. By default Spring instantiates a singleton beans at the time of startup [Eagerly Instantiation]

This is good behavior as it exposes any problems in instantiation of beans at start up only. But sometimes this behavior is not expected hence by addition lazy-init=”true” to the bean definition the instantiation can be postponed to first request. Also following configuration will not allow any bean to get instantiated
eagerly.


 <beans default-lazy-init="true">
 <!-- no beans will be pre-instantiated... -->
 </beans>

Autowiring :

  • By Autowiring , Spring injects dependencies without having to specify those explicitly.
  • Spring inspects bean factory contents and establishes relationships amongst collaborating beans. To implement it,just add autowire property in xml configuration.

Different Modes of autowiring :

Autowiring having five following modes:

  • no : no autowire
  • byName : Autowiring by property name, means bean matching property name is autowired.
  • byType : Bean having type as that of property type is autowired.
  • constructor : Similar to byType just that the property is in constructor.
  • autodetect :  Spring is allowed to select autowiring from byType and constructor

Different bean scopes available to configure :

  • singleton : One bean instance per IoC container  [It is default]
  • prototype : Any number of instances of bean
  • request : Within HTTPRequest object scope
  • session : As long as HttpSession is alive
  • globalsession : Within life-cycle of global HttpSession. Applicable in portlet context usually.

How can you control bean instantiation process?

1. Bean Initailization by spring can be controlled by using initialization call backs.

There are two ways to do it.

  • First is having a initialization method (say init()) and specifying it in bean configuration as ‘init-method’ property
  • Second is implementing InitializingBean interface and implementing afterPropertiesSet() method in it.

How can you control bean destruction process?

There are two ways to do it.

  • First is add a destroy() method and specify it in bean configuration as ‘destroy-method’ property
  • Second is implement DisposableBean interface and implement destroy() method of it.

What all you have to do to start using Spring?

  • Download Spring (and dependent Jars) from Spring’s site.
  • Create application context xml to define beans and dependencies.
  • Integrate this xml with web.xml
  • Deploy and Run the application

Design Patterns are used in Spring:

  • Factory Pattern : BeanFactory for creating instance of an object Singleton : instance type can be singleton for a context Prototype : instance type can be prototype.
  • Abstract Factory Pattern
  • Builder Pattern : you can also define a method in a class who will be responsible for creating complex instance.
  • Decorator Pattern
  • Service Locator
  • Proxy – used heavily in AOP, and remoting.
  • Singleton – beans defined in spring config files are singletons by default.
  • Model View Controller :The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.
  • Front Controller : Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
  • View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

Implement Inheritence in Bean Definition :

Inheritence can be implement to specifying the ‘parent’ property in bean and pass id of (parent) bean.

Bean Life Cycle in spring container:

  • Spring container finds the bean definition from xml configuration file and instataite the bean.
  • Using the DI,Spring populate all the properies specified in bean definition.
  • If the bean implements the BeanNameAware interface ,then factory calls the setBeanName() and pass id in it.
  • If the bean implements the BeanFactoryAware interface , then factory call the setBeanFactory and pass bean instance itself.
  • If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
  • If an init-method is specified for the bean, it will be called.
  • Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

What are singleton beans and how can you create prototype beans?

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named “singleton” if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default
it is set to true. So, all the beans in spring framework are by default singleton beans.


 <beans>
 <bean id="bar" singleton="false"/>
 </beans>

What are the important beans lifecycle methods?

There are the two important beans lifecycle method.

1. setup
2. teardown

setup – it is called when bean is loaded into the container
teardown – it is called when bean is unloaded from the container

How can you override beans default lifecycle methods?

The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods.

Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.


 <beans>
 <bean id="bar" init-method="fooSetup" destroy="fooTeardown"/>
 </beans>

Inner Bean in Spring :

When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

Example :

In Spring framework, whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean.And the inner bean is supported both in setter injection ‘property‘ and constructor injection
‘constructor-arg‘.


 public class Customer
 {
 private Person person;

 public Customer(Person person) {
 this.person = person;
 }

 public void setPerson(Person person) {
 this.person = person;
 }

 @Override
 public String toString() {
 return "Customer [person=" + person + "]";
 }
 }
 public class Person
 {
 private String name;
 private String address;
 private int age;

 //getter and setter methods

 @Override
 public String toString() {
 return "Person [address=" + address + ",
 age=" + age + ", name=" + name + "]";
 }
 }

Often times, you may use “ref” attribute to reference the “Person” bean into “Customer” bean, person property as following :


 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="CustomerBean">
 <property name="person" ref="PersonBean" />
 </bean>

 <bean id="PersonBean">
 <property name="name" value="mkyong" />
 <property name="address" value="address1" />
 <property name="age" value="28" />
 </bean>

 </beans>

In general, it’s fine to reference like this, but since the ‘mkyong’ person bean is only used for Customer bean only, it’s better to declare this ‘mkyong’ person as an inner bean as following :


 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="CustomerBean">
 <property name="person">
 <bean>
 <property name="name" value="mkyong" />
 <property name="address" value="address1" />
 <property name="age" value="28" />
 </bean>
 </property>
 </bean>
 </beans>

This inner bean also supported in constructor injection as following :


 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="CustomerBean">
 <constructor-arg>
 <bean>
 <property name="name" value="mkyong" />
 <property name="address" value="address1" />
 <property name="age" value="28" />
 </bean>
 </constructor-arg>
 </bean>
 </beans>

Run It :


 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class App
 {
 public static void main( String[] args )
 {
 ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

 Customer cust = (Customer)context.getBean("CustomerBean");
 System.out.println(cust);

 }
 }

What are the different types of events related to Listeners?

There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event.

They are :

  • ContextClosedEvent – This is fired when the context is closed.
  • ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
  • RequestHandledEvent – This is fired when the web context handles any request.

DataAccessException :

  • It is runtime/unchecked exception. [User can not be froced to handle this type of exception]
  • Spring DAO is not throws any technology specific exception like SQLException . it is throw a subtype of dataaccess exception

Configure a bean to get DataSource from JNDI?


 <bean id="dataSource">
 <property name="jndiName">
 <value>java:comp/env/jdbc/myDatasource</value>
 </property>
 </bean>

Create a DataSource connection pool?


 <bean id="dataSource">
 <property name="driver">
 <value>${db.driver}</value>
 </property>
 <property name="url">
 <value>${db.url}</value>
 </property>
 <property name="username">
 <value>${db.username}</value>
 </property>
 <property name="password">
 <value>${db.password}</value>
 </property>
 </bean>

What are the types of the transaction management Spring supports ?

- declarative
- programatically

Spring Programatically transaction management Example :


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

 <!-- Initialization for data source -->
 <bean id="dataSource"
 >
 <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
 <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
 <property name="username" value="root"/>
 <property name="password" value="password"/>
 </bean>

 <!-- Initialization for TransactionManager -->
 <bean id="transactionManager"
 >
 <property name="dataSource"  ref="dataSource" />
 </bean>

 <!-- Definition for studentJDBCTemplate bean -->
 <bean id="studentJDBCTemplate"
 >
 <property name="dataSource"  ref="dataSource" />
 <property name="transactionManager"  ref="transactionManager" />
 </bean>

</beans>

You can free to add more questions in comment for readers.

 

Thanks to visit aoiblog.com

Abstract Factory Pattern

  • It is creation design pattern
  • It is one level abstraction higher than factory pattern.
  • It return the factory of the classes.

We must need to know the factory design pattern before to start read Abstract factory design pattern.

http://www.aoiblog.com/factory-method-design-pattern/

Where we can use this design pattern ?

When application needs to create the multiple families of product and we want to provide a library of products with hiding the implementation details.

Let take an same example of factory pattern to understand the abstract factory pattern.


package com.abstractfactorypattern.example;

public abstract class Message {

 public abstract String display();

}

There are three sub classes which is extends to common class names Message and override the display() method.


package com.abstractfactorypattern.example;

public class GoodMorning extends Message{

 @Override
 public String display() {
 return "Good Morning";
 }

}

package com.abstractfactorypattern.example;

public class GoodAfternoon extends Message{

 @Override
 public String display() {
 return "Good Afternoon";
 }

}

package com.abstractfactorypattern.example;

public class GoodEvening extends Message {

 @Override
 public String display() {
 return "Good Evening";
 }

}

[java]

Now we are going add one abstract layer for Message service application

[java]

package com.abstractfactorypattern.example;

public interface AbstractMessageFactory {

 public Message createMessage();

}

Now we creates the ConcreteFactory classes for GoodMorning,GoodAfternoon and GoodEvening


package com.abstractfactorypattern.example;

public class GoodMorningAbstractFactory implements AbstractMessageFactory {

 @Override
 public Message createMessage() {

 return new GoodMorning();
 }

}

package com.abstractfactorypattern.example;

public class GoodAfterNoonAbstractFactory implements AbstractMessageFactory {

 @Override
 public Message createMessage() {
 return new GoodAfternoon();
 }

}

package com.abstractfactorypattern.example;

public class GoodEveningAbstractFactory implements AbstractMessageFactory {

 @Override
 public Message createMessage() {

 return new GoodEvening();
 }

}

Create a class which will return the factories based on data provided


package com.abstractfactorypattern.example;

public class AbstractFactoryMessageProvider {

 public AbstractMessageFactory getMessage(String str){
 if(str.equals("morning")){
 return new GoodMorningAbstractFactory();
 } else if(str.equals("afternoon")){
 return new GoodAfterNoonAbstractFactory();
 } else {
 return new GoodEveningAbstractFactory();
 }
 }
}

Main Run Class :


package com.abstractfactorypattern.example;

public class ExecuteAbstractFactory {

 public static void main(String[] args) {
 AbstractFactoryMessageProvider messageFactory = new AbstractFactoryMessageProvider();
 AbstractMessageFactory message = messageFactory.getMessage("morning");
 System.out.println(message.createMessage().display());
 }

}

output : Good Morning

Factory Method Design Pattern

Key Points :

  • It is creation design pattern
  • Factory is the java class that is encapsulate object creation code
  • Factory class instantiates and return the object based on data provided
  • The different types of objects that are returned from a factory typically are subclasses of a common parent class.
  • Sub class Object creations being defered at Runtime

Example :

Let take an example to understand the factory method design pattern.This is very small and understandable example for factory method design pattern . we have to write a program to display the wishing message like Good Morning,Good Afternoon and Good Evening

We are creating an abstract class which is having an abstract method that can be implement by many sub class.


package com.factorypattern.example;

public abstract class Message {

 public abstract String display();

}

There are three sub classes which is extends to common class names Message and override the display() method.


package com.factorypattern.example;

public class GoodMorning extends Message{

 @Override
 public String display() {
 return "Good Morning";
 }

}

package com.factorypattern.example;

public class GoodAfternoon extends Message{

 @Override
 public String display() {
 return "Good Afternoon";
 }

}

package com.factorypattern.example;

public class GoodEvening extends Message {

 @Override
 public String display() {
 return "Good Evening";
 }

}

[java]

Now we are creating the Factory class that returns the sub class object based on data provided.

[java]

package com.factorypattern.example;

public class MessageFactory {

 public Message getMessage(String str){
 if(str.equals("morning")){
 return new GoodMorning();
 } else if(str.equals("afternoon")){
 return new GoodAfternoon();
 } else {
 return new GoodEvening();
 }
 }
}

Now we creates the class that calls the Factory class and pass the data to it.


package com.factorypattern.example;

public class ExecuteFactory {

 public static void main(String[] args) {
 MessageFactory messageFactory = new MessageFactory();
 Message message = messageFactory.getMessage("morning");
 System.out.println(message.display());
 }

}

output : Good Morning

We can also creates the interface instead of abstract class.

Benefits :

Loosing coupling for application
Adding new features for application very easily

Drawback :

The factory has to be used for a family of objects. If the classes doesn’t extend common base class or interface they can not be used in a factory design template.

Marker Interface In Java

Marker Interface :

  • An Interface having no method.
  • There is no need to implement any implementation method into the implementation class
  • It is used to inform the compiler to add special behaviour  for implementing class.

Marker Interface Example :

  • Serializable [Java IO Package]
  • Cloneable [Java Lang Package]
  • EventListener [Java Utils Package]

Purpose of Marker Interface :

It is used as tag to identify the module class i.e. There are so many class in real life project development and to find the identification between class and module where we can use the marker interface. [which class belong to which module]

Lets take an example :

Each organization having multiple department such as account,travel,hr,technical and admin. If we want to find for identity to department class is belong to which module ,there we can use the marker interface and give the tag information to it.

Suppose i am making my own marker interface for account.

interface Account{
 //There is no method , it is just used to identified the Account department.
}
public class Department implement Account{
 //Code here.

}
public class Employee {
 Department d = new Department();
 if(d instanceof  Account){
 println("He is belongs to account department");
 } else if(d instanceof Travel){
 println("He is belongs to travel department");
 }
 // rest code will come here.

}

 

Please give us your feedback for marker interface for better understanding.

Clonable Interface

Key Points:

  • Need to Implement Clonable Interface.
  • Clonable Interface is marker Interface.
  • Create dublicate copy for Object.
  • Classes which clonable interface that can be cloned only
  • If you access a class which does not implement a clonable interface so it will return CloneNotSupportedException exception.
  • When we create a clone object so constructor will not be called for clone object.

Example :


public class ClonableExample implements Cloneable{

 ClonableExample(){
 System.out.println("ClonableExample Constructor");
 }

 /**
 * @param args
 */
 public static void main(String[] args)
 {
 ClonableExample clonableExample = new ClonableExample();
 System.out.println("Obj 1 "+clonableExample.hashCode());
 try {
 ClonableExample clonableExample2 = (ClonableExample)clonableExample.clone();
 System.out.println("Obj 2 "+clonableExample2.hashCode());
 } catch (CloneNotSupportedException e) {
 e.printStackTrace();
 }
 }

}

Output :

ClonableExample Constructor
Obj 1 4384790
Obj 2 9634993

Next Example :

public class ClonableExample implements Cloneable{
 int a;
 int b;
 ClonableExample(){
 System.out.println("Contructor Call");
 }

 /**
 * @param args
 */
 public static void main(String[] args)
 {
 ClonableExample clonableExample = new ClonableExample();
 clonableExample.a=10;
 clonableExample.b=20;
 System.out.println("Obj 1 "+clonableExample.a + "  "+clonableExample.b);
 try {
 ClonableExample clonableExample2 = (ClonableExample)clonableExample.clone();
 System.out.println("Obj 2 "+clonableExample2.a + "  "+clonableExample2.b);
 } catch (CloneNotSupportedException e) {
 e.printStackTrace();
 }
 }

}
Contructor Call
Obj 1 10  20
Obj 2 10  20

My Village

It was the very special day of my life. I want to spend it in a very special cool place. I want to go somewhere in very typical but different place. So I choose MY Village.

My Village is at SG Highway and Himalaya Mall. But I went to Himalaya Mall. When I enter, Munimaji was sitting with latest computer. He gave us passes.(as we were 2).1 cost 300 rs. After that we got the stamp on hand for entry.

The village was nice infrastructure. It was Rajasthani and Gujarati Village. You can get each and evry food there. Like chats, pani puries, bhel,ragda patis, Dhosa, Paubhaji, chienis, Dal bati, Punjabi sabji, Kadhi Khichadi, Dal fry and rice, Nan, roti, Laccha partha, Chhass and juise. Something new was different types of papad made by them as chat.and yes you can also get Farsan like Dhokla,bhajia and sweet like Jalebi, Gulab Jamun, Sheera..

I tried to eat as I can. I found the test of Chats and Dal fry very nice. But when it comes to other stuff, it was not so good.

And ya there was also Jyotish, Tarrot reader, Pan Vala and ice-cream vala on cycle make the advantage.

It was also celebrated by puppet show, Garba and ends with DJ.

So if you want to spend more than 2 hour in any hotel or restaurant, you must have to visit MY Village.

 

Spring ContextLoaderListener


<listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
</listener>

<context-param>
 <param-value>applicationContext.xml</param-value>
</context-param>
Class ContextLoaderListener extends ContextLoader
 implements ServletContextListener{

}

This is used for bootstrap the startup – stutdown the spring application.we can define the configuration details and load it during the application startup and save it as context so we can use that configuration in overall application .

For Example :

Database Configuration

Context is always one for an application.

There is no need to do configuration for ContextLoaderListener in Spring 3.0.Application will successfully run without to define it. But If we need to define some configuration into the context and that should be loaded during application start so we have to defined it in deployment descriptor

How JSP page convert into Servlet ?

First Creating  a default JSP page [myTestJsp.jsp]:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>">

 <title>My JSP 'myTestJsp.jsp' starting page</title>

 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">

 </head>

 <body>
 This is my JSP page. <br>
 </body>
</html>

Converting into JAVA Servlet class :

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

public final class myTestJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent {

 private static java.util.List _jspx_dependants;

 public Object getDependants() {
 return _jspx_dependants;
 }

 public void _jspService(HttpServletRequest request, HttpServletResponse response)
 throws java.io.IOException, ServletException {

 JspFactory _jspxFactory = null;
 PageContext pageContext = null;
 HttpSession session = null;
 ServletContext application = null;
 ServletConfig config = null;
 JspWriter out = null;
 Object page = this;
 JspWriter _jspx_out = null;
 PageContext _jspx_page_context = null;

 try {
 _jspxFactory = JspFactory.getDefaultFactory();
 response.setContentType("text/html;charset=ISO-8859-1");
 pageContext = _jspxFactory.getPageContext(this, request, response,
 null, true, 8192, true);
 _jspx_page_context = pageContext;
 application = pageContext.getServletContext();
 config = pageContext.getServletConfig();
 session = pageContext.getSession();
 out = pageContext.getOut();
 _jspx_out = out;

 out.write('\r');
 out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 out.write("\r\n");
 out.write("\r\n");
 out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
 out.write("<html>\r\n");
 out.write("  <head>\r\n");
 out.write("    <base href=\"");
 out.print(basePath);
 out.write("\">\r\n");
 out.write("    \r\n");
 out.write("    <title>My JSP 'myTestJsp.jsp' starting page</title>\r\n");
 out.write("    \r\n");
 out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
 out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
 out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
 out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
 out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
 out.write("\t\r\n");
 out.write("\r\n");
 out.write("  </head>\r\n");
 out.write("  \r\n");
 out.write("  <body>\r\n");
 out.write("    This is my JSP page. <br>\r\n");
 out.write("  </body>\r\n");
 out.write("</html>\r\n");
 } catch (Throwable t) {
 if (!(t instanceof SkipPageException)){
 out = _jspx_out;
 if (out != null && out.getBufferSize() != 0)
 out.clearBuffer();
 if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
 }
 } finally {
 if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
 }
 }
}

2. Now I am declaring some variable in declaration .

 <%!
 int a = 0,b=0,c=0;
 %>

so converted jsp will put it as global

public final class myTestJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent {

 int a = 0,b=0,c=0;

 private static java.util.List _jspx_dependants;

 public Object getDependants() {
 return _jspx_dependants;
 }

 public void _jspService(HttpServletRequest request, HttpServletResponse response)
 throws java.io.IOException, ServletException {
 //Same code as above

 }
}

3.Now i am adding function in my declaration part

 <%!
 int a = 0,b=0,c=0;
 public void abc(){

 a=10;
 b=20;
 c=30;

 System.out.println("a "+a);
 System.out.println("b "+b);
 System.out.println("c "+c);
 }
 %>

Converting Jsp in servlet :

 public final class myTestJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent {

 int a = 0,b=0,c=0;
 public void abc(){

 a=10;
 b=20;
 c=30;

 System.out.println("a "+a);
 System.out.println("b "+b);
 System.out.println("c "+c);
 }

 private static java.util.List _jspx_dependants;

 public Object getDependants() {
 return _jspx_dependants;
 }

 public void _jspService(HttpServletRequest request, HttpServletResponse response)
 throws java.io.IOException, ServletException {
 //Same code as above

 }
}

Note : You  can not declare the function in scriptlet.

4. Now I am creating scriptlet in Jsp :

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="java.text.SimpleDateFormat"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>">

 <title>My JSP 'myTestJsp.jsp' starting page</title>

 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">

 </head>

 <body>
 <%!
 int a = 0,b=0,c=0;
 public void abc(){

 a=10;
 b=20;
 c=30;

 System.out.println("a "+a);
 System.out.println("b "+b);
 System.out.println("c "+c);
 }
 %>

 <%
 Date d1 = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
 String mydisplayDate = sdf.format(d1);

 System.out.println("mydisplayDate "+mydisplayDate);
 %>
 This is my JSP page.<br/>
 This is my Outer Date : <%=mydisplayDate%>
 <br>
 </body>
</html>

Converted Servlet :

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;
import java.text.SimpleDateFormat;

public final class myTestJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent {

 int a = 0,b=0,c=0;
 public void abc()
 {

 a=10;
 b=20;
 c=30;

 System.out.println("a "+a);
 System.out.println("b "+b);
 System.out.println("c "+c);
 }

 private static java.util.List _jspx_dependants;

 public Object getDependants() {
 return _jspx_dependants;
 }

 public void _jspService(HttpServletRequest request, HttpServletResponse response)
 throws java.io.IOException, ServletException {

 JspFactory _jspxFactory = null;
 PageContext pageContext = null;
 HttpSession session = null;
 ServletContext application = null;
 ServletConfig config = null;
 JspWriter out = null;
 Object page = this;
 JspWriter _jspx_out = null;
 PageContext _jspx_page_context = null;

 try {
 _jspxFactory = JspFactory.getDefaultFactory();
 response.setContentType("text/html;charset=ISO-8859-1");
 pageContext = _jspxFactory.getPageContext(this, request, response,
 null, true, 8192, true);
 _jspx_page_context = pageContext;
 application = pageContext.getServletContext();
 config = pageContext.getServletConfig();
 session = pageContext.getSession();
 out = pageContext.getOut();
 _jspx_out = out;

 out.write("\r\n");
 out.write("\r\n");

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 out.write("\r\n");
 out.write("\r\n");
 out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
 out.write("<html>\r\n");
 out.write("  <head>\r\n");
 out.write("    <base href=\"");
 out.print(basePath);
 out.write("\">\r\n");
 out.write("    \r\n");
 out.write("    <title>My JSP 'myTestJsp.jsp' starting page</title>\r\n");
 out.write("    \r\n");
 out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
 out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
 out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
 out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
 out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
 out.write("\t\r\n");
 out.write("\r\n");
 out.write("  </head>\r\n");
 out.write("  \r\n");
 out.write("  <body>\r\n");
 out.write("\t  ");
 out.write("\r\n");
 out.write("  \r\n");
 out.write("  \t\t");

 Date d1 = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
 String mydisplayDate = sdf.format(d1);

 System.out.println("mydisplayDate "+mydisplayDate);

 out.write("\r\n");
 out.write("    r\n");
 out.write("    This is my Outer Date :This is my JSP page.<br/>\ ");
 out.print(mydisplayDate);
 out.write("\r\n");
 out.write("     <br>\r\n");
 out.write("  </body>\r\n");
 out.write("</html>\r\n");
 } catch (Throwable t) {
 if (!(t instanceof SkipPageException)){
 out = _jspx_out;
 if (out != null && out.getBufferSize() != 0)
 out.clearBuffer();
 if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
 }
 } finally {
 if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
 }
 }
}

How to display serial number in display tags

RowDecorator Java Class :
import org.displaytag.decorator.TableDecorator;

public class RowDecorator extends TableDecorator
{

 public Integer getAddRowId()
 {
 return getListIndex()+1;
 }
}

Display Table :


<display:table id="cul" uid="cul" name="${iterateCollectionList}" defaultsort="1" defaultorder="ascending"
 pagesize="10" excludedParams="*" partialList="true"  decorator="RowDecorator"
 requestURI="yoururl.html"  size="${iterateCollectionSize}" export="true">

 <display:column property="addRowId" sortable="true" title="Serial Number" />

</display:table>

Sort List of String in reverse Order Using Collections

public class SortingStringInReverseOrder {

 /**
 * @param args
 */
 public static void main(String[] args) {

 List<String> strList = new ArrayList<String>();

 strList.add("aaaa");
 strList.add("bbbb");
 strList.add("cccc");
 strList.add("dddd");
 strList.add("eeee");
 strList.add("ffff");

 System.out.println("strList "+strList);

 Comparator comp = Collections.reverseOrder();

 Collections.sort(strList, comp);

 System.out.println("strList "+strList);

 }

}