Sei sulla pagina 1di 178

IBM

Ans 5)

Six Steps to Running Your First Servlet

Once Tomcat is installed and configured, you can put it to work. Six steps take you from writing your servlet to
running it. These steps are as follows:
1. Create a directory structure under Tomcat for your application.
2. Write the servlet source code. You need to import the javax.servlet package and the javax.servlet.http
package in your source file.
3. Compile your source code.
4. Create a deployment descriptor.
5. Run Tomcat.
6. Call your servlet from a web browser.

Step 1: Create a Directory Structure under Tomcat

When you install Tomcat, several subdirectories are automatically created under the Tomcat home directory
(%TOMCAT_HOME%). One of the subdirectories is webapps. The webapps directory is where you store your web
applications. A web application is a collection of servlets and other contents installed under a specific subset of the
server's URL namespace. A separate directory is dedicated for each servlet application. Therefore, the first thing to
do when you build a servlet application is create an application directory. This section explains how to create a
directory structure for an application called myApp.
1. Create a directory called myApp under the webapps directory. The directory name is important because this
also appears in the URL to your servlet.
2. Create the src and WEB-INF directories under myApp, and create a directory named classes under WEB-
INF. The directory structure is shown in Figure 1.4. The src directory is for your source files, and the classes
directory under WEB-INF is for your Java classes. If you have html files, you put them directly in the
myApp directory. You also may want to create a directory called images under myApp for all your image
files.
Note that the admin, ROOT, and examples directories are for applications created automatically when you install
Tomcat.
Figure 1.4 Tomcat application directory structure.

Step 2: Write the Servlet Source Code

In this step, you prepare your source code. You can write the source code yourself using your favorite text
editor or copy it from the CD included with the book.
1
The code in Listing 1.1 shows a simple servlet called TestingServlet. The file, named TestingServlet.java, sends to
the browser a few HTML tags and some text. For now, don't worry if you haven't got a clue about how it works.

Listing 1TestingServlet.java

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

public class TestingServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Testing Center");
out.println("</BODY>");
out.println("</HTML>");
}
}
Now, save your TestingServlet.java file to the src subdirectory under myApp. You actually can place the source files
anywhere; however, it is always a good idea to be organized by storing all your source code files in the src directory.

Step 3: Compile Your Source Code

For your servlet source code to compile, you need to include in your CLASSPATH environment variable the path to
the servlet.jar file. The servlet.jar is located in the common\lib\ subdirectory under %CATALINA_HOME%.
NOTE
If you have forgotten how to edit the CLASSPATH environment variable, refer to Appendix A, "Tomcat Installation
and Configuration."
If you are using Windows, remember that the new environment variable takes effect only for new console windows.
In other words, after changing a new environment variable, open a new console window for typing your command
lines.
Now, change directory to your working directory and type the following if you are using Windows:
javac -d ..\WEB-INF\classes\ TestingServlet.java
If you are using Linux/UNIX, the command is very similar, except that / is used to separate a directory from a
subdirectory.
javac -d ../WEB-INF/classes/ TestingServlet.java
The -d option specifies where to place the generated class files. The command also assumes that you have placed the
JDK's bin directory in the path so you can call any program in it from any directory.

2
Step 4: Create the Deployment Descriptor

A deployment descriptor is an optional component in a servlet application, taking the form of an XML document
called web.xml. The descriptor must be located in the WEB-INF directory of the servlet application. When present,
the deployment descriptor contains configuration settings specific to that application. Deployment descriptors are
discussed in detail in Chapter 16. "Application Deployment."
For this step, you now need to create a web.xml file and place it under the WEB-INF directory under myApp.
The web.xml for this example application must have the following content.<?xml version="1.0" encoding="ISO-
8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
</web-app>
The web.xml file has one element: web-app. You should write all your servlets under <web-app>. For each servlet,
you have a <servlet> element and you need the <servlet-name> and <servlet-class> elements. The <servlet-name> is
the name for your servlet, by which it is known to Tomcat. The <servlet-class> is the compiled file of your servlet
without the .class extension.
Having more than one servlet in an application is common. For every servlet, you need a <servlet> element in the
web.xml file. For example, the following code shows how the web.xml looks if you add another servlet called
Login.
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
</web-app>

Step 5: Run Tomcat

If it is not already running, you need to start Tomcat. For information on how to do that, see Appendix A, "Tomcat
Installation and Configuration."

3
Step 6: Call Your Servlet from a Web Browser

You are ready to call your servlet from a web browser. By default, Tomcat runs on port 8080 in myApp virtual
directory under the servlet subdirectory. The servlet that you just wrote is named Testing. The URL for that servlet
has the following format:
http://domain-name/virtual-directory/servlet/servlet-name
If you run the web browser from the same computer as Tomcat, you can replace domain-name with localhost.
Therefore, the URL for your servlet would be http://localhost:8080/myApp/servlet/Testing.

In the deployment descriptor you wrote in Step 4, you actually mapped the servlet class file called TestingServlet
with the name "Testing" so that your servlet can be called by specifying its class file (TestingServlet) or its name
(Testing). Without a deployment descriptor, your servlet must be called by specifying its class name; that is,
TestingServlet. This means that if you had not written a deployment descriptor in Step 4, you would have to use the
following URL to call your servlet:
http://localhost:8080/myApp/servlet/TestingServlet
Typing the URL in the Address or Location box of your web browser will give you the string "Welcome to the
Servlet Testing Center," as shown in Figure 1.5.
Figure 1.5 The Testing servlet.

Congratulations. You have just written your first servlet.

Ans 8)
Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName
or obj['propName'] and the object does not have such a property - which can be checked via
obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]]
instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the
original object's prototype-chain until a match is found or its end is reached.
Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property
named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a
new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by
Func.prototype.

This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen -
prototypical, and not class-based:
Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the
constructor function's prototype property) as shared members, ie members which are the same for each instance. In
class-based systems, methods are implemented the same way for each instance, so methods are normally added to
the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during
construction.

Capgemini

4
Ans 1)
You use a self join when a table references data in itself.
E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current
employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

Ans 2)
The beans definition is found by the spring container from the XML file and instantiates the bean. All the
properties specified in the bean definition are populated by spring using dependency injection. The beans Id is
passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase
the bean implements the BeanFactoryAware interface. The init() method is invoked if specified. If any
BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.

Explain Bean lifecycle in Spring framework.

1. The spring container finds the beans definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans
ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an
instance of itself.

5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization()
methods will be called.

6. If an init-method is specified for the bean, it will be called.

7. Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.

Ans 3)

5
Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ
according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test3{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());

Ans 4)

6
4. Implement Custom Scope bean

To integrate your custom scope(s) into the Spring container, you need to implement the
org.springframework.beans.factory.config.Scope interface. Create the custom scope com.javabeat.MyScope under
directory src/com/javabeat which implements Scope interface. The contents of the file are as below:
1 package com.javabeat;

3 import java.util.Collections;

4 import java.util.HashMap;

5 import java.util.Map;

7 import org.springframework.beans.factory.ObjectFactory;

8 import org.springframework.beans.factory.config.Scope;

10 public class MyScope implements Scope {

11 private Map<String, Object> objectMap = Collections

12 .synchronizedMap(new HashMap<String, Object>());

13

14 /**

15 * (non-Javadoc)

16 *

17 * @see org.springframework.beans.factory.config.Scope#get(java.lang.String,

18 * org.springframework.beans.factory.ObjectFactory)

19 */

20 public Object get(String name, ObjectFactory<?> objectFactory) {

21 if (!objectMap.containsKey(name)) {

22 objectMap.put(name, objectFactory.getObject());

23 }

24 return objectMap.get(name);

25

26 }

27

28 /**
7
29 * (non-Javadoc)

30 *

31 * @see org.springframework.beans.factory.config.Scope#remove(java.lang.String)

32 */

33 public Object remove(String name) {

34 return objectMap.remove(name);

35 }

36

37 /**

38 * (non-Javadoc)

39 *

40 * @see org.springframework.beans.factory.config.Scope#registerDestructionCallback

41 * (java.lang.String, java.lang.Runnable)

42 */

43 public void registerDestructionCallback(String name, Runnable callback) {

44 // do nothing

45 }

46

47 /**

48 * (non-Javadoc)

49 *

* @see
50
org.springframework.beans.factory.config.Scope#resolveContextualObject(java.lang.String)

51 */

52 public Object resolveContextualObject(String key) {

53 return null;

54 }

55

56 /**

57 * (non-Javadoc)

58 *

8
59 * @see org.springframework.beans.factory.config.Scope#getConversationId()

60 */

61 public String getConversationId() {

62 return "MyScope";

63 }

64

65 /**

66 * clear the beans

67 */

68 public void clearBean() {

69 objectMap.clear();

70 }

71 }

5. Create a example bean

Add com.javabeat.Person bean under directory src/com/javabeat. The contents of the file are as below:
1 package com.javabeat;

3 public class Person {

4 /**

5 * Default Constructor

6 */

7 public Person() {

8 System.out.println("*** Person() constructor ***");

9 }

10 }

6. Create spring configuration file and register the Custom scope bean

Create beans configuration file Custombean.xml under the src folder.


<?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"

9
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans.xsd

7 http://www.springframework.org/schema/aop
8 http://www.springframework.org/schema/aop/spring-aop.xsd">
9
10 <bean id="myScope" class="com.javabeat.MyScope"/>
11
12 <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
13 <property name="scopes">
14 <map>

15 <entry key="customscope">
16 <ref bean="myScope" />
17 </entry>
18 </map>
19 </property>
20 </bean>

21
22 <bean name="p1" class="com.javabeat.Person" scope="customscope" />
23
24 </beans>

Few things to notice here:


MyScope is defined as a bean here with name customscope. Application can lookup this bean to remove the short
lived beans.
MyScope is registered with the Spring IoC container using CustomScopeConfigurer with scope name myScope. The
key will be the name of the Custom Scope to be used in the bean definition and the value will be bean which
implement the scope.
Finally, the Person bean is defined with scope customscope.

7. Sample application for spring custom scope and testing

Create MainApp.java
Write a MainApp class under the directory src/com/javabeat. The contents of the file are as below:
view source
print?
1 package com.javabeat;

3 import org.springframework.context.ApplicationContext;

10
4 import org.springframework.context.support.ClassPathXmlApplicationContext;

6 public class MainApp {

8 public static void main(String args[]) {

9 ApplicationContext ctx = new ClassPathXmlApplicationContext(

10 "Custombean.xml");

11

12 // 1. Retrieve the bean 'p1' from Context

13 System.out.println("Looking up 'p1'");

14 Person p1 = ctx.getBean("p1", Person.class);

15

16 // 2. Retrieve the bean 'p1' from Context again

17 System.out.println("Looking up 'p1' again");

18 Person p2 = ctx.getBean("p1", Person.class);

19 // 3. The beans retrieved in step 1 and 2 should be same.

20 System.out.println("p1 = " + p1.toString());

21 System.out.println("p2 = " + p2.toString());

22

23 // 4. Trigger the Clearing of bean.

24 System.out.println("======================================================");

25 System.out.println("Clearing the beans...");

26 MyScope myScope = ctx.getBean("myScope", MyScope.class);

27 myScope.clearBean();

28 System.out.println("Clear Bean Completed.");

29 System.out.println("======================================================");

30

31 // 4. Retrieve the bean 'p1' from Context after clearing

32 System.out.println("Looking up 'p1'");

33 Person p3 = ctx.getBean("p1", Person.class);

34

11
35 // 5. Retrieve the bean 'p1' from Context again after clearing

36 System.out.println("Looking up 'p1' again");

37 Person p4 = ctx.getBean("p1", Person.class);

38

39 // 6. The beans retrieved in step 4 and 5 should be same.

40 System.out.println("p3 = " + p3.toString());

41 System.out.println("p4 = " + p4.toString());

42

43 }

44 }

Run the sample application:


As a final step, let us run the application. If everything is fine with your application, the following output is printed:
1 Looking up 'p1'

2 *** Person() constructor ***

3 Looking up 'p1' again

4 p1 = com.javabeat.Person@7c7410

5 p2 = com.javabeat.Person@7c7410

6 ======================================================

7 Clearing the beans...

8 Clear Bean Completed.

9 ======================================================

10 Looking up 'p1'

11 *** Person() constructor ***

12 Looking up 'p1' again

13 p3 = com.javabeat.Person@a7c8bd

14 p4 = com.javabeat.Person@a7c8bd

We can see in the output that Person constructor is called first time when we requested the bean from the context,
for the next request (at step 2), the Person constructor is not invoked, instead, Spring has returned the same instance
which is created earlier (at step 1).
After removing/clearing bean, when we requested the bean p1 (at step 4), the Person constructor is invoked, and for
the next request (at step 5), the instance which is created earlier (at step 4) is returned.
Download Example Application for Custom Bean Scope (381)

12
8. Summary

In this post we saw how to custom create a bean scope in Spring with an example. On similar lines custom scopes
can be create for beans which can be shared between servlet contexts or for beans which can be shared within a
same thread and many more examples. In the next post I shall cover customizing Spring beans callback methods.
If you are interested in receiving the future articles, please subscribe here.

Ans 6)
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class Main {

public static void main(String[] args) {


HashMap<String, String> hMap = new HashMap<String, String>();
hMap.put("1", "One");
hMap.put("2", "Two");
hMap.put("3", "Three");

Collection c = hMap.values();
Iterator itr = c.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
/*
Three
Two
One

13
*/
Ans 7)
A new instance of a a persistent class which is not associated with a Session, has no representation in the database
and no identifier value is considered transient by Hibernate:
Person person = new Person();
person.setName("Foobar");
// person is in a transient state
A persistent instance has a representation in the database, an identifier value and is associated with a Session. You
can make a transient instance persistent by associating it with a Session:
Long id = (Long) session.save(person);
// person is now in a persistent state
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached
to a Session anymore (but can still be modified and reattached to a new Session later though).

Ans 8)
import org.hibernate.*;
import org.hibernate.cfg.*;

public class ClientLogicProgram {

public static void main(String... args)


{

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();

Session session1 = factory.openSession();

Product p=null; //Transient state..


Object o=session1.get(Product.class, new Integer(1001));
p=(Product)o; //now p is in Persistent state..

14
session1.close();

p.setPrice(36000); // p is in Detached state

Session session2=factory.openSession();

Transaction tx=session2.beginTransaction();
session2.update(p); // now p reached to Persistent state
tx.commit();

session2.close();

factory.close();
}
}

Virtusa
Ans 1) Servlet is an Interface
It is nothing but an interface which contains set of method names (prototypes).
Those are called servlet life cycle methods.
init(ServletConfig)
getServletConfig()
service(SeveletRequest , ServletResponce)
distroy()

The class which says itself a servlet class, must implement these methods first (directly or indirectly). These
methods will be called by the web container at different states of the life cycle of servlet object ...

WIPRO
ANS 1)
The one-word answer they're probably looking for is "encapsulation".

15
By encapsulating the private field value, you have the opportunity to change the logic on how the value is
set/retrieved in the future. Say, for example, you want to validate on set and filter on retrieval (get). By
encapsulating the value, your creating an API which allows for better maintenance moving forward.

Infosys
ANS 1)
Difference between SAX and DOM Parser is very popular Java interview and often asked when interviewed on Java
and XML. Both DOM and SAX parser are extensively used to read and parse XML file in java and have there own set of
advantage and disadvantage which we will cover in this article. Though there is another way of reading xml file using
xpath in Java which is more selective approach like SQL statements people tend to stick with XML parsers. DOM Parser
vs SAX parsers are also often viewed in terms of speed, memory consumption and there ability to process large xml
files.

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element
representing tree branches. DOM Parser creates an In Memory tree representation of XML file and then parses it, so it
requires more memory and its advisable to have increased heap size for DOM parser in order to avoid
Java.lang.OutOfMemoryError:java heap space . Parsing XML file using DOM parser is quite fast if XML file is small but if
you try to read a large XML file using DOM parser there is more chances that it will take a long time or even may not be
able to load it completely simply because it requires lot of memory to create XML Dom Tree. Java provides support DOM
Parsing and you can parse XML files in Java using DOM parser. DOM classes are in w3c.dom package while DOM Parser
for Java is in JAXP (Java API for XML Parsing) package.

SAX XML Parser in Java

SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so
much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and
the parsing works accordingly. Its recommended to use SAX XML parser for parsing large xml files in Java
because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts. Java provides
support for SAX parser and you can parse any xml file in Java using SAX Parser, I have covered example of reading xml
file using SAX Parser here. One disadvantage of using SAX Parser in java is that reading XML file in Java using SAX
Parser requires more code in comparison of DOM Parser.

Difference between DOM and SAX XML Parser

Here are few high level differences between DOM parser and SAX Parser in Java:

1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.

16
4) DOM parser works on Document Object Model while SAX is an event based xml parser.

Thats all on difference between SAX and DOM parsers in Java, now its up to you on which XML parser you going to
choose. I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you dont
know size of xml files to be processed or they are large.

JSON

Evaluates to JavaScript Objects

The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use standard
JavaScript functions to convert JSON data into native JavaScript objects.
JSON Example
<!DOCTYPE html>
<html>
<body>

<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>

<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';

var obj = JSON.parse(text);

document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

</body>
</html>

Much Like XML Because

Both JSON and XML is "self describing" (human readable)


Both JSON and XML is hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages

17
Both JSON and XML can be fetched with an XMLHttpRequest

Much Unlike XML Because

JSON doesn't use end tag


JSON is shorter
JSON is quicker to read and write
JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function.

Why JSON?

For AJAX applications, JSON is faster and easier than XML:


Using XML
Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables
Using JSON
Fetch a JSON string
JSON.Parse the JSON string

JSON Data - A Name and a Value

JSON data is written as name/value pairs.


A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example

"firstName":"John"

JSON names require double quotes. JavaScript names don't.

18
JSON Values

JSON values can be:


A number (integer or floating point)
A string (in double quotes)
A Boolean (true or false)
An array (in square brackets)
An object (in curly braces)
null

JSON Objects

JSON objects are written inside curly braces.


Just like JavaScript, JSON objects can contain multiple name/values pairs:

Example

{"firstName":"John", "lastName":"Doe"}

JSON Arrays

JSON arrays are written inside square brackets.


Just like JavaScript, a JSON array can contain multiple objects:

Example

"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
In the example above, the object "employees" is an array containing three objects. Each object is a record of a
person (with a first name and a last name).
ANS 2)
Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

19
prototype - Scopes a single bean definition to any number of object instances.
request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has
its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware
Spring ApplicationContext.
session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-
aware Spring ApplicationContext.
global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid
when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
ANS 3) REFER NEW BOOK

ANS 4)
1.My understanding is that the less buffer size that you use, the performance is better for client side browsers.
Does my assumption correct? If you think otherwise, please explain
Answer: Yes, not actually in terms of performance. But in terms of rendering the content. Because the client will get
data at faster rate. Buffer size should be greater than or equal to the underlying socket buffer size. Otherwise, though
the jsp's flushes when the buffer size is reached it will not be actually written to the client.
2.What should be the optimal buffer size
Answer: As i have said above it should be greater than or equal the underlying socket buffer size. The optimal size
also depends on your application. It should be such a value that once the buffer size is reached, the response will be
committed and you can no more do operation which result in adding response header.
3.Is there a way to know what is the default buffer size?
Answer : Yes , using JspWriter class. JspWriter has a getter getBufferSize() which gives you the buffer size. The
JspWriter can be obtained using pageContext.getOut().

4.Setting autoflush to true should flush the buffer once the max size reached. If you set it to false, its upto you
to decide when to flush
Answer: It set to true, it will flush when the max buffer size is reached. If set to false, it will throw an raised
exception
ANS 5)
SessionFactory factory = cfg.buildSessionFactory();

Session session1 = factory.openSession();


Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();
s1.setMarks(97);

Session session2 = factory.openSession();


Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;

20
Transaction tx=session2.beginTransaction();
session2.merge(s1);
Explanation
See from line numbers 47, we just loaded one object s1 into session1 cache and closed session1 at line number 7,
so now object s1 in the session1 cache will be destroyed as session1 cache will expires when ever we say
session1.close().

Now s1 object will be in some RAM location, not in the session1 cache. Here s1 is in detached state, and at line
number 8 we modified that detached object s1, now if we call update() method then hibernate will throws an error,
because we can update the object in the session only.
So we opened another session [session2] at line number 10, and again loaded the same student object from the
database, but with name s2. So in this session2, we called session2.merge(s1); now into s2 object s1 changes
will be merged and saved into the database
ANS 6)
When you call session.load() method, it will always return a proxy object, whats the meaning of proxy object ?
Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the
database, for example if we call session.load(Student.class,new Integer(107)); > hibernate will create one fake
Student object [row] in the memory with id 107, but remaining properties of Student class will not even be

initialized.
GET
When you call session.get() method, it will hit the database immediately and returns the original object. If the row is
not available in the database, it returns null.

Difference Between EAGER and LAZY

Okay, so we talked about the fact that FetchType.LAZY is the default fetch type for all Hibernate annotation
relationships.
Please note below:
@onetomany:lazy
@manytomany:lazy
@manytoone:eager
@onetoone:eager

21
We also talked about the fact that when you use the Lazy fetch type, Hibernate wont load the relationships for that
particular object instance. So then, whats the difference between Eager and Lazy?
Fetch type Eager is essentially the opposite of Lazy, Eager will by default load ALL of the relationships related to a
particular object loaded by Hibernate. This means that if you change the relationship to be this:
view plaincopy to clipboardprint?
1. import javax.persistence.FetchType;
2. //....
3. //....
4. //....
5.
6. @OneToOne(fetch=FetchType.EAGER)
7. @JoinColumn(name="user_profile_id")
8. private Profile getUserProfile()
9. {
10. return userProfile;
}
FetchType.LAZY = Doesnt load the relationships unless explicitly asked for via getter
FetchType.EAGER = Loads ALL relationships

Bydefault lazy loading is true.Lazy loading means when the select query is executed it will not hit the database. It
will wait for getter function i.e when we required then ,it will fetch from the datbase. for example: You are a parent
who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he
comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all
the time. So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever
you call him, he just comes to you without his toys.
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes
one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of
SQL queries it needs to generate within a given transaction. That is instead of updating after every modification
done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between
it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not
bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query,
at that time no need to go for a database transaction. In this way the second level cache works. Here we can use
query level cache also. Later we will discuss about it.

22
ANS 7)

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again
for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also
specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a
new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data
that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

ANS 11)
Actually our POJO class object having 3 states like
Transient state
Persistent state
Detached state

Transient & Persistent states:

When ever an object of a pojo class is created then it will be in the Transient state
When the object is in a Transient state it doesnt represent any row of the database, i mean not associated
with any Session object, if we speak more we can say no relation with the database its just an normal object
If we modify the data of a pojo class object, when it is in transient state then it doesnt effect on the database
table
When the object is in persistent state, then it represent one row of the database, if the object is in persistent
state then it is associated with the unique Session
if we want to move an object from persistent to detached state, we need to do either closing that session or
need to clear the cache of the session
if we want to move an object from persistent state into transient state then we need to delete that object
permanently from the database

23
Example____ ClientProgram.java

1 import org.hibernate.*;
2 import org.hibernate.cfg.*;
3
4 public class ClientProgram {
5
6 public static void main(String[] args)
7 {
8
9 Configuration cfg = new Configuration();
10 cfg.configure("hibernate.cfg.xml");
11
12 SessionFactory factory = cfg.buildSessionFactory();
13 Session session = factory.openSession();
14
15 // Transient state_____start
16 Product p=new Product();
17 p.setProductId(101);
18 p.setProName("iPhone");
19 p.setPrice(25000);
20 // Transient state_____end
21
22 // Persistent state_____start
23 Transaction tx = session.beginTransaction();
24 session.save(p);
25 System.out.println("Object saved successfully.....!!");
26 tx.commit();

24
27 // Persistent state_____end
28
29 session.close();
30 factory.close();
31 }
32
33 }
Note:
see the above client program, line numbers 16 to 19 we just loaded the object and called the corresponding
setter methods, its not related to the database row
if you see, line number 24 we called save method in the Session Interface, means the object is now having
the relation with the database
if we want to convert the object from Transient state to Persistentstate we can do in 2 ways
o By saving that object like above

o By loading object from database

If we do any modifications all the changes will first applied to the object in session cache only (Let__ we do the
modifications 5 times, then 5 times we need to save the changes into the database right, which means number of
round trips from our application to database will be increased, Actually if we load an object from the database, first
it will saves in the cache-memory so if we do any number of changes all will be effected at cache level only and
finally we can call save or update method so with the single call of save or update method the data will be saved into
the database.
If we want to save an object into database then we need to call any one of the following 3 methods
save()
persist()
saveOrUpdate()
i will explain about persist, saveOrUpdate methods later.
If we want to load an object from database, then we need to call either load() or get() methods

Transient:

One newly created object,with out having any relation with the database, means never persistent, not associated with
any Session object

25
Persistent:

Having the relation with the database, associated with a unique Session object

Detached:

previously having relation with the database [persistent ], now not associated with any Session
see the next sessions for the better understanding of the life cycle states of pojo class object(s) the hibernate
ANS 12)
1. The spring container finds the beans definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans
ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an
instance of itself.

5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization()
methods will be called.

6. If an init-method is specified for the bean, it will be called.

7. Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called
ANS 14)
Container is used to describe any component that can contain other components inside itself.
As per the Spring documentation here
The BeanFactory interface is the central IoC container interface in Spring. Its
responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the
dependencies between these objects.
IOC is the core principle which Spring uses for Separation of concern concept . No matter what you use - Spring
MVC, Security , Core , DAO integrations , you will be using the IOC principle.
ANS 15)
ORM allows you to use java objects as representation of a relational database. It maps the two concepts (object-
oriented and relational)
Hibernate is an ORM framework - you describe how your objects are represented in your database, and hibernate
handles the conversion.

26
JDBC is the API for database access, and it works "in a relational way" - you query tables and get rows and columns
back. Hibernate uses JDBC under the hood to fetch the data and later convert it to objects.
A jdbc ResultSet has multiple records, and each record has a set of columns. In hibernate this becomes of
List<SomeClass> where SomeClass has a field for every column in the database table, and there
is one instance ofSomeClass` per database record.

I was reading on Hibernate and stumbled accross this thread. Doing further research, I found this other great
explanation which may help someone:
Hibernate framework simplifies the development of java application to interact with the database. Hibernate
is an open source, lightweight, ORM (Object Relational Mapping) tool.
An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique
that maps the object to the data stored in the database.

1 Advantages of Hibernate:
down
vote 1) Opensource and Lightweight: Hibernate framework is opensource under the LGPL license and
lightweight.
2) Fast performance: The performance of hibernate framework is fast because cache is internally used in
hibernate framework. There are two types of cache in hibernate framework first level cache and second level
cache. First level cache is enabled bydefault.
3) Database Independent query: HQL (Hibernate Query Language) is the object-oriented version of SQL. It
generates the database independent queries. So you don't need to write database specific queries. Before
Hibernate, If database is changed for the project, we need to change the SQL query as well that leads to the
maintenance problem.
4) Automatic table creation: Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.
5) Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework.
6) Provides query statistics and database status: Hibernate supports Query cache and provide statistics
about query and database status.

ANS 17)
Answer:
In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the
autowire attribute in <bean>. In Spring, 5 Auto-wiring modes are supported.

27
no: Default, no auto wiring, set it manually via ref attribute
byName: Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire
it.
byType: Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean
property, auto wire it.
constructor: byType mode in constructor argument.
autodetect: If a default constructor is found, use autowired by constructor; Otherwise, use autowire by type.
- See more at: http://www.java2novice.com/java_interview_questions/spring-autowire-
modes/#sthash.k5wW4v40.dpuf
(PLEASE REFER NOTES IN OTHER BOOK)
ANS 18) JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the
Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
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
Generates browser-specific code that makes an OBJECT or EMBED tag for the
jsp:plugin
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.

ANS 19)
Metadata is the data that describes your spring beans and their methods. Metadata can be added in multiple ways:
xml - <bean>

annotations (@Service, @Component, @Lazy, @Async, etc.)

javaconfig - again annotations, but meant to allow more flexibility - @Configuration, @Bean.

I don't know what "metadata programming" is meant to mean, but it's likely the use of the above annotations and
xml.
ANS 20)

28
Difference between Setter and Constructor Injection in Spring framework

As I said earlier Spring supports both setter and constructor Injection which are
two standard way of injecting dependency on beans managed by IOC constructor. Spring
framework doesn't support Interface Injection on which dependency is injected by
implementing a particular interface. In this section we will see couple of difference
between setter and constructor Injection, which will help you decide when to use setter
Injection over constructor Injection in Spring and vice-versa.

1) Fundamental difference between setter and constructor injection, as there name implies
is How dependency is injected. Setter injection in Spring uses setter methods like
setDependency() to inject dependency on any bean managed by Spring's IOC container.
On the other hand constructor injection uses constructor to inject dependency on any
Spring managed bean.

2) Because of using setter method, setter Injection in more readable than constructor
injection in Spring configuration file usually applicationContext.xml . Since setter
method has name e.g. setReporotService() by reading Spring XML config file you know
which dependency you are setting. While in constructor injection, since it uses index to
inject dependency, its not as readable as setter injection and you need to refer either Java
documentation or code to find which index corresponds to which property.

3) Another difference between setter vs constructor injection in Spring and one of the
drawback of setter injection is that it does not ensures dependency Injection. You can not
guarantee that certain dependency is injected or not, which means you may have an
object with incomplete dependency. On other hand constructor Injection does not allow
you to construct object, until your dependencies are ready.

4) One more drawback of setter Injection is Security. By using setter injection, you can
override certain dependency which is not possible which is not possible with constructor
injection because every time you call constructor, a new object is gets created.

5) One of our reader Murali Mohan Reddy, pointed out one more difference between Setter
and Constructor injection in Spring, where later can help, if there is a circular dependency
between two object A and B.
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring

29
throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A
object cannot be created until B is created and vice-versa. So spring can resolve circular
dependencies through setter-injection. Objects constructed before setter methods invoked.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for
configuring Spring we use XML files, readability is much bigger concern. Also drawback of
setter Injection around ensuring mandatory dependency injected or not can be handled by
configuring Spring to check dependency using "dependency-check" attribute of tag or
tag. Another worth noting point to remember while comparing Setter Injection vs
Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6
its handy manageable to passing dependency via constructor. Setter Injection is preferred
choice when number of dependency to be injected is lot more than normal, if some of
those arguments is optional than using Builder design pattern is also a good option.

In Summary both Setter Injection and Constructor Injection has there own advantage and
disadvantage. Good thing about Spring is that it doesn't restrict you to use either Setter
Injection or Constructor Injection and you are free to use both of them in one Spring
configuration file. Use Setter injection when number of dependency is more or you need
readability. Use Constructor Injection when Object must be created with all of its
dependency.

WIREFLOW
ANS 1)
Once an object is saved in a database, we can modify that object any number of times right, If we want to know how
many no of times that an object is modified then we need to apply this versioning concept.
When ever we use versioning then hibernate inserts version number as zero, when ever object is saved for the first
time in the database. Later hibernate increments that version no by one automatically when ever a modification is
done on that particular object.
In order to use this versioning concept, we need the following two changes in our application
Add one property of type int in our pojo class
In hibernate mapping file, add an element called version soon after id element
Files required to execute this program..
Product.java (My POJO class)
Product.hbm.xml (Xml mapping file )
hibernate.cfg.xml (Xml configuration file)
ClientForSave_1.java (java file to write our hibernate logic)
30
ClientForUpdate_2.java

Product.java

1 package str;
2
3 public class Product{
4
5 private int productId;
6 private String proName;
7 private double price;
8
9 private int v;
10
11 public void setProductId(int productId)
12 {
13 this.productId = productId;
14 }
15 public int getProductId()
16 {
17 return productId;
18 }
19
20 public void setProName(String proName)
21 {
22 this.proName = proName;
23 }
24 public String getProName()
25 {

31
26 return proName;
27 }
28
29 public void setPrice(double price)
30 {
31 this.price = price;
32 }
33 public double getPrice()
34 {
35 return price;
36 }
37
38 public void setV(int v)
39 {
40 this.v = v;
41 }
42 public int getV()
43 {
44 return v;
45 }
46 }

Product.hbm.xml

1 <?xml version="1.0"?>
2 <!DOCTYPE hibernate-mapping PUBLIC
3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

32
4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5
6 <hibernate-mapping>
7 <class name="str.Product" table="products">
8
9 <id name="productId" column="pid" />
10 <version name="v" column="ver" />
11 <property name="proName" column="pname" length="10"/>
12 <property name="price"/>
13
14 </class>
15 </hibernate-mapping>
Note:
In this above mapping file, find the <version> element, there i have given column name as version, actually
you can write any name its not predefined.

hibernate.cfg.xml

1 <?xml version='1.0' encoding='UTF-8'?>


2 <!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5
6 <hibernate-configuration>
7 <session-factory>
8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
9 </property>
10 <property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>

33
11 <property name="connection.username">system</property>
12 <property name="connection.password">admin</property>
13
14 <property name="dialect">org.hibernate.dialect.OracleDialect</property>
15 <property name="show_sql">true</property>
16 <property name="hbm2ddl.auto">update</property>
17
18 <mapping resource="Product.hbm.xml"></mapping>
19 </session-factory>
20 </hibernate-configuration>

ClientForSave_1.java

1 package str;
2
3 import org.hibernate.*;
4 import org.hibernate.cfg.*;
5
6 public class ClientForSave_1 {
7
8 public static void main(String[] args)
9 {
10
11 Configuration cfg = new Configuration();
12 cfg.configure("hibernate.cfg.xml");
13
14 SessionFactory factory = cfg.buildSessionFactory();
15 Session session = factory.openSession();

34
16 Product p=new Product();
17
18 p.setProductId(104);
19 p.setProName("AC");
20 p.setPrice(14000);
21
22 Transaction tx = session.beginTransaction();
23 session.save(p);
24 System.out.println("Object saved successfully.....!!");
25 tx.commit();
26 session.close();
27 factory.close();
28 }
29
30 }
Note:
Remember friends, first we must run the logic to save the object then hibernate will inset 0 (Zero) by default
in the version column of the database, its very important point in the interview point of view also
First save logic to let the hibernate to insert zero in the version column, then any number of update logics
(programs) we run, hibernate will increments +1 to the previous value
But if we run the update logic for the first time, hibernate will not insert zero..! it will try to increment the
previous value which is NULL in the database so we will get the exception.

ClientForUpdate_2.java

1 package str;
2
3 import org.hibernate.*;

35
4 import org.hibernate.cfg.*;
5
6 public class ClientForUpdate_2 {
7
8 public static void main(String[] args)
9 {
10
11 Configuration cfg = new Configuration();
12 cfg.configure("hibernate.cfg.xml");
13
14 SessionFactory factory = cfg.buildSessionFactory();
15 Session session = factory.openSession();
16 Object o=session.load(Product.class,new Integer(104));
17 Product s=(Product)o;
18
19 Transaction tx = session.beginTransaction();
20
21 s.setPrice(4000); // implicitly update method will be call
22
23 tx.commit();
24
25 System.out.println("Object Updated successfully.....!!");
26 session.close();
27 factory.close();
28 }
29
30 }
First run the ClientForSave_1.java, then only ClientForUpdate_2.java
&
Note(Important..!!!)______
Guys your know some thing.., actually we can run any logic (Save or Update) for the first time, but make sure the
versioning column is a number (>=0), but save logic has ability to insert zero by default if there is no value, and
36
update logic will directly tries to increments already existing value by 1, it wont insert any value by default if its
null, hope you are clear about this point, and mates its the very important concept in the interview point of view, if
you have any doubt just Ask a Question on this our team will respond ASAP
ANS 3)
1)
You can import a class file into your jsp and use as you use in your regular java class.

<%@ page import=" fully qualified name " %>

2)
A servlet can dispatch the instance of the java class to your jsp and your jsp can retrieve that object
from the request obj and use it.

ANS 4)

Exception Handling in JSP

The exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the
runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side
for the web developer. In JSP, there are two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file

process.jsp

1. <%@ page errorPage="error.jsp" %>

error.jsp

1. <%@ page isErrorPage="true" %>


2. <h3>Sorry an exception occured!</h3>
3. Exception is: <%= exception %>

HCL
ANS 2)

37
Parsing / Reading XML file in Java.

While working on a small requirement, I had to write a small piece of code that can parse an XML file in Java.
Although there are number of libraries available in Java which does this task efficiently, I ended up in using normal
Java XML parsing using org.w3c.dom parser.
You may want to copy this code and customize it to your to fit it for your need.
Following is the sample XML file that I used.
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>

Source Code of XML Parser

Following is the source code of sample XML parser in Java that I used to parse sample XML file.
package net.viralpatel.java.xmlparser;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class XMLParser {

38
public void getAllUserNames(String fileName) {

try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);

if (file.exists()) {
Document doc = db.parse(file);

Element docEle = doc.getDocumentElement();

// Print root element of the document

System.out.println("Root element of the document: "


+ docEle.getNodeName());

NodeList studentList = docEle.getElementsByTagName("student");

// Print total student elements in document

System.out
.println("Total students: " + studentList.getLength());

if (studentList != null && studentList.getLength() > 0) {


for (int i = 0; i < studentList.getLength(); i++) {

Node node = studentList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

System.out
.println("=====================");

Element e = (Element) node;


NodeList nodeList = e.getElementsByTagName("name");

System.out.println("Name: "

39
+ nodeList.item(0).getChildNodes().item(0)

.getNodeValue());

nodeList = e.getElementsByTagName("grade");

System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)

.getNodeValue());

nodeList = e.getElementsByTagName("age");

System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)

.getNodeValue());
}

}
} else {

System.exit(1);
}

}
} catch (Exception e) {

System.out.println(e);
}

}
public static void main(String[] args) {

XMLParser parser = new XMLParser();


parser.getAllUserNames("c:\\test.xml");

}
}

Following is the output of our XML parser

Program Output

Root element of the document: students


Total students: 3
==============================
Name: John
40
Grade: B
Age: 12
==============================
Name: Mary
Grade: A
Age: 11
==============================
Name: Simon
Grade: A
Age: 18
You can customize this code for your input XML file.
Finally i got the solution to my problem. thanks everyone who tried to help me :-)
Connection connection = null;
PreparedStatement getorgpstmt = null;
ResultSet rs = null;

connection = FQEDataBaseUtil.getConnection();
if(connection != null){
getorgpstmt = connection.prepareStatement(FQEOutboundConstants.getOrgId);

File folder = new File("D:\\Phani\\EAM-IN\\");


File[] listOfFiles = folder.listFiles();
String fileName=null;
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}

System.out.println(fileName);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


Document document;
DocumentBuilder builder = factory.newDocumentBuilder();
document=builder.parse(new File("D:\\Phani\\EAM-IN\\"+fileName));
document.getDocumentElement().normalize();
NodeList nList = document.getElementsByTagName("WORKORDER");
FQoutDataObj = new FQOutboundData();
for (int temp = 0; temp < nList.getLength(); temp++) {

org.w3c.dom.Node nNode = nList.item(temp);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

FQoutDataObj.setMessagetype(eElement.getElementsByTagName("MESSAGETYPE").item(0).getTextConte
nt());

FQoutDataObj.setWorkordernumber(eElement.getElementsByTagName("WORKORDERNUMBER").item(0).getT
extContent());

FQoutDataObj.setDeviceid(eElement.getElementsByTagName("DEVICEID").item(0).getTextContent());

41
FQoutDataObj.setCalibratedby(eElement.getElementsByTagName("CALIBRATEDBY").item(0).getTextCon
tent());

FQoutDataObj.setSignedby(eElement.getElementsByTagName("SIGNEDBY").item(0).getTextContent());

FQoutDataObj.setSignedbyid(eElement.getElementsByTagName("SIGNEDBYID").item(0).getTextContent
());

FQoutDataObj.setCalibrationpassed(eElement.getElementsByTagName("CALIBRATIONPASSED").item(0).
getTextContent());

FQoutDataObj.setAsfoundpassed(eElement.getElementsByTagName("ASFOUNDPASSED").item(0).getTextC
ontent());

FQoutDataObj.setWorkinghours(eElement.getElementsByTagName("WORKINGHOURS").item(0).getTextCon
tent());
FQoutDataObj.setUsername(FQEOutboundConstants.Username);
FQoutDataObj.setPassword(FQEOutboundConstants.Password);

getorgpstmt.setString(1,eElement.getElementsByTagName("WORKORDERNUMBER").item(0).getTextConte
nt());

getorgpstmt.executeQuery();

}
}
}

return FQoutDataObj;
}

public FQOutboundData readAllFiles(FQOutboundData FQOutboundDataBean) throws FQEException{

String path = "D:\\Phani\\EAM-IN\\";

String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++)


{

if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".xml") || files.endsWith(".XML"))
{
System.out.println("All xmls read in flolder are "+files);

Connection connection = null;


PreparedStatement dummyPstmt = null;
PreparedStatement intablePstmt = null;
PreparedStatement transidPstmt = null;

ResultSet rs = null;

42
try {
connection = FQEDataBaseUtil.getConnection();
if(connection != null){
dummyPstmt = connection.prepareStatement(FQEOutboundConstants.INSERT_EC_DUMMY);
intablePstmt =
connection.prepareStatement(FQEOutboundConstants.INSERT_HISTORY_TABLE);

int updatedummy = dummyPstmt.executeUpdate();


System.out.println("Dummy record updated to table to create a transid");

if (updatedummy!=0){

transidPstmt=
connection.prepareStatement(FQEOutboundConstants.GET_NEXT_TRANSID);
rs = transidPstmt.executeQuery();
if(rs != null){
while(rs.next()){
int newTransId = rs.getInt("TRANSID");

FQOutboundData FQobj = readtoBean(FQOutboundDataBean);


String workorderId = FQobj.getWorkordernumber().substring(8);
intablePstmt.setInt(1,newTransId);
intablePstmt.setString(2,FQobj.getMessagetype());
intablePstmt.setString(3,workorderId);
intablePstmt.setString(4,FQobj.getDeviceid());
intablePstmt.setString(5,FQobj.getCalibratedby());
intablePstmt.setString(6,FQobj.getSignedby());
intablePstmt.setString(7,FQobj.getSignedbyid());
intablePstmt.setString(8,FQobj.getCalibrationpassed());
intablePstmt.setString(9,FQobj.getAsfoundpassed());
intablePstmt.execute();
System.out.println("Data is inserted in the IN table");
}
}
}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(intablePstmt != null){
intablePstmt.close();
}

if(connection != null){

43
connection.close();
}
} catch (SQLException e) {
}
}

}
}

}
return FQOutboundDataBean;
}}

Not Company Related


ANS 1)
Session factory objects are to be implemented using the singleton design pattern. Instances of SessionFactory are
thread-safe and typically shared throughout an application. As these objects are heavy weight because they contains
the connection information, hibernate configuration information and mapping files,location path. So creating
number of instances will make our application heavy weight. But the session objects are not thread safe. So in short
it is - SessionFactory objects are one per application and Session objects are one per client.
Hence it would be one SessionFactory per DataSource. Your application may have more than one DataSource so
you may have more than one SessionFactory in that instance. But you would not want to create a SessionFactory
more than once in an application.
ANS 2)
Criteria Api is one of the good concept of Hibernate. according to my view these are the few point by which we can
make difference between HQL and Criteria Api
1. HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the
data, we cannot perform non-select operations using criteria.
2. HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
3. HQL doesnt support pagination concept, but we can achieve pagination with Criteria.
4. Criteria used to take more time to execute than HQL.
5. With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your
queries are either fixed or parametrized, there is no safe from SQL Injection
MIND TREE
ANS 1)
Similar to scope and lifetime of variables in Java as you have seen in blocks-and-methods-in-java, parameters and
attributes in a Java EE web application also have scope and lifetime in the context of the web application. The scope
of a parameter/attribute denotes the availability of that parameter/attribute for use. A web application serves multiple

44
requests from clients when it is up and running. These requests can be from same client or different clients. We have
seen from the servlet life cycle that a servlets service() method is called every time a request comes.
Different scopes are request, session and application. JSP has an additional scope called page scope.

Application or context scope

Context scope or application scope starts from the point where a web application is put into service (started)
till it is removed from service (shutdown) or the web application is reloaded. Parameters/attributes within the
application scope will be available to all requests and sessions.
Application scope is denoted by javax.servlet.ServletContext interface.
Application object is available in a JSP page as an implicit object called application.
In a servlet, you can get application object by calling getServletContext() from within the servlets code
directly (the servlet itself implements the ServletConfig interface that contains this method) or by explicitly
calling getServletConfig().getServletContext().
The web container provides one ServletContext object per web application per jvm.

Request scope

Request scope start from the moment an HTTP request hits a servlet in our web container and end when the
servlet is done with delivering the HTTP response.
With respect to the servlet life cycle, the request scope begins on entry to a servlets service() method and
ends on the exit from that method.
A request scope parameter/attribute can be accessed from any of servlets or jsps that are part of serving one
request. For example, you call one servlet/jsp, it then calls another servlet/jsp and so on, and finally the
response is sent back to the client.
Request scope is denoted by javax.servlet.http.HttpServletRequest interface.
Container passes the request object as an argument of type HttpServletRequest to Servlet's service method.
Request object is available in a JSP page as an implicit object called request. You can set value for an
attribute in request object from a servlet and get it from a JSP within the same request using the implicit
request object.

Session scope

A session scope starts when a client (e.g. browser window) establishes connection with our web application
till the point where the browser window is closed.
Session scope spans across multiple requests from the same client.

45
A noteable feature of tabbed browsing is that session is shared between the tabs and hence you can requests
from other tabs too during a session without logging in again. For instance, you can load your gmail inbox in
another tab without logging in again. This also means browsing an unknown site and a secure site from
different tabs from the same browser can expose your secure session ID to malicious applications. So always
open a new browser window when you want to do secure transactions, especially financial transactions.
Session scope is denoted by javax.servlet.http.HttpSession interface.
Session object is available in a JSP page as an implicit object called session.
In a servlet, you can get Session object by calling request.getSession().

JSP page scope

The page scope restricts the scpoe and lifetime of attributes to the same page where it was created.
Page scope is denoted by javax.servlet.jsp.PageContext abstract class.
It is available in a JSP page as an implicit object called pageScope .

ANS 4)
One of the most powerful features of JSP is that a JSP page can access, create, and modify data objects on the
server. You can then make these objects visible to JSP pages. When an object is created, it defines or defaults to a
given scope. The container creates some of these objects, and the JSP designer creates others.
The scope of an object describes how widely it's available and who has access to it. For example, if an object is
defined to have page scope, then it's available only for the duration of the current request on that page before being
destroyed by the container. In this case, only the current page has access to this data, and no one else can read it. At
the other end of the scale, if an object has application scope, then any page may use the data because it lasts for the
duration of the application, which means until the container is switched off.

Page Scope

Objects with page scope are accessible only within the page in which they're created. The data is valid only during
the processing of the current response; once the response is sent back to the browser, the data is no longer valid. If
the request is forwarded to another page or the browser makes another request as a result of a redirect, the data is
also lost.
//Example of JSP Page Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="page" />

Request Scope

Objects with request scope are accessible from pages processing the same request in which they were created. Once
the container has processed the request, the data is released. Even if the request is forwarded to another page, the
data is still available though not if a redirect is required.

46
//Example of JSP Request Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="request" />

Session Scope

Objects with session scope are accessible from pages processing requests that are in the same session as the one in
which they were created. A session is the time users spend using the application, which ends when they close their
browser, when they go to another Web site, or when the application designer wants (after a logout, for instance). So,
for example, when users log in, their username could be stored in the session and displayed on every page they
access. This data lasts until they leave the Web site or log out.
//Example of JSP Session Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="session" />

Application Scope

Objects with application scope are accessible from JSP pages that reside in the same application. This creates a
global object that's available to all pages.
Application scope uses a single namespace, which means all your pages should be careful not to duplicate the names
of application scope objects or change the values when they're likely to be read by another page (this is called
thread safety). Application scope variables are typically created and populated when an application starts and then
used as read-only for the rest of the application.
//Example of JSP Application Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="application" />

ANS 5)
As per Spring documentation ::
session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-
aware Spring ApplicationContext.
global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
ANS 6)
The init method is designed to be called only once. It is called when the servlet is first created, and not called again
for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also
specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a
new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data
that will be used throughout the life of the servlet.

47
When is destroy of servlets called?

The destroy() method is called by container before removing a servlet instance from service and gives servlet an
opportunity to clean up any resources being held (for example, memory, file handles, threads) and make sure that
any persistent state is synchronized with the servlet's current state in memory.
The destroy() and init() methods are called only once in a servlet's lifetime while the service() method may
be called multiple times. The destory() will be called :

when the container shuts down or the application shuts down;


when the container decides that there is a shortage of memory;
when this servlet hasn't got a request in a long time.
After the servlet container calls this method, it will not call the service method again on this servlet.
ADITI TECHNOLOGIES
ANS 2)
Normal Hibernate Configurartion
<property name="connection.pool_size">1</property>
Providing a connection pool for an application that uses Hibernate is pretty easy, as a matter of fact Hibernate
supports a variety of connection pooling mechanisms. If you are using an application server, you may wish to use
the built-in pool (typically a connection is obtaining using JNDI).
For example, this is a sample hibernate.cfg.xml configuration file that is used to handle connections to a MySQL
database which is bound into the JNDI as java:jboss/datasources/MySqlDS
1
<hibernate-configuration>
2 <session-factory>
3 <property name="dialect">

4 org.hibernate.dialect.MySQLDialect

5 </property>
<property name="connection.datasource">java:jboss/datasources/MySqlDS</property>
6
</session-factory>
7
</hibernate-configuration>
8
If you can't or don't wish to use your application server's built-in connection pool, Hibernate supports several other
connection pools such as:

c3p0 http://sourceforge.net/projects/c3p0 Distributed with Hibernate

Apache http://jakarta.apache.org/commons/dbcp/ Apache Pool


DBCP

48
Proxool http://proxool.sourceforge.net/ Distributed with Hibernate

Configure C3P0 Connection Pool

Here's a sample configuration for the built-in Connection pool:


1
<hibernate-configuration>
2
<session-factory>
3 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
4 <property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/myschema</property>
5
<property name="hibernate.connection.username">user</property>
6
<property name="hibernate.connection.password">password</property>
7
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
8 <property name="show_sql">true</property>
9
10 <property name="hibernate.c3p0.min_size">5</property>

11 <property name="hibernate.c3p0.max_size">20</property>

12 <property name="hibernate.c3p0.timeout">300</property>

<property name="hibernate.c3p0.max_statements">50</property>
13
<property name="hibernate.c3p0.idle_test_period">3000</property>
14
15
. . . .
16
</session-factory>
17
And some explanation about the properties:
hibernate.c3p0.min_size Minimum number of JDBC connections in the pool. Hibernate default: 1
hibernate.c3p0.max_size Maximum number of JDBC connections in the pool. Hibernate default: 100
hibernate.c3p0.timeout When an idle connection is removed from the pool (in second). Hibernate default: 0,
never expire.
hibernate.c3p0.max_statements Number of prepared statements will be cached. Increase performance. Hibernate
default: 0 , caching is disable.
hibernate.c3p0.idle_test_period idle time in seconds before a connection is automatically validated. Hibernate
default: 0

Configure Apache DBCP Connection Pool

Apache Connection Pool can be downloaded from http://commons.apache.org/dbcp/

49
In order to integrate this pool with Hibernate you will need the following jars: commons-dbcp.jar and commons-
pool-1.5.4.jar.
Here's a sample configuration in hibernate.cfg.xml:
<hibernate-configuration>

<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myschema</property>
<property name="hibernate.connection.username">user</property>

<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="show_sql">true</property>

<property name="hibernate.dbcp.initialSize">8</property>
<property name="hibernate.dbcp.maxActive">20</property>

<property name="hibernate.dbcp.maxIdle">20</property>
<property name="hibernate.dbcp.minIdle">0</property>

</session-factory>

ANS 3)

Testing frameworks for Java

There are several testing frameworks available for Java. The most popular ones are JUnit and TestNG.
This description focuses at JUnit.

Using JUnit

5.1. The JUnit framework

JUnit in version 4.x is a test framework which uses annotations to identify methods that specify a test.
The main websites for JUnit are the JUnit homepage and the GitHub project page.

5.2. How to define a test in JUnit?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class.
To write a test with the JUnit 4.x framework you annotate a method with the @org.junit.Test annotation.

50
In this method you use an assert method, typically provided by the JUnit or another assert framework, to check the
expected result of the code execution versus the actual result. These method calls are typically called asserts or
assert statements.
You should provide meaningful messages in assert statements so that it is easier for the developer to identify the
problem. This helps in fixing the issue, especially if someone looks at the problem, who did not write the code under
test or the test code.

5.3. Example JUnit test

The following code shows a JUnit test. This test assumes that the MyClass class exists and has a multiply(int,
init) method.
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MyTests {

@Test
public void multiplicationOfZeroIntegersShouldReturnZero() {

// MyClass is tested
MyClass tester = new MyClass();

// assert statements
assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
}

ANS 5)
Log4j is a JavaSW library that specializes in logging. At the time of this writing, its home page is at
http://logging.apache.org/log4j/docs/ . The Java library itself is available for download at
http://logging.apache.org/site/binindex.cgi . The short manual at http://logging.apache.org/log4j/docs/manual.html
does a great job covering many of the standard features of Log4j. At its most basic level, you can think of it as a
replacement for System.out.println's in your code. Why is it better than System.out.println's? The reasons are
numerous.
To begin with, System.out.println outputs to standard output, which typically is a console window. The output from
Log4j can go to the console, but it can also go to an email server, a databaseW table, a log file, or various other
destinations.
Another great benefit of Log4j is that different levels of logging can be set. The levels are hierarchical and are as
follows: TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. If you set a particular log level, messages will get
logged for that level and all levels above it, and not for any log levels below that. As an example, if your log level is
set to ERROR, you will log messages that are errors and fatals. If your log level is set to INFO, you will log
messages that are infos, warns, errors, and fatals. Typically, when you develop on your local machine, it's good to
set the log level to DEBUG, and when you deploy a web application, you should set the log level to INFO or higher
so that you don't fill up your error logs with debug messages.

51
Log4j can do other great things. For instance, you can set levels for particular Java classes, so that if a particular
class spits out lots of warnings, you can set the log level for that class to ERROR to suppress all the warning
messages.
Typically, you can configure Log4j via a configuration file. This means that you can change your logging
configuration without requiring code updates. If you need to do something like set the log level to DEBUG for your
deployed application in order to track down a particular bug, you can do this without redeploying your application.
Instead, you can change your log configuration file, reread the configuration file, and your logging configuration
gets updated.
Let's try out Log4j. First off, we can download the log4j jarW file from the address mentioned above. I downloaded
the jar file and added it to my project's build path.

I created a Log4JTest class. In this class, notice that I have a static Logger object called log, and this object is
obtained from Logger.getLogger, with the Log4JTest class passed as a parameter to getLogger. This is basically
saying that we have a Logger object that we can use in our Log4JTest class, and that the Log4JTest.class is the name
that the logger is recognized as. In the main method, we have one log.debug call. Let's see what happens if we try to
run our class at this stage.

52
So, does this mean that Log4j doesn't work? Actually, if we read the console output, we can see that the problem is
that we need to initialize Log4j. This is typically done via a Configurator. If we were using a properties file to set the
logging configuration, we would use the PropertyConfigurator class, but for the sake of simplicity, let's use
BasicConfigurator, which gives us a plain vanilla Log4j configuration without requiring any properties to be set. A
call to the configure() method initializes Log4j, after which we can use the static Logger object in our class (and any
other loggers throughout our application). If we now execute our class, we see the following:

53
Log4j outputs our "This is a debug message" to the console. The number at the front of the line is the number of
milliseconds since the application started. The [main] indicates the name of the thread. In addition, the line displays
the log level (DEBUG) and the class name that we specified in our Logger.getLogger method call.
Let's make some trivial tweaks to the test class and execute it, as shown below.

54
In this example, I changed the logger's identifier to be "bacon" rather than the class name. However, it's typical to
use the class's name as its identifier. I added a method that throws and catches an exception, and displays an
exception message and the stack trace for that exception. It also displays an info message.
Although the Log4JTest class is trivial and not very useful, it's included below.

Log4JTest.java
package test;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Log4JTest {


static Logger log = Logger.getLogger("bacon");

55
public static void main(String[] args) {
BasicConfigurator.configure();
log.debug("This is a debug message");
myMethod();
log.info("This is an info message");
}

private static void myMethod() {


try {
throw new Exception("My Exception");
} catch (Exception e) {
log.error("This is an exception", e);
}
}
}

ANS 6)
Currently (as of version 3.2) the procedure for deploying a new WAR file is:
1. Stop Tomcat.
2. Delete existing deployment. If you have previously deployed "foo.war" in
TOMCAT_HOME/webapps, then it has been unpacked into webapps/foo/... You must delete this
directory and all its contents. On Unix, this can be done with
rm -r $TOMCAT_HOME/webapps/foo
3. Copy WAR file to TOMCAT_HOME/webapps/.
4. Start Tomcat.

ANS 7)

Web application testing methodologies

In this article, web application refers to all applications that are accessed through a browser. This section outlines
some of the testing methodologies you can use to test your web applications.

Usability testing

For an application to be effective, the user interfaces should comply to standards. Follow globally accepted
conventions wherever applicable. For example, color coding conventions indicate that red is used to stop a process
and green to start one.
Usability testing plays a pivotal role with applications that are designed to make manual tasks easier. The
applications should comply with accessibility standards. For example, the widely used Captcha code has an option
for spelling for people who are visually challenged.
Keep the following guidelines in mind when undertaking usability testing:

56
Ensure proper navigation between web pages.
Be sure to have a site map.
Use appropriate color combinations and best practices.
Avoid over-crowded content.
Practice user friendliness to all types of users, from novice to expert.
Provision support for physically challenged people.

User acceptance testing

The objective of user acceptance testing is to make sure your application meets the expectations of the user. It
ensures that the application is fit enough to be deployed and used effectively. The following are tips for user
acceptance testing:
Ensure browser compatibility.
Make sure that mandatory fields are given data in forms.
Check for time outs and field widths.
Be sure that proper control is used to feed data. For example, when requesting gender information, use an
option button.
Alpha and beta testing are the two types of user acceptance testing.
Alpha testing
Testing in a development environment by developers.
Beta testing
Testing in a deployment or client environment by end users.

Performance testing

Performance testing on web applications measures the performance under various scenarios. Performance tests
include:
Stress testing
To determine the maximum performance limits of an application.
Scalability testing
To find out how adaptable the application is to changes in software and hardware.
Load testing
To get an idea of how the application behaves under a heavy load. This test yields information and details
about memory usage, CPU usage, and so forth.

57
Security testing

Security testing for your application is very important if data leaks or modifications are unacceptable and
intolerable. For example, if a university application includes the academic grades of a student, then security testing
should ensure that the system cannot be hacked. For e-commerce applications, which sometimes involve banking
transactions, security testing is critical. It should also ensure that sufficient authentication and authorization
mechanisms are in place.
Security testing can be static or dynamic.
Static
Static testing involves doing a static code analysis to check for any vulnerabilities. The goal is to understand
the code flow and check for security threats by walking through the code.
Dynamic
Dynamic testing entails running the application to see if the response is as expected for the associated
request. It is very similar to black box testing.

Functional testing

Functional testing ensures that individual functions are working well. Test cases should ensure that boundary
conditions are tested. Invalid inputs should prompt appropriate error messages.
In web applications, functional testing can range from testing whether links are working to checking whether
changes made by users in a web page are reflected in the database. Some of the functional tests for web applications
include:
Database testing
Configuration testing
Compatibility testing
Flow testing

Interface testing

Conduct interface testing to ensure that individual components are connected properly. The output of one module
should be fed to the intended module without any issues. Interface testing plays a vital role for your applications that
are developed to work on multiple platforms. The following are considerations to keep in mind during interface
testing:
Ensure that data flow occurs smoothly and as expected between modules in a single application and between
applications.
Ensure that the interfaces exposed by components are generic and extensible. They should be able to
accommodate changes to the components while remaining backward compatible.
Back to top

58
Web application testing tools

This section summarizes the various testing techniques and tools available for testing web application technologies.
See Resources for links to the tools mentioned in this article.
Basic web applications that have primarily HTML content can be tested with the following tools:

Hypertext markup language (HTML)

An IBM tool that can test several web application technologies, including HTML, using a
Rational Functional
record and playback method. You can also edit and customize the recorded script to suit
Tester (RFT)
your needs.
Selenium An open source project based on a record and playback test framework.
Testing your client-side script is essential for proper validation. JavaScript can be tested using the following tools:

JavaScript

JSpec A testing framework with its own grammar and preprocessor. It supports multiple modes of testing.
RhinoUnit An Ant-based JavaScript testing framework for performing unit testing.

Dojo testing

For Dojo, Dojo Objective Harness (DOH) testing provides both command line and browser support. DOH is
flexible and easy to use.
For testing RIA-based applications such as Flex, you can use the following:

Adobe Flex

FlexMonkey A record and playback-based testing framework for Flex applications. It is an open source tool.
FlexUISelenium An extension to the Selenium test framework for testing Flex applications.
You need to test the HTML links in your website to be sure that none are broken. Many online and offline tools are
available for this type of testing, including:

HTML links

WebLight A tool used for testing broken links and non-standard HTML.

59
LinkTiger.com An online analysis of broken links for your websites.
Corresponding test frameworks are available for server-side scripts such as PHP, ASP, and JSP.

Server-side scripting

PHPUnit A unit testing framework for PHP based on JUnit for Java.
ASPUnit A unit testing framework for ASP.
Cactus A JSP test framework from Apache.
A website should be resistant to hacking attempts and denial of service attacks. Security threats can include SQL
injection, command injection, cross-site scripting, and server configuration errors. An array of tools is available for
security testing.

Web application security testing

Nikto An open source tool used for checking web servers for security flaws.
An IBM tool that supports automatic test creation and modification. It can also be
Rational AppScan
easily integrated into existing testing environments.
Acunetix Web
A tool that helps check cross-site scripting and other similar vulnerabilities.
Vulnerability Scanner
Make sure that the web content for your site is uniform in all browsers. Be aware that some functions are browser-
dependent; users will expect and use functions specific to their chosen browser. Several tools are available for
browser testing, including:

Browser compatibility testing

A tool that can perform various tasks, such as checking element alignment, showing
Microsoft Expression
attributes of DOM elements, and rendering in different sizes. The overlay layout
Web SuperPreview
feature helps you compare two browser views of a page.
An online-based solution from Adobe that lets you test a website in various browsers
Adobe Browser Labs
and versions. It has features to change the page size and take snapshots of the screen.

ANS 13)

60
Top 10 Java Debugging Tips with Eclipse

In this tutorial we will see about debugging java applications using Eclipse. Debugging helps us to identify and fix
defects in the application. We will focus on run-time issues and not compile time errors. There are command line
debuggers like gdb available. In this tutorial we will focus on GUI based debugger and we take our favourite IDE
Eclipse to run through the tutorial. Though we say Eclipse, the points are mostly generic and is suitable for
debugging using most of the IDEs like NetBeans too.
Before going through this tutorial, I recommend you to have a look at Eclipse shortcuts and it will really help. My
Eclipse version is Juno as of writing this tutorial.
Do not use System.out.println as a tool to debug.
Enable detailed log level of all the components involved.
Use a log analyzer to read logs.

1. Conditional Breakpoint

Hope we know how to add a breakpoint. If not, just click on the left pane (just before the line number) and a
breakpoint will be created. In debug perspective, Breakpoints view will list the breakpoint created. We can add a
boolean condition to it. That is, the breakpoint will be activated and execution will hold only if the boolean
condition is met otherwise this breakpoint will be skipped.

2. Exception Breakpoint

In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint.
For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a
breakpoint using this.

61
3. Watch Point

This is one nice feature I love. When a chosen attribute is accessed or modified program execution will halt and
allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This
will create a watch point for that attribute and it will be listed in Breakpoints view.

62
4. Evaluation (Display or Inspect or Watch)

Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent
watch on an expression/variable which will be shown in Expressions view when debug is on.

63
5. Change Variable Values

We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and
select the value, type and enter.

6. Stop in Main

In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we
debug a java program that launches with a main method, the execution halts at first line of main method.

64
7. Environment Variables

Instead of going to System properties to add an environment variable, we can conveniently add it through Edit
Configuration dialog box.

65
8. Drop to Frame

This is the second best feature I love. We can just return the control to any frame in the call stack during debug.
Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug
from there and click the drop to frame button from debug toolbar. Eclipse is cool!

66
9. Step Filter

When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add
a filter in preferences and exclude packages.

67
10. Step Into, Over and Return

I kept this as the last point as this is the first thing to learn in debugging :-)
F5 Step Into: moves to next step and if the current line has a method call the control will go into the first
line of the called method.
F6 Step Over: moves the control to next line. If there is a method call in the current line, it executes the
method call internally and just moves the control to next line.
F7 Step Return: When done from inside a method the control will move to the calling line from where the
current method is invoked.
F8 Move to next breakpoint.

68
ANS 14)
Once an application finds an exception, responds an exception by throwing another exception. It causes another
exception. Knowing an exception that causes another exception is very useful.

Chained exceptions helps in finding the root cause of the exception that occurs during applications execution. The
methods that support chained exceptions are getCause(), initCause() and the constructors Throwable(Throwable),
Throwable(String, Throwable). The reason / cause for the current exception is returned by the method getCause().
With initCause() method, the current exceptions cause is set.
We need to chain the exceptions to make logs readable.
Take following examples of 1. without chaining and 2. chaining, exceptions to feel the difference
Create following Exceptions
class NoLeaveGrantedException extends Exception {

public NoLeaveGrantedException(String message, Throwable cause) {


super(message, cause);
}

public NoLeaveGrantedException(String message) {


super(message);
}
}

class TeamLeadUpsetException extends Exception {

public TeamLeadUpsetException(String message, Throwable cause) {


super(message, cause);
}

public TeamLeadUpsetException(String message) {


super(message);
}
}

class ManagerUpsetException extends Exception {

69
public ManagerUpsetException(String message, Throwable cause) {
super(message, cause);
}

public ManagerUpsetException(String message) {


super(message);
}
}

class GirlFriendOfManagerUpsetException extends Exception {

public GirlFriendOfManagerUpsetException(String message, Throwable cause) {


super(message, cause);
}

public GirlFriendOfManagerUpsetException(String message) {


super(message);
}
}
Now use them
1. Without chaining
public class MainClass {

public static void main(String[] args) throws Exception {


getLeave();
}

static void getLeave() throws NoLeaveGrantedException {


try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
e.printStackTrace();
throw new NoLeaveGrantedException("Leave not sanctioned.");
}
}

static void howIsTeamLead() throws TeamLeadUpsetException {


try {
howIsManager();
} catch (ManagerUpsetException e) {
e.printStackTrace();
throw new TeamLeadUpsetException(
"Team lead is not in good mood");
}
}

static void howIsManager() throws ManagerUpsetException {


try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
e.printStackTrace();
throw new ManagerUpsetException("Manager is in bad mood");
}

static void howIsGirlFriendOfManager()


throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException(
70
"Girl friend of manager is in bad mood");
}
}

2. Chaining
3. public class MainClass {
4.
5. public static void main(String[] args) throws Exception {
6. getLeave();
7. }
8.
9. static void getLeave() throws NoLeaveGrantedException {
10. try {
11. howIsTeamLead();
12. } catch (TeamLeadUpsetException e) {
13. throw new NoLeaveGrantedException("Leave not sanctioned.", e);
14. }
15. }
16.
17. static void howIsTeamLead() throws TeamLeadUpsetException {
18. try {
19. howIsManager();
20. } catch (ManagerUpsetException e) {
21. throw new TeamLeadUpsetException(
22. "Team lead is not in good mood", e);
23. }
24. }
25.
26. static void howIsManager() throws ManagerUpsetException {
27. try {
28. howIsGirlFriendOfManager();
29. } catch (GirlFriendOfManagerUpsetException e) {
30. throw new ManagerUpsetException("Manager is in bad mood", e);
31. }
32.
33. }
34.
35. static void howIsGirlFriendOfManager()
36. throws GirlFriendOfManagerUpsetException {
37. throw new GirlFriendOfManagerUpsetException(
38. "Girl friend of manager is in bad mood");
39. }
40. }

Now compare logs


1. Without chaining
com.bskyb.svod.autoingest.GirlFriendOfManagerUpsetException: Girl friend of manager is in
bad mood
at com.bskyb.svod.autoingest.MainClass.howIsGirlFriendOfManager(MainClass.java:61)
at com.bskyb.svod.autoingest.MainClass.howIsManager(MainClass.java:52)
at com.bskyb.svod.autoingest.MainClass.howIsTeamLead(MainClass.java:43)
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:34)
at com.bskyb.svod.autoingest.MainClass.main(MainClass.java:29)
com.bskyb.svod.autoingest.ManagerUpsetException: Manager is in bad mood
at com.bskyb.svod.autoingest.MainClass.howIsManager(MainClass.java:55)

71
at com.bskyb.svod.autoingest.MainClass.howIsTeamLead(MainClass.java:43)
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:34)
at com.bskyb.svod.autoingest.MainClass.main(MainClass.java:29)
com.bskyb.svod.autoingest.TeamLeadUpsetException: Team lead is not in good mood
at com.bskyb.svod.autoingest.MainClass.howIsTeamLead(MainClass.java:46)
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:34)
at com.bskyb.svod.autoingest.MainClass.main(MainClass.java:29)
Exception in thread "main" com.bskyb.svod.autoingest.NoLeaveGrantedException: Leave not
sanctioned.
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:37)
at com.bskyb.svod.autoingest.MainClass.main(MainClass.java:29)
2. Chaining
Exception in thread "main" com.bskyb.svod.autoingest.NoLeaveGrantedException: Leave not
sanctioned.
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:36)
at com.bskyb.svod.autoingest.MainClass.main(MainClass.java:29)
Caused by: com.bskyb.svod.autoingest.TeamLeadUpsetException: Team lead is not in good
mood
at com.bskyb.svod.autoingest.MainClass.howIsTeamLead(MainClass.java:44)
at com.bskyb.svod.autoingest.MainClass.getLeave(MainClass.java:34)
... 1 more
Caused by: com.bskyb.svod.autoingest.ManagerUpsetException: Manager is in bad mood
at com.bskyb.svod.autoingest.MainClass.howIsManager(MainClass.java:52)
at com.bskyb.svod.autoingest.MainClass.howIsTeamLead(MainClass.java:42)
... 2 more
Caused by: com.bskyb.svod.autoingest.GirlFriendOfManagerUpsetException: Girl friend of
manager is in bad mood
at com.bskyb.svod.autoingest.MainClass.howIsGirlFriendOfManager(MainClass.java:58)
at com.bskyb.svod.autoingest.MainClass.howIsManager(MainClass.java:50)
... 3 more

MERRITRAC PRIVATE LIMITED


ANS 1)
Composite primary keys means having more than one primary key, let us see few points on this concept
If the table has a primary key then in the hibernate mapping file we need to configure that column by using
<id /> element right..!
Even though the database table doesnt have any primary key, we must configure one column as id (one
primary key is must)
If the database table has more than one column as primary key then we call it as composite primary key, so
if the table has multiple primary key columns , in order to configure these primary key columns in the
hibernate mapping file we need to use one new element called <composite-id ..> </composite-id>
To map a composite key, you can use the EmbeddedId or the IdClass annotations. I know this question is not
strictly about JPA but the rules defined by the specification also applies. So here they are:

2.1.4 Primary Keys and Entity Identity

...

72
A composite primary key must correspond to either a single persistent field or property or to a set of such fields or
properties as described below. A primary key class must be defined to represent a composite primary key.
Composite primary keys typically arise when mapping from legacy databases when the database key is comprised
of several columns. The EmbeddedId and IdClass annotations are used to denote composite primary keys. See
sections 9.1.14 and 9.1.15.
...
The following rules apply for composite primary keys:
The primary key class must be public and must have a public no-arg constructor.
If property-based access is used, the properties of the primary key class must be public or protected.
The primary key class must be serializable.

The primary key class must define equals and hashCode methods. The semantics of value equality for
these methods must be consistent with the database equality for the database types to which the key is
mapped.
A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14,
EmbeddedId Annotation) or must be represented and mapped to multiple fields or properties of the entity
class (see Section 9.1.15, IdClass Annotation).
If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of
primary key fields or properties in the primary key class and those of the entity class must correspond and
their types must be the same.

With an IdClass

The class for the composite primary key could look like (could be a static inner class):
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;

public TimePK() {}

public TimePK(Integer levelStation, Integer confPathID) {


this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
@Id
private Integer levelStation;
@Id
private Integer confPathID;

private String src;


private String dst;

73
private Integer distance;
private Integer price;

// getters, setters
}
The IdClass annotation maps multiple fields to the table PK.

With EmbeddedId

The class for the composite primary key could look like (could be a static inner class):
@Embeddable
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;

public TimePK() {}

public TimePK(Integer levelStation, Integer confPathID) {


this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
class Time implements Serializable {
@EmbeddedId
private TimePK timePK;

private String src;


private String dst;
private Integer distance;
private Integer price;

//...
}
The @EmbeddedId annotation maps a PK class to table PK.

ANS 3)
public class Example {
public static void main(String[] args) {
// insert code here
try {
new Example().go();
// throw new OutOfMemoryError();
} catch (Error e) {
System.out.println(e);
}
}

void go() {
go();
}

74
}
With following output :
java.lang.StackOverflowError
Answer to your question is yes, you can catch error in java. And your code is almost correct. Your method
go() calls itself infinitely and therefore causes StackOverflowError that is caught in your catch block and
printed by System.out.println()

ANS 7)
The JVM only deals with method overriding. A method is overridden by adding a method with the same signature in
a derived class (the only allowed difference is in the return type, which is allowed to be more specific). The
signature encodes the method's name, as well as the types of the parameters and the return type.
Method overloading means having multiple methods with the same "simple name" but different signatures. At
compile time, the javac compiler chooses one of the same-named methods based on the types of the arguments and
places its signature in the compiled .class file. A method invocation in compiled Java bytecode must specify the
signature of the callee.
Not Company Related
ANS 1)
Hibernate detects that the @Id annotation is on a field and assumes that it should access properties on an object
directly through fields at runtime. If you placed the @Id annotation on the getId() method, you would enable access
to properties through getter and setter methods by default. Hence, all other annotations are also placed on either
fields or getter methods, following the selected strategy. Following section will explain the annotations used in the
above class.

@Entity Annotation:

The EJB 3 standard annotations are contained in the javax.persistence package, so we import this package as the
first step. Second we used the @Entity annotation to the Employee class which marks this class as an entity bean,
so it must have a no-argument constructor that is visible with at least protected scope.

@Table Annotation:

The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the
database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its
schema, and enforce unique constraints on columns in the table. For now we are using just table name which is
EMPLOYEE.

@Id and @GeneratedValue Annotations:

Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary
key can be a single field or a combination of multiple fields depending on your table structure.
75
By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to
be used but you can override this by applying the @GeneratedValue annotation which takes two parameters
strategy and generator which I'm not going to discuss here, so let us use only default the default key generation
strategy. Letting Hibernate determine which generator type to use makes your code portable between different
databases.

@Column Annotation:

The @Column annotation is used to specify the details of the column to which a field or property will be mapped.
You can use column annotation with the following most commonly used attributes:
name attribute permits the name of the column to be explicitly specified.
length attribute permits the size of the column used to map a value particularly for a String value.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
unique attribute permits the column to be marked as containing only unique values.

Create Application Class:

Finally, we will create our application class with the main() method to run the application. We will use this
application to save few Employee's records and then we will apply CRUD operations on those records.

Database Configuration:

Now let us create hibernate.cfg.xml configuration file to define database related parameters. This time we are not
going

Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and
CLASSPATH appropriately before proceeding for the compilation and execution.
Delete Employee.hbm.xml mapping file from the path.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on
tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by
Hibernate into conventional SQL queries which in turns perform action on database.

76
Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use
HQL whenever possible to avoid database portability hassles, and to take advantage of Hibernate's SQL generation
and caching strategies.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names
are case sensitive in HQL.

FROM Clause

You will use FROM clause if you want to load a complete persistent objects into memory. Following is the simple
syntax of using FROM clause:
String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

AS Clause

The AS clause can be used to assign aliases to the classes in your HQL queries, specially when you have long
queries. For instance, our previous simple example would be the following:
String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();
The AS keyword is optional and you can also specify the alias directly after the class name, as follows:
String hql = "FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

SELECT Clause

The SELECT clause provides more control over the result set than the from clause. If you want to obtain few
properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using
SELECT clause to get just first_name field of the Employee object:
String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
It is notable here that Employee.firstName is a property of Employee object rather than a field of the EMPLOYEE
table.

WHERE Clause

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause. Following is
the simple syntax of using WHERE clause:
String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();

77
ORDER BY Clause

To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the results by any
property on the objects in the result set either ascending (ASC) or descending (DESC). Following is the simple
syntax of using ORDER BY clause:
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();
If you wanted to sort by more than one property, you would just add the additional properties to the end of the order
by clause, separated by commas as follows:
String hql = "FROM Employee E WHERE E.id > 10 " +
"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

GROUP BY Clause

This clause lets Hibernate pull information from the database and group it based on a value of an attribute and,
typically, use the result to include an aggregate value. Following is the simple syntax of using GROUP BY clause:
String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +
"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();

Using Named Paramters

Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from
the user easy and you do not have to defend against SQL injection attacks. Following is the simple syntax of using
named parameters:
String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

UPDATE Clause

Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they did in
Hibernate 2. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or
DELETE statements.
The UPDATE clause can be used to update one or more properties of an one or more objects. Following is the
simple syntax of using UPDATE clause:
String hql = "UPDATE Employee set salary = :salary " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

78
DELETE Clause

The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE
clause:
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

INSERT Clause

HQL supports INSERT INTO clause only where records can be inserted from one object to another object.
Following is the simple syntax of using INSERT INTO clause:
String hql = "INSERT INTO Employee(firstName, lastName, salary)" +
"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods

HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and
following is the list of the available functions:
S.N. Functions Description
1 avg(property name) The average of a property's value
2 count(property name or *) The number of times a property occurs in the results
3 max(property name) The maximum value of the property values
4 min(property name) The minimum value of the property values
5 sum(property name) The sum total of the property values
The distinct keyword only counts the unique values in the row set. The following query will return only unique
count:
String hql = "SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Pagination using Query

There are two methods of the Query interface for pagination.


S.N. Method & Description
1 Query setFirstResult(int startPosition)

79
This method takes an integer that represents the first row in your result set, starting with row 0.

Query setMaxResults(int maxResult)


2
This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application.
Following is the example which you can extend to fetch 10 rows at a time:
String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the
methods is Criteria API which allows you to build up a criteria query object programmatically where you can apply
filtration rules and logical conditions.
The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object
that returns instances of the persistence object's class when your application executes a criteria query.
Following is the simplest example of a criteria query is one which will simply return every object that corresponds
to the Employee class.
Criteria cr = session.createCriteria(Employee.class);
List results = cr.list();

Restrictions with Criteria:

You can use add() method available for Criteria object to add restriction for a criteria query. Following is the
example to add a restriction to return the records with salary is equal to 2000:
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
Following are the few more examples covering different scenarios and can be used as per requirement:
Criteria cr = session.createCriteria(Employee.class);

// To get records having salary more than 2000


cr.add(Restrictions.gt("salary", 2000));

// To get records having salary less than 2000


cr.add(Restrictions.lt("salary", 2000));

// To get records having fistName starting with zara


cr.add(Restrictions.like("firstName", "zara%"));

// Case sensitive form of the above restriction.


cr.add(Restrictions.ilike("firstName", "zara%"));

// To get records having salary in between 1000 and 2000


cr.add(Restrictions.between("salary", 1000, 2000));

// To check if the given property is null


cr.add(Restrictions.isNull("salary"));
80
// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));

// To check if the given property is empty


cr.add(Restrictions.isEmpty("salary"));

// To check if the given property is not empty


cr.add(Restrictions.isNotEmpty("salary"));
You can create AND or OR conditions using LogicalExpression restrictions as follows:
Criteria cr = session.createCriteria(Employee.class);

Criterion salary = Restrictions.gt("salary", 2000);


Criterion name = Restrictions.ilike("firstNname","zara%");

// To get records matching with OR condistions


LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );

// To get records matching with AND condistions


LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );

List results = cr.list();


Though all the above conditions can be used directly with HQL as explained in previous tutorial.

Pagination using Criteria:

There are two methods of the Criteria interface for pagination.


S.N. Method & Description
public Criteria setFirstResult(int firstResult)
1
This method takes an integer that represents the first row in your result set, starting with row 0.

public Criteria setMaxResults(int maxResults)


2
This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application.
Following is the example which you can extend to fetch 10 rows at a time:
Criteria cr = session.createCriteria(Employee.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();

Sorting the Results:

The Criteria API provides the org.hibernate.criterion.Order class to sort your result set in either ascending or
descending order, according to one of your object's properties. This example demonstrates how you would use the
Order class to sort the result set:
Criteria cr = session.createCriteria(Employee.class);

81
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));

// To sort records in descening order


crit.addOrder(Order.desc("salary"));

// To sort records in ascending order


crit.addOrder(Order.asc("salary"));

List results = cr.list();

Projections & Aggregations:

The Criteria API provides the org.hibernate.criterion.Projections class which can be used to get average,
maximum or minimum of the property values. The Projections class is similar to the Restrictions class in that it
provides several static factory methods for obtaining Projection instances.
Following are the few examples covering different scenarios and can be used as per requirement:
Criteria cr = session.createCriteria(Employee.class);

// To get total row count.


cr.setProjection(Projections.rowCount());

// To get average of a property.


cr.setProjection(Projections.avg("salary"));

// To get distinct count of a property.


cr.setProjection(Projections.countDistinct("firstName"));

// To get maximum of a property.


cr.setProjection(Projections.max("salary"));

// To get minimum of a property.


cr.setProjection(Projections.min("salary"));

// To get sum of a property.


cr.setProjection(Projections.sum("salary"));

Criteria Queries Example:

Consider the following POJO class:


public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
82
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Let us create the following EMPLOYEE table to store Employee objects:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following will be mapping file.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main() method to run the application where we will use
Criteria queries:
import java.util.List;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

83
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {


private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();

/* Add few employee records in database */


Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 5000);
Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);

/* List down all the employees */


ME.listEmployees();

/* Print Total employee's count */


ME.countEmployee();

/* Print Toatl salary */


ME.totalSalary();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}

/* Method to READ all the employees having salary more than 2000 */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// Add restriction.
cr.add(Restrictions.gt("salary", 2000));
List employees = cr.list();

84
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to print total number of records */
public void countEmployee(){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);

// To get total row count.


cr.setProjection(Projections.rowCount());
List rowCount = cr.list();

System.out.println("Total Coint: " + rowCount.get(0) );


tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to print sum of salaries */
public void totalSalary(){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);

// To get total salary.


cr.setProjection(Projections.sum("salary"));
List totalSalary = cr.list();

System.out.println("Total Salary: " + totalSalary.get(0) );


tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}

85
Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and
CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

First Name: Daisy Last Name: Das Salary: 5000


First Name: John Last Name: Paul Salary: 5000
First Name: Mohd Last Name: Yasee Salary: 3000
Total Coint: 4
Total Salary: 15000

You can use native SQL to express database queries if you want to utilize database-specific features such as query
hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored
procedures, for all create, update, delete, and load operations.
Your application will create a native SQL query from the session with the createSQLQuery() method on the
Session interface.:
public SQLQuery createSQLQuery(String sqlString) throws HibernateException
After you pass a string containing the SQL query to the createSQLQuery() method, you can associate the SQL result
with either an existing Hibernate entity, a join, or a scalar result using addEntity(), addJoin(), and addScalar()
methods respectively.

Scalar queries:

The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the syntax for
using native SQL for scalar values:
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();

Entity queries:

The above queries were all about returning scalar values, basically returning the "raw" values from the resultset. The
following is the syntax to get entity objects as a whole from a native sql query via addEntity().
String sql = "SELECT * FROM EMPLOYEE";
86
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
List results = query.list();

Named SQL queries:

The following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query.
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
query.setParameter("employee_id", 10);
List results = query.list();

Native SQL Example:

Consider the following POJO class:


public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Let us create the following EMPLOYEE table to store Employee objects:
create table EMPLOYEE (
id INT NOT NULL auto_increment,

87
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following will be mapping file.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main() method to run the application where we will use Native
SQL queries:
import java.util.*;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {


private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();

/* Add few employee records in database */


Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 5000);
Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);

/* List down employees and their salary using Scalar Query */


ME.listEmployeesScalar();

/* List down complete employees information using Entity Query */

88
ME.listEmployeesEntity();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}

/* Method to READ all the employees using Scalar Query */


public void listEmployeesScalar( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List data = query.list();

for(Object object : data)


{
Map row = (Map)object;
System.out.print("First Name: " + row.get("first_name"));
System.out.println(", Salary: " + row.get("salary"));
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

/* Method to READ all the employees using Entity Query */


public void listEmployeesEntity( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
String sql = "SELECT * FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
List employees = query.list();

for (Iterator iterator =


employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();

89
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}

Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and
CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

First Name: Zara, Salary: 2000


First Name: Daisy, Salary: 5000
First Name: John, Salary: 5000
First Name: Mohd, Salary: 3000
First Name: Zara Last Name: Ali Salary: 2000
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 5000
First Name: Mohd Last Name: Yasee Salary: 3000

Caching is all about application performance optimization and it sits between your application and the database to
avoid the number of database hits as many as possible to give a better performance for performance critical
applications.
Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below:

90
First-level cache:

The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The
Session object keeps an object under its own power before committing it to the database.
If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the
number of update SQL statements issued. If you close the session, all the objects being cached are lost and either
persisted or updated in the database.

Second-level cache:

Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to
locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-
collection basis and mainly responsible for caching objects across sessions.
Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided,
which must be implemented to provide Hibernate with a handle to the cache implementation.

Query-level cache:

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache.
This is an optional feature and requires two additional physical cache regions that hold the cached query results and
the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same
parameters.

91
The Second Level Cache:

Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. Let's go straight to the
optional second-level cache. Not all classes benefit from caching, so it's important to be able to disable the second-
level cache
The Hibernate second-level cache is set up in two steps. First, you have to decide which concurrency strategy to use.
After that, you configure cache expiration and physical cache attributes using the cache provider.

Concurrency strategies:

A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them
from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class
and collection, which cache concurrency strategy to use.
Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent
transactions,in the rare case of an update.
Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in
concurrent transactions,in the rare case of an update.
Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database.
Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.
Read-only: A concurrency strategy suitable for data which never changes. Use it for reference data only.
If we are going to use second-level caching for our Employee class, let us add the mapping element required to tell
Hibernate to cache Employee instances using read-write strategy.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<cache usage="read-write"/>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
The usage="read-write" attribute tells Hibernate to use a read-write concurrency strategy for the defined cache.

92
Cache provider:

Your next step after considering the concurrency strategies you will use for your cache candidate classes is to pick a
cache provider. Hibernate forces you to choose a single cache provider for the whole application.
S.N. Cache Name Description
It can cache in memory or on disk and clustered caching and it supports the optional
1 EHCache
Hibernate query result cache.
Supports caching to memory and disk in a single JVM, with a rich set of expiration
2 OSCache
policies and query cache support.
A cluster cache based on JGroups. It uses clustered invalidation but doesn't support
3 warmCache
the Hibernate query cache
A fully transactional replicated clustered cache also based on the JGroups multicast
library. It supports replication or invalidation, synchronous or asynchronous
4 JBoss Cache
communication, and optimistic and pessimistic locking. The Hibernate query cache
is supported
Every cache provider is not compatible with every concurrency strategy. The following compatibility matrix will
help you choose an appropriate combination.
Strategy/Provider Read-only Nonstrictread-write Read-write Transactional
EHCache X X X
OSCache X X X
SwarmCache X X
JBoss Cache X X
You will specify a cache provider in hibernate.cfg.xml configuration file. We choose EHCache as our second-level
cache provider:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>

<!-- Assume students is the database name -->


<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>

93
<property name="hibernate.connection.password">
root123
</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>

<!-- List of XML mapping files -->


<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
Now, you need to specify the properties of the cache regions. EHCache has its own configuration file, ehcache.xml,
which should be in the CLASSPATH of the application. A cache configuration in ehcache.xml for the Employee
class may look like this:
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
That's it, now we have second-level caching enabled for the Employee class and Hibernate now hits the second-
level cache whenever you navigate to a Employee or when you load a Employee by identifier.
You should analyze your all the classes and choose appropriate caching strategy for each of the classes. Sometime,
second-level caching may downgrade the performance of the application. So it is recommended to benchmark your
application first without enabling caching and later on enable your well suited caching and check the performance.
If caching is not improving system performance then there is no point in enabling any type of caching.

The Query-level Cache:

To use the query cache, you must first activate it using the hibernate.cache.use_query_cache="true" property in
the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to
hold the query and identifier sets.
Next, to use the query cache, you use the setCacheable(Boolean) method of the Query class. For example:
Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
List users = query.list();
SessionFactory.closeSession();
Hibernate also supports very fine-grained cache support through the concept of a cache region. A cache region is
part of the cache that's given a name.

94
Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
query.setCacheRegion("employee");
List users = query.list();
SessionFactory.closeSession();
This code uses the method to tell Hibernate to store and look for the query in the employee area of the cache.
Consider a situation when you need to upload a large number of records into your database using Hibernate.
Following is the code snippet to achieve this using Hibernate:
Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Employee employee = new Employee(.....);
session.save(employee);
}
tx.commit();
session.close();
Because by default, Hibernate will cache all the persisted objects in the session-level cache and ultimately your
application would fall over with an OutOfMemoryException somewhere around the 50,000th row. You can resolve
this problem if you are using batch processing with Hibernate.
To use the batch processing feature, first set hibernate.jdbc.batch_size as batch size to a number either at 20 or 50
depending on object size. This will tell the hibernate container that every X rows to be inserted as batch. To
implement this in your code we would need to do little modification as follows:
Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Employee employee = new Employee(.....);
session.save(employee);
if( i % 50 == 0 ) { // Same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
Above code will work fine for the INSERT operation, but if you are willing to make UPDATE operation then you
can achieve using the following code:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

ScrollableResults employeeCursor = session.createQuery("FROM EMPLOYEE")


.scroll();
int count = 0;

while ( employeeCursor.next() ) {
Employee employee = (Employee) employeeCursor.get(0);
employee.updateEmployee();
seession.update(employee);
if ( ++count % 50 == 0 ) {
session.flush();
session.clear();
}
}

95
tx.commit();
session.close();

Batch Processing Example:

Let us modify configuration file as to add hibernate.jdbc.batch_size property:


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>

<!-- Assume students is the database name -->


<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<property name="hibernate.jdbc.batch_size">
50
</property>

<!-- List of XML mapping files -->


<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
Consider the following POJO Employee class:
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {

96
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Let us create the following EMPLOYEE table to store Employee objects:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following will be mapping file to map Employee objects with EMPLOYEE table.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main() method to run the application where we will use flush()
and clear() methods available with Session object so that Hibernate keep writing these records into the database
instead of caching them in the memory.
import java.util.*;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {

97
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();

/* Add employee records in batches */


ME.addEmployees( );
}
/* Method to create employee records in batches */
public void addEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
String fname = "First Name " + i;
String lname = "Last Name " + i;
Integer salary = i;
Employee employee = new Employee(fname, lname, salary);
session.save(employee);
if( i % 50 == 0 ) {
session.flush();
session.clear();
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return ;
}
}

Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and
CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained above.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program which will create 100000 records in EMPLOYEE
table.

98
As you have learnt that in Hibernate, an object will be created and persisted. Once the object has been changed, it
must be saved back to the database. This process continues until the next time the object is needed, and it will be
loaded from the persistent store.
Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which
can be called at different stages to perform some required tasks. These methods are callbacks from the session to the
application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved,
updated, deleted or loaded. Following is the list of all the methods available within the Interceptor interface:
S.N. Method and Description
findDirty()
1
This method is be called when the flush() method is called on a Session object.

instantiate()
2
This method is called when a persisted class is instantiated.

isUnsaved()
3
This method is called when an object is passed to the saveOrUpdate() method/

onDelete()
4
This method is called before an object is deleted.

onFlushDirty()
5 This method is called when Hibernate detects that an object is dirty (ie. have been changed) during a flush i.e.
update operation.

onLoad()
6
This method is called before an object is initialized.

onSave()
7
This method is called before an object is saved.

postFlush()
8
This method is called after a flush has occurred and an object has been updated in memory.

preFlush()
9
This method is called before a flush.

Hibernate Interceptor gives us total control over how an object will look to both the application and the database.

99
How to use Interceptors?

To build an interceptor you can either implement Interceptor class directly or extend EmptyInterceptor class.
Following will be the simple steps to use Hibernate Interceptor functionality.

Create Interceptors:

We will extend EmptyInterceptor in our example where Interceptor's method will be called automatically when
Employee object is created and updated. You can implement more methods as per your requirements.
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

public class MyInterceptor extends EmptyInterceptor {


private int updates;
private int creates;
private int loads;

public void onDelete(Object entity,


Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
// do nothing
}

// This method is called when Employee object gets updated.


public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) {
if ( entity instanceof Employee ) {
System.out.println("Update Operation");
return true;
}
return false;
}
public boolean onLoad(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
// do nothing
return true;
}
// This method is called when Employee object gets created.
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {

100
if ( entity instanceof Employee ) {
System.out.println("Create Operation");
return true;
}
return false;
}
//called before commit into database
public void preFlush(Iterator iterator) {
System.out.println("preFlush");
}
//called after committed into database
public void postFlush(Iterator iterator) {
System.out.println("postFlush");
}
}

Create POJO Classes:

Now let us modify a little bit our first example where we used EMPLOYEE table and Employee class to play with:
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}

101
Create Database Tables:

Second step would be creating tables in your database. There would be one table corresponding to each object you
are willing to provide persistence. Consider above objects need to be stored and retrieved into the following
RDBMS table:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

Create Mapping Configuration File:

This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database
tables.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>

Create Application Class:

Finally, we will create our application class with the main() method to run the application. Here it should be noted
that while creating session object we used our Interceptor class as an argument.
import java.util.List;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {


private static SessionFactory factory;
public static void main(String[] args) {
try{

102
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}

ManageEmployee ME = new ManageEmployee();

/* Add few employee records in database */


Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);

/* List down all the employees */


ME.listEmployees();

/* Update employee's records */


ME.updateEmployee(empID1, 5000);

/* Delete an employee from the database */


ME.deleteEmployee(empID2);

/* List down new list of the employees */


ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();

103
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}

Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and
CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create MyInterceptor.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.

104
You would get following result, and records would be created in EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

Create Operation
preFlush
postFlush
Create Operation
preFlush
postFlush
Create Operation
preFlush
postFlush
First Name: Zara Last Name: Ali Salary: 1000
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 10000
preFlush
postFlush
preFlush
Update Operation
postFlush
preFlush
postFlush
First Name: Zara Last Name: Ali Salary: 5000
First Name: John Last Name: Paul Salary: 10000
preFlush
postFlush
If you check your EMPLOYEE table, it should have following records:
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent
framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and
Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer
from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects
based on the appropriate O/R mechanisms and patterns.

Hibernate Advantages:

Hibernate takes care of mapping Java classes to database tables using XML files and without writing any
line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.

105
If there is change in Database or in any table then the only need to change XML file properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimize database access with smart fetching strategies.
Provides Simple querying of data.

Supported Databases:

Hibernate supports almost all the major RDBMS. Following is list of few of the database engines supported by
Hibernate.
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server

Hibernate Architecture:

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate
makes use of the database and configuration data to provide persistence services (and persistent objects) to the
application.
Following is a very high level view of the Hibernate Application Architecture.

106
Following is a detailed view of the Hibernate Application Architecture with few important core classes.

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory
Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases,

107
allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to
be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application
Architecture.

Configuration Object:

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created
only once during application initialization. It represents a configuration or properties file required by the Hibernate.
The Configuration object provides two keys components:
Database Connection: This is handled through one or more configuration files supported by Hibernate.
These files are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup
This component creates the connection between the Java classes and database tables..

SessionFactory Object:

Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application
using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a
thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use.
You would need one SessionFactory object per database using a separate configuration file. So if you are using
multiple databases then you would have to create multiple SessionFactory objects.

Session Object:

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be
instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a
Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should
be created and destroyed them as needed.

Transaction Object:

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction
functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from
JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing
transactions in their own application code.

108
Query Object:

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create
objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and
finally to execute the query.

Criteria Object:

Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

ANS 2)
Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of
the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and
calls the method for you. Very nice in simple cases with no object hierarchy. Typecasting and instanceof
work perfectly on the proxy in this case since it is a direct subclass.
ANS 3)
By specifying the @JoinColumn on both models you don't have a two way relationship. You have two one way
relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE
column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn off of the
@OneToMany side entirely, and instead add mappedBy to the @OneToMany.
@OneToMany(fetch=FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
return airlineFlights;
}
That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the
configuration."

Hewlett Packard (HP)


ANS 1)
J2EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise"
Applications which can generally be classed as large-scale, distributed, transactional and highly-available
applications designed to support mission-critical business requirements.
In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has
kept changing over the last five years. It really is about the class of problems that are being solved more than
anything else. Transactions and distribution are key.

J2EE is a collection of specifications for developing and deploying enterprise applications.


In general, enterprise applications refer to software hosted on servers that provide the applications that support the
enterprise.

109
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up J2EE are:
1. JDBC
2. JNDI
3. EJBs
4. RMI
5. JSP
6. Java servlets
7. XML
8. JMS
9. Java IDL
10. JTS
11. JTA
12. JavaMail
13. JAF
The J2EE product provider is typically an application-server, web-server, or database-system vendor who provides
classes that implement the interfaces defined in the specifications. These vendors compete on implementations of
the J2EE specifications.
When a company requires J2EE experience what are they really asking for is experience using the technologies that
make up J2EE. Frequently, a company will only be using a subset of the J2EE technologies.

What Is J2EE?

Before defining what J2EE is, let us understand that J2EE is not simply a language, package, utility, or service.

Java 2 Platform, Enterprise Edition (J2EE)

In simpler terms, J2EE is essentially a standard middleware architecture, proposed by Sun Microsystems for
developing and deploying multitier, distributed, e-enabled, enterprise scale business applications. Applications
written for J2EE standards enjoy certain inherent benefits such as portability, security, scalability, load-balancing,
and reusability.
Middleware are essentially server-side software solutions that provide the much-required foundation for linking
several disparate systems and resources that are scattered across the network. Prior to the introduction of J2EE,
middleware solutions were highly proprietary and restrictive to specific vendors and productswith limited features

110
and compatibility, and no interoperability or portability across different solutions. There was no common/acceptable
industry standard in place to adhere to, and many of the features were left to the choice of vendors.
J2EE represents the maturity and seasoning that middleware technology has undergone over the years by learning
from the mistakes of the past and addressing all the essential requirements of the industry. It also provides enough
room for future developments. While developing this standard, Sun collaborated with other major vendors of
middleware, operating systems, and database management systemsincluding IBM and Oracle.
At its core, J2EE is a set of standards and guidelines that defines how distributed n-tier applications can be built
using the Java language. Developers build their applications on the top of these standards while middleware
infrastructure vendors ensure compatibility to these guidelines set forth by J2EE . Thus, J2EE applications can be
ported and deployed across several application servers, with minimal or no code-level changes. This concept is
represented in Figure 1.
Figure 1 J2EE compatibility between application servers and developer codes.

Perspectives on J2EE

J2EE offers several perspectives, as discussed in the following sections.

J2EE: A Syntax for Multitier, Distributed Middleware

J2EE clearly demarcates various tiers that are involved in application development, and defines components that can
be hosted in those tiers. These tiers include the clients tier, presentation logic tier, business logic tier, and enterprise
information systems tier. All J2EE applications are built on the top of this basic framework, and they naturally
evolve as multitier systems, even without conscious effort. Each tier may be physically distributed across several
servers.
With J2EE, distributed application development is no longer a complex task. J2EE components make no
assumptions about the server environment in which they existand all resources are accessed through distributed
directories. This means that there is no deliberate effort required on the part of application developers to distribute
their components and resources.

J2EE: A Platform for Enterprise Scale Applications

J2EE, implemented as specific Web application servers such as BEA Web logic or IBM Web sphere, is a platform
for building enterprise scale distributed applications. Applications can be built on top of the J2EE application-
programming model, and can be deployed in one or more J2EE-compatible Web application servers.
A specific application server platform that is best suited for a given enterprise IT infrastructure can be chosen from a
wide variety of J2EE compatible productseach enjoying its own distinctive advantage over the others. Irrespective
of their unique features, all J2EE application servers provide a common groundwork for developing and deploying
enterprise scale applications.

J2EE: A Model for e-Enabled Application Development

J2EE applications can be very easily exposed to Web, Palm, and handheld devices; mobile phones; and a variety of
other devices. In other words, application components can be "e-enabled" without much effort. The J2EE

111
application-programming model ensures that the business logic and back-end systems remain untouched as their
facilities are exposed to different types of client access.
Yet another great feature of J2EE platform is automatic load-balancing, scaling, fault-tolerance, and fail-over.
Components deployed in J2EE environment automatically inherit these facilities, and there is no deliberate coding
effort required.
These features are significantly important for constructing Web portals that are available to clients 24/7/365.

J2EE: The Widely Adapted Standard in Web Application Servers

J2EE is perhaps the first industry standard to relish widespread industry recognition and adoption in the middleware
world. Almost all top-notch Web application servers (BEA's Weblogic, IBM's Web sphere, HP's Application servers,
Sun-Netscape's iPlanet, and Macromedia's Jrun, to name a few) are all J2EE-certified application servers. No other
standard advocated before has been supported by such a long list of middleware infrastructure providers.
Moreover, with J2EE, companies are no longer nailed down to a specific vendor or application server provider. As
long as the application components stick to J2EE specifications, they can be deployed across different application
servers along the enterprise network. To ensure compatibility and coherence across different J2EE application
servers, Sun has released a compatibility test suite.

Vision of J2EE

The primary vision that propels J2EE can be summarized as follows: "Developers should be writing codes to
express their business and presentation logic, whereas the underlying middleware infrastructure takes care of
system-level issues such as memory management, multithreading, resource allocation, availability, and garbage
collectionautomatically."

ANS 2)

Inner classes are best for the purpose of logically grouping classes that are used in one-place. For example,
if you want to create class which is used by ONLY enclosing class, then it doesn't make sense to create a
separate file for that. Instead you can add it as "inner class"
As per javadoc:
9 down
vote Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
It can lead to more readable and maintainable code.

Why does Java need inner classes?

From the very beginnings of Java, its designers have recognized the need for a construct like a "method pointer,"
which (in all its various forms) amounts to a handle on an individual block of code which can be used without
reference to the object or class containing the code. In languages (like C or Lisp) where functions are free
112
standing, independent of objects, function pointers serve this role. For example, these pointers often serve to
connect a "callback" or "event" in one module to a piece of code in another. In a more object oriented style,
Smalltalk has "blocks," which are chunks of code that behave like little objects. As with C or Lisp function
pointers, Smalltalk blocks can be used to organize complex control flow patterns, such as iteration over
collections.
In Java, the same complex control flow patterns, including event management and iteration, are expressed by classes
and interfaces. Java uses interfaces with one method where other languages might use separate "function types." The
Java programmer creates the equivalent of a callback or a Smalltalk block by wrapping the desired code in an
adapter class which implements the required interface. With inner classes, the notation for adapters is about as
simple as that of Smalltalk blocks, or of inner functions in other languages. However, since classes are richer than
functions (because they have multiple entry points), Java adapter objects are more powerful and more structured
than function pointers.
So, whereas C, Lisp, and Smalltalk programmers use variations of "method pointers" to encapsulate chunks of code,
Java programmers use objects. Where other languages have specialized function types and notations to encapsulate
behavior as functions, Java has only class and interface types. In Java, "the class is the quantum of behavior." One
benefit of this approach is simplicity and stability for the Java Virtual Machine, which needs no special support for
inner classes or function pointers.
Without inner classes, Java programmers can create callbacks and iterators by means of adapter classes defined at
top-level, but the notation is so clumsy as to be impractical. By means of inner classes, Java programmers can write
concise adapter classes which are coded precisely where they are needed, and operate directly on the internal
variables and methods of a class or a block.
Thus, inner classes make adapter classes practical as a coding style. In the future, inner classes will also be more
efficient than equivalent top-level adapter classes, because of increased opportunities for optimization, especially of
(externally) inaccessible classes.

ANS 3)

Java 6.0 New Collection APIs an Overview

The following are the new collection APIs introduced in Java 6.0. I listes them as Interfaces and classes.

New Interfaces

Deque
BlockingDeque
NavigableSet
NavigableMap

New Classes

ArrayDeque

113
LinkedBlockingDeque
ConcurrentSkipListSet
ConcurrentSkipListMap
AbstractMap.SimpleEntry
AbstractMap.SimpleImmutableEntry

Updated Classes in Java 6.0

LinkedList
TreeSet
TreeMap
Collections
ANS 6)
I am trying to configure spring with JMS and Hibernate and I want a two phase commit. I am using
ActiveMQ and as database IBM DB2 with XA DataSource. Spring is now complaining about class cast
exception between IBM XA DataSource and javax.sql.DataSource. I am using also Spring
JtaTransactionManager as a proxy to Jencks-Geronimo Transaction manager.

Is it possible to connect these things together using spring and have wrapped a method within such kind of
transaction? Do you have an example somewhere around?
Yes, it is possible of course. With your setup (I have already worked with exactly the same) you need a
ManagedConnectionFactory similar to what's shown on Jencks website. Search also these forums, there are
bunch of posts on this topic from my side like this one.
ANS 8)
Different books and different organizations provide different definitions to Web Services. Some of them are listed
here.
A web service is any piece of software that makes itself available over the internet and uses a standardized
XML messaging system. XML is used to encode all communications to a web service. For example, a client
invokes a web service by sending an XML message, then waits for a corresponding XML response. As all
communication is in XML, web services are not tied to any one operating system or programming
language--Java can talk with Perl; Windows applications can talk with Unix applications.
Web services are self-contained, modular, distributed, dynamic applications that can be described, published,
located, or invoked over the network to create products, processes, and supply chains. These applications can
be local, distributed, or web-based. Web services are built on top of open standards such as TCP/IP, HTTP,
Java, HTML, and XML.
Web services are XML-based information exchange systems that use the Internet for direct application-to-
application interaction. These systems can include programs, objects, messages, or documents.

114
A web service is a collection of open protocols and standards used for exchanging data between applications
or systems. Software applications written in various programming languages and running on various
platforms can use web services to exchange data over computer networks like the Internet in a manner
similar to inter-process communication on a single computer. This interoperability (e.g., between Java and
Python, or Windows and Linux applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that:
Is available over the Internet or private (intranet) networks
Uses a standardized XML messaging system
Is not tied to any one operating system or programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism

Components of Web Services

The basic web services platform is XML + HTTP. All the standard web services work using the following
components
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
All these components have been discussed in the Web Services Architecture chapter.

How Does a Web Service Work?

A web service enables communication among various applications by using open standards such as HTML, XML,
WSDL, and SOAP. A web service takes the help of:
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.
You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that runs on
Windows.
You can also use C# to build new web services on Windows that can be invoked from your web application that is
based on JavaServer Pages (JSP) and runs on Linux.

Example

Consider a simple account-management and order processing system. The accounting personnel use a client
application built with Visual Basic or JSP to create new accounts and enter new customer orders.
115
The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a
database to store information.
The steps to perform this operation are as follows:
The client program bundles the account registration information into a SOAP message.
This SOAP message is sent to the web service as the body of an HTTP POST request.
The web service unpacks the SOAP request and converts it into a command that the application can
understand.
The application processes the information as required and responds with a new unique account number for
that customer.
Next, the web service packages the response into another SOAP message, which it sends back to the client
program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the account registration process.

AON HEWITT
ANS 1)
An object of ServletConfig is created by the web container for each servlet. This object can be used to get
configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is
easier to manage the web application if any specific content is modified from time to time.

Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the
web.xml file.

Methods of ServletConfig interface

1. public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter
names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.

116
How to get the object of ServletConfig

1. getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax of getServletConfig() method

1. public ServletConfig getServletConfig();

ServletContext Interface

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.
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-
param> element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We
provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet.
Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.

117
Commonly used methods of ServletContext interface

There is given some commonly used 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.
6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.

How to get the object of ServletContext interface

1. getServletContext() method of ServletConfig interface returns the object of ServletContext.


2. getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax of getServletContext() method

1. public ServletContext getServletContext()


ANS 2)

Types of Synchronization:
1)Method level Synchronization: A method can be Synchronized by adding a perfix word "Synchronize". Here we
have Parametrised Synchronization options also.
example: public Synchronize void foo(){}
2)Block level Synchronization: A block can be Synchronized by adding a perfix word "Synchronize". Here we have
Parametrised Synchronization options also.
Synchronize { }
ANS 4)
The forward method of RequestDispatcher will forward the ServletRequest and ServletResponse that it is
passed to the path that was specified in getRequestDispatcher(String path). The response will not be sent
back to the client and so the client will not know about this change of resource on the server. This method is
useful for communicating between server resources, (servlet to servlet). Because the request and response
are forwarded to another resource all request parameters are maintained and available for use. Since the
client does not know about this forward on the server, no history of it will be stored on the client, so using

118
the back and forward buttons will not work. This method is faster than using sendRedirect as no network
round trip to the server and back is required.

An example using forward:


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
rd.forward(request, response);
}

The sendRedirect(String path) method of HttpServletResponse will tell the client that it should send a
request to the specified path. So the client will build a new request and submit it to the server, because a new
request is being submitted all previous parameters stored in the request will be unavailable. The client's
history will be updated so the forward and back buttons will work. This method is useful for redirecting to
pages on other servers and domains.

An example using sendRedirect:


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("pathToResource");
}

ANS 6)

How to define Java mehtods in JSP pages?

Each JSP compiles to a separate class, so there are classes involved. If you are reusing the code chunks in the same
JSP, then you can declare a method to appear in the JSP class. The JSP Declarations are used to declare variables
and methods in the scripting language used in a JSP page. A declaration should be a complete declarative statement,
or sequence thereof according to the syntax of the scripting language specified. The JSP declaration syntax is:
<%! declaration(s) %>
Declarations do not produce any output into the current out stream.

Declarations are initialized when the JSP page is initialized and are made available to othe declarations,
scriptlets, and expressions.
Declarations declare methods global to the page.
<%
public String doSomething(String param) {
//
}

String test = doSomething("test");

%>
Is that legal? I am getting some weird compile errors (like a ; is expected) that don't seem to fit.

You need to use declaration syntax (<%! ... %>):


<%!
public String doSomething(String param) {
//
119
}
%>
<%
String test = doSomething("test");
%>

<% ... %> is used to embed some java code within the main service() method of the JSP. It is executed during
the rendering of the page.
<%! ... %> is used to define code outside of the flow of the page, and therefore outside the main service()
method. Typically, this was used to define utility methods that would be called from within a <% ... %> block.

Both approaches are now obsolete, however. JSP EL, JSTL and tag classes are the preferred way of doing the same
thing.

ANS 9)
With connection pools servlets acquire connetions to databases from a pool and returns the connection back to the
pool for later reuse. Because the connection is opened only at the first request there is no overhead with opening and
closing connection every time. The servlet creates the pool in its 'init' method. This method is executed only when
the servlet is loaded. After a timeout period the connection pool closes expired connections.
Connection pools are an efficient way of handling database connections with servlets.
Not COMPANY RELATED
ANS 1) <%@ page isErrorPage="true" %>
<error-page>
<exception-type>PaymentException</exception-type>
<location>/paymentError.jsp</location>
</error-page>
ANS 2)

What is the difference between absolute, relative and canonical path of file or
directory?

Absolute path is the full directory such as C:\XyzWs\test.txt. The definition of absolute pathname is system
dependent. On UNIX systems, a pathname is absolute if its prefix is "/". On Win32 systems, a pathname is
absolute if its prefix is a drive specifier followed by "\\", or if its prefix is "\\".
For example, We have two directories: XyzWs and XyzWs1 and test.txt file is in XyzWs directory.
C:\XyzWs
C:\XyzWs1
In Java under Windows, you may have the following possible absolute paths that refer to the same file
test.txt.
c:\XyzWs\test.txt
C:\XYZWS\test.txt
c:\XyzWs\TEST.TXT
c:\XyzWs\.\test.txt
c:\XyzWs1\..\XyzWs\test.txt

120
Relative path is relative to the directory you are in, so if you are in the above directory, then if you reference
file test.txt as relative, it assumes the same directory you are in. When you do ../ then it goes back one
directory.
Canonical paths are a bit harder. For starters, all canonical paths are absolute (but not all absolute paths are
canonical). A single file existing on a system can have many different paths that refer to it, but only one
canonical path. Canonical gives a unique absolute path for a given file. The details of how this is achieved
are probably system-dependent.
For the above example, we have one and only one canonical path:
c:\XyzWs\test.txt
The following example shows how there can be many different paths (and absolute paths) to the same file, which all
have the exact same canonical path. Thus canonical path is useful if you want to know if two different paths point to
the same file or not.
import java.io.*;

public class Test {


public static void showPaths(String pathName) throws IOException {
File file = new File(pathName);
System.out.println("path: " + file.getPath());
System.out.println("absolute path: " + file.getAbsolutePath());
System.out.println("canonical path: " + file.getCanonicalPath());
System.out.println();
}

public static void main(String[] s) throws IOException {


File file = new File(new File("test.txt").getAbsolutePath());
String parent = file.getParent();
File parentFile = new File(parent);
String parentName = parentFile.getName();
String grandparent = parentFile.getParent();
file.createNewFile();

showPaths("test.txt");
showPaths("TEST.TXT");
showPaths("." + File.separator + "TEST.TXT");

showPaths(parent
+ File.separator + "."
+ File.separator + "test.txt");

showPaths(grandparent
+ File.separator + parentName
+ File.separator + ".."
+ File.separator + parentName
+ File.separator + "test.txt");
}
}
On window XP and Java 5.0, the results are:
path: test.txt
absolute path: C:\XyzWs\test.txt
canonical path: C:\XyzWs\test.txt

path: TEST.TXT
absolute path: C:\XyzWs\TEST.TXT
canonical path: C:\XyzWs\test.txt

121
path: .\TEST.TXT
absolute path: C:\XyzWs\.\TEST.TXT
canonical path: C:\XyzWs\test.txt

path: C:\XyzWs\.\test.txt
absolute path: C:\XyzWs\.\test.txt
canonical path: C:\XyzWs\test.txt

path: C:\XyzWs\..\XyzWs\test.txt
absolute path: C:\XyzWs\..\XyzWs\test.txt
canonical path: C:\XyzWs\test.txt

More about "Canonical"

Canonical path is validated with the File System while Absolute path is still abstract and may not be able to
represent any physical path. An IOException is thrown if the path name is not possible (Z:/x:/test.txt). For example,
import java.io.*;
public class Test {
public static void main(String[] s) throws IOException {
File file = new File ( "Z:/a,b,b", "a*b*c" );
System.out.print ( "Absolute Path:" );
System.out.println ( file.getAbsolutePath () );
System.out.print ( "Canonical Path:" );
System.out.println ( file.getCanonicalPath () );
}
}
Prints:
Absolute Path:Z:\a,b,b\a*b*c
Canonical Path:java.io.IOException: Invalid argument
at java.io.Win32FileSystem.canonicalize(Native Method)
at java.io.File.getCanonicalPath(File.java:437)
at Test.main(Test.java:9)
Since file systems differ over platforms, FileSystem is an abstract class, and canonicalize() is an abstract method. A
canonical path is an absolute path, but how it is expressed is up to the concrete implementation of
java.io.FileSystem. You'd need to run the code on two separate systems to see the difference between the two
methods, assuming there is one.
NOT COMPANY RELATED
ANS 1)
1. Here is a good explanation about hashing. For example you want to store the string "Rachel" you apply a
hash function to that string to get a memory location. myHashFunction(key: "Rachel" value:
"Rachel") --> 10. The function may return 10 for the input "Rachel" so assuming you have an array of
size 100 you store "Rachel" at index 10. If you want to retrieve that element you just call
GetmyHashFunction("Rachel") and it will return 10. Note that for this example the key is "Rachel" and
the value is "Rachel" but you could use another value for that key for example birth date or an object. Your
hash function may return the same memory location for two different inputs, in this case you will have a
collision you if you are implementing your own hash table you have to take care of this maybe using a
linked list or other techniques.
2. Here are some common hash functions used. A good hash function satisfies that: each key is equally likely to
hash to any of the n memory slots independently of where any other key has hashed to. One of the methods
is called the division method. We map a key k into one of n slots by taking the remainder of k divided by n.
122
h(k) = k mod n. For example if your array size is n = 100 and your key is an integer k = 15 then h(k) =
10.

3. Hashtable is synchronised and Hashmap is not. Hashmap allows null values as key but Hashtable does not.
4. The purpose of a hash table is to have O(c) constant time complexity in adding and getting the elements. In a
linked list of size N if you want to get the last element you have to traverse all the list until you get it so the
complexity is O(N). With a hash table if you want to retrieve an element you just pass the key and the hash
function will return you the desired element. If the hash function is well implemented it will be in constant
time O(c) This means you dont have to traverse all the elements stored in the hash table. You will get the
element "instantly".
5. Of couse a programer/developer computer scientist needs to know about data structures and complexity =)

ANS 2)
A Web server exclusively handles HTTP requests, whereas an application server serves business logic to
application programs through any number of protocols.
Let's examine each in more detail.

The Web server

A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an
HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static
HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as
CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other
server-side technology. Whatever their purpose, such server-side programs generate a response, most often in
HTML, for viewing in a Web browser.
Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the
Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any
functionality beyond simply providing an environment in which the server-side program can execute and pass back
the generated responses. The server-side program usually provides for itself such functions as transaction
processing, database connectivity, and messaging.
While a Web server may not itself support transactions or database connection pooling, it may employ various
strategies for fault tolerance and scalability such as load balancing, caching, and clusteringfeatures oftentimes
erroneously assigned as features reserved only for application servers.

The application server

As for the application server, according to our definition, an application server exposes business logic to client
applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending
HTML for display in a Web browser, an application server provides access to business logic for use by client
application programs. The application program can use this logic just as it would call a method on an object (or a
function in the procedural world).

123
Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even
other application servers. The information traveling back and forth between an application server and its client is not
restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data
and method calls and not static HTML, the client can employ the exposed business logic however it wants.
In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise
JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the
application server manages its own resources. Such gate-keeping duties include security, transaction processing,
resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and
fault-tolerance techniques.

An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the
site will provide a form with which you can choose a product. When you submit your query, the site performs a
lookup and returns the results embedded within an HTML page. The site may implement this functionality in
numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how
these scenarios differ will help you to see the application server's function.

Scenario 1: Web server without an application server

Recent Java How-Tos

Jump into Java microframeworks, Part 4: Play

124

10 hard-core coding tips for faster Python

Open source Java projects: Apache Phoenix


In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request,
then passes it to a server-side program able to handle the request. The server-side program looks up the pricing
information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate
the HTML response, then the Web server sends it back to your Web browser.
To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server

Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However,
you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the
script knowing how to look up the data and formulate a response, the script can simply call the application server's
lookup service. The script can then use the service's result when the script generates its HTML response.
In this scenario, the application server serves the business logic for looking up a product's pricing information. That
functionality doesn't say anything about display or how the client must use the information. Instead, the client and
application server send data back and forth. When a client calls the application server's lookup service, the service
simply looks up the information and returns it to the client.

125
By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more
reusable between applications. A second client, such as a cash register, could also call the same service as a clerk
checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information
is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests
by replying with an HTML page while the application server serves application logic by processing pricing and
availability requests.

MPHASIS
ANS 9)
First we must talk about what actually the difference between Aggregation and Composition is to be on the same
page.
Aggregation is an association where the associated entity may exist independent of the association. For example, a
Person may be associated to an Organisation but he/she may have independent existence in the system.
whereas
Composition refers to a situation when one of the associated entities is strongly related to the other and cannot exist
without the other's existence. In fact the identity of that entity is always associated with the identity of the other
object. For example, wheels in a car.
Now, aggregation can simply be achieved by holding a property of one entity in another as below:
class Person {
Organisation worksFor;
}

class Organisation {
String name;
}

class Main {
public static void main(String args[]) {

//Create Person object independently


Person p = new Person();

//Create the Organisation independently


Organisation o = new Organisation();
o.name = "XYZ Corporation";

/*
At this point both person and organisation
exist without any association
*/
p.worksFor = o;

}
}
For Composition it is necessary that the dependent object is always created with the identity of its associated object.
You can use an inner class for the same.
class Car {
class Wheel {

126
Car associatedWith;
}
}

class Main {
public static void main() {
//Create Car object independently
Car car = new Car();

//Cannot create Wheel instance independently


//need a reference of a Car for the same.
Car.Wheel wheel = car.new Wheel();
}
}
Please note that the same use case may fall under aggregation/composition depending on the application scenario.
For example, the Person-Organisation case may become composition if you are developing an application for people
working in some organisation and the reference to organisation is must for sign up. Similarly, if you are maintaining
inventory for parts of a Car, Car-Wheel relationship can be aggregation.

NOTION VESSEL
ANS 1)
The main difference is that when you use forward the control is transferred to the next servlet/jsp you are
calling, while include retains the control with the current servlet, it just includes the processing done by the
calling servlet/jsp(like doing any out.println or other processing).
Junior developers often get confused between the include and the forward methods of the RequestDispatcher. The
key difference between the two is the fact that the forward method will close the output stream after it has been
invoked, whereas the include method leaves the output stream open.
Why does this matter? Well, if you are doing processing in a server side component, and then forward to a JSP or
Servlet in order to generate markup for a client, once that JSP or Servlet has finished processing, you can no longer
call on any other components to generate markup that can be sent to the client. Once you have performed a forward,
markup generation for the current request and response cycle is finished.
Alternatively, with an include, you the output stream remains open, so you can call on as many different files to
generate client side markup that you need. So you can include two or three JSP files and even a Servlet in the chain
of components that generate client based markup. When you use an include, the output stream is not closed after
invocation.
Of course, it sounds nice to have an open stream, and be able to call includes on multiple resources, but this
typically is not a good practice. Having a server side controller invoking multiple resources for markup can get
messy and be difficult to manage. As a result, it is usually best to forward to a single server-side artifact and have it
generate markup for the client, and simply accept the fact that the generation of client-side markup has completed.
ANS 2)
oad-on-startup tells the servlet container to load the specified resource at server startup. The number that you see
tells the order of startup if there are more than one load-on-startup tag.
<load-on-startup>1</load-on-startup>
<load-on-startup>2</load-on-startup>

127
will cause the resource with load on startup 1 to be loaded first. This is to control the sequence of loading if there is
a dependency. Look at the servlet specification that explains the load sequence.

Taking a look at the default Tomcat's web.xml configuration file...


<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
...
<load-on-startup>1</load-on-startup>
</servlet>

<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
...
<load-on-startup>3</load-on-startup>
</servlet>

HCL
ANS 3)

What is a session?

The interaction between a Web browser and a Web server is stateless. The browser connects to the server, requests a
single piece of information, then disconnects, at which point the server completely forgets about the transaction and
awaits the next request. Sessions are traditionally used to create a state for Web-based communications. Essentially,
they are dictionaries of name-value pairs that persist from one request to the next.
Behind the scenes, most servers store the session data in memory and map it to a respective browser via a special
cookie. When the browser connects to the server for the first time, the server assigns it a unique identification code
and tells the browser to save that code as a cookie. Any future requests from the browser include the cookie, which
the server uses to look up any session data stored in memory.
Alternatives to storing session data include encoding the session ID into all of the URLs on the page being served or
using the client's IP address, but those options are either too complex or unreliable. URL encoding requires that you
visit each link via code, which is cumbersome and, if you are using a template system, impractical. Using the client's
IP isn't reliable because the client might be behind a proxy that allows multiple machines to share a single IP to the
outside network.

What is wrong with sessions?

Nothing is wrong with the concept of sessions, but the way the server handles sessions can produce problems.
Storing session data in memory precludes the effective use of load balancing on a farm of Web servers. If a browser
were directed to a different server each time it connected, it would have multiple sessions in existence on each
server it visited. And, of course, those sessions would not synchronize with each other, thus leading to complete
pandemonium.

128
The most common solution is to use a load-balancing mechanism that makes a browser sticky to a particular server.
The load-balancing mechanism remembers which browsers visited which servers and ensures that they keep
returning to the same place. Figure 1 illustrates the separate copies of each session across the farm of Web servers.

Figure 1. Session management can become futile


Making a client sticky to a single server turns the server into a single point of failure. If the server crashes, the client
loses all its session data. If the server undergoes an excessive load, and thus responds slowly, the user experience
degrades. In addition, it is entirely possible that a majority of abnormally active users will coincidentally be routed
to a single server, overburdening that server more than its brethren.
An Alternative
The obvious solution, to anybody familiar with multitier applications, is to move the sessions out of the Web servers
and into a central point of reference. So, no matter which Web server in the farm a browser connects to, it will
receive the same session in the same state following the last request. This central point of reference could be a
database (JDBC), a remote object (Remote Method Invocation/Enterprise JavaBeans), a naming server (JNDI), or
even a cookie (assuming the browser can handle cookies). Figure 2 shows the session relocated from the Web server
to the database.

Figure 2. Session management centralized


In Part 2, we will use a database for storing session data.

The database

To plug database-stored sessions into the RSEF, we have to implement a version of SessionWrapper that reads
from and writes to a database.

129
As stated above, a session is just a dictionary of name-value pairs, so our database table needs to reflect that. The
table also needs a way to remember which session each data pair belongs to. Here's what the table looks like:
SESSION_MASTER
--------------
SESSION_ID CHAR(50) KEY
NAME CHAR(50) KEY
VALUE CHAR(1024)
DATE DATETIME
(We assume that you have a basic knowledge of database theory, as the subject expands beyond the scope of this
article. In addition, for purposes of brevity and simplicity, we will ignore the issues of char versus varchar versus
clob or blob fields in relation to indexing, keys, etc.)

The DATE column time-stamps the session entries, thus accommodating expiration or garbage-collection services.
You'll see how the following code examples handle this column, but it will not be part of the overall discussion.
Now that we have laid the foundation for storing session data, we need to code the logic for utilizing the database.
This logic will be neatly packed into our first wrapper.
ANS 13)
package HCL.Answer.Thirteen;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
*
* @author HP
*/
public class HCLAnswerThirteen {

public static void main(String [] args){


ArrayList<String> hello = new ArrayList<String>();
hello.add("House");
hello.add("House");
hello.add("House");

130
hello.add("Dog");
hello.add("Dog");
hello.add("Dog");
hello.add("Dog");
Set<String> uniqueWords = new HashSet<String>(hello);
for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(hello, word));
}
}
}
Larsen And Toubro (L&T)
ANS 1)
If you build using servlets, JDBC DAOs and JSPs, then it would be fairly straightforward to introduce Spring to the
application at a later date:
Replace the servlet code with Spring controllers. This would be doing Spring a bit of a dis-service, since
they're capable of being so much more than just servlet replacements, but it's a start.
In your JDBC DAOs, make use of Spring's JdbcDaoSupport and/or JdbcTemplate support classes. The bulk
of your JDBC code would remain unchanged, you'd just be able to remove some of the plumbing and let
Spring take the strain.
If your app makes use of web page forms, you can use Spring's form taglib if you choose, although that
would require re-engineering the controllers also. You can just leave the JSPs as they are, if you choose,
completely unmodified.
You can start using your Spring context to start auto-wiring your controllers and DAOs together, reducing
manually-written wiring.
You can do any of these steps in any order, one step at a time. Spring is pretty good at being useful for as much as
you want it to be, and then getting out of the way.
Hibernate's a different kettle of fish. It's big and complex, and a bit scary to begin with. I suggest getting settled in
with Spring first, since Spring makes Hibernate a bit easier to handle.
ANS 2)
ArrayList and HashMap are two commonly used collection classes in Java. Even though both are the part of
collection framework, the way they store and process the data is entirely different. In this post we will see the main
differences between these two collections.

131
ArrayList vs HashMap in Java

1) Implementation: ArrayList implements List Interface while HashMap is an implementation of Map interface.
List and Map are two entirely different collection interfaces.
2) Memory consumption: ArrayList stores the elements value alone and internally maintains the indexes for each
element.
ArrayList<String> arraylist = new ArrayList<String>();
//String value is stored in array list
arraylist.add("Test String");
HashMap stores key & value pair. For each value there must be a key associated in HashMap. That clearly shows
that memory consumption is high in HashMap compared to the ArrayList.
HashMap<Integer, String> hmap= new HashMap<Integer, String>();
//String value stored along with the key value in hash map
hmap.put(123, "Test String");
3) Order: ArrayList maintains the insertion order while HashMap doesnt. Which means ArrayList returns the list
items in the same order in which they got inserted into the list. On the other side HashMap doesnt maintain any
order, the returned key-values pairs are not sorted in any kind of order.
4) Duplicates: ArrayList allows duplicate elements but HashMap doesnt allow duplicate keys (It does allow
duplicate values).
5) Nulls: ArrayList can have any number of null elements. HashMap allows one null key and any number of null
values.
6) get method: In ArrayList we can get the element by specifying the index of it. In HashMap the elements is being
fetched by specifying the corresponding key.

ANS 3)

How HashMap Internally Works in Java

Questions start with simple statement:

Have you used HashMap before or What is HashMap? Why do you use it
Almost everybody answers this with yes and then interviewee keep talking about common facts about HashMap
like HashMap accept null while Hashtable doesn't, HashMap is not synchronized, HashMap is fast and so on
along with basics like its stores key and value pairs etc. This shows that person has used HashMap and quite
familiar with the functionality it offers, but interview takes a sharp turn from here and next set of follow-up
questions gets more detailed about fundamentals involved with HashMap in Java. Interviewer strike back with
questions like:

Do you Know how HashMap works in Java or How does get () method of HashMap works in Java
And then you get answers like, I don't bother its standard Java API, you better look code on Java source or Open
JDK; I can find it out in Google at any time etc. But some interviewee definitely answers this and will say

132
HashMap works on the principle of hashing, we have put(key, value) and get(key) method for
storing and retrieving Objects from HashMap. When we pass Key and Value object to put() method on Java
HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its
own hashing function to find a bucket location for storing Entry object, important point to mention is that
HashMap in Java stores both key and value object as Map.Entry in a bucket which is essential to understand the
retrieving logic.

If people fail to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving
logic of any object stored in Java HashMap. This answer is very much acceptable and does make sense that
interviewee has a fair bit of knowledge on how hashing works and how HashMap works in Java. But this is just
start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by
day basis. Next question could be about collision detection and collision resolution in Java HashMap e.g.

What will happen if two different objects have the same hashcode?
Now from here onwards real confusion starts, sometime candidate will say that since hashcode is equal, both
objects are equal and HashMap will throw exception or not store them again etc, Then you might want to remind
them about equals() and hashCode() contract that two unequal objects in Java can have same hashcode.
Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would
be same and collision will occur in HashMap Since HashMap uses LinkedList to store object, this entry (object
of Map.Entry comprise key and value ) will be stored in LinkedList. Great this answer make sense though
there are many collision resolution methods available like linear probing and chaining, this is simplest and
HashMap in Java does follow this. But story does not end here and interviewer asks

How will you retrieve Value object if two Keys will have the same hashcode?

Interviewee will say we will call get() method and then HashMap uses Key Object's hashcode to find
out bucket location and retrieves Value object but then you need to remind him that there are two Value objects are
stored in same bucket , so they will say about traversal in LinkedList until we find the value object , then you ask
how do you identify value object because you don't have value object to compare ,Until they know that HashMap
stores both Key and Value in LinkedList node or as Map.Entry they won't be able to resolve this issue and
will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location, we will
call keys.equals() method to identify a correct node in LinkedList and return associated value object for that key
in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashCode() and equals() or
keys and values object in Java HashMap which is pretty obvious because they are dealing with the

133
hashcode() in all previous questions and equals() come in picture only in case of retrieving value object
from HashMap in Java. Some good developer point out here that using immutable, final object with proper
equals() and hashcode() implementation would act as perfect Java HashMap keys and improve the
performance of Java HashMap by reducing collision. Immutability also allows caching their hashcode of
different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes
e.g. Integer very good keys in Java HashMap.

Now if you clear this entire Java HashMap interview, You will be surprised by this very interesting question
"What happens On HashMap in Java if the size of the HashMap exceeds a given threshold defined by load
factor ?". Until you know how HashMap works exactly you won't be able to answer this question. If the size of
the Map exceeds a given threshold defined by load-factor e.g. if the load factor is .75 it will act to re-size the
map once it filled 75%. Similar to other collection classes like ArrayList, Java HashMap re-size itself by creating
a new bucket array of size twice of the previous size of HashMap and then start putting every old element into that
new bucket array. This process is called rehashing because it also applies the hash function to find new bucket
location.

If you manage to answer this question on HashMap in Java you will be greeted by "do you see any problem with
resizing of HashMap in Java" , you might not be able to pick the context and then he will try to give you hint
about multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap in
Java.

134
So the answer is Yes there is potential race condition exists while resizing HashMap in Java, if two thread at the
same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of
HashMap in Java, the element in the bucket which is stored in linked list get reversed in order during their
migration to new bucket because Java HashMap doesn't append the new element at tail instead it append new
element at the head to avoid tail traversing. If race condition happens then you will end up with an infinite loop.
Though this point, you can potentially argue that what the hell makes you think to use HashMap in multi-threaded
environment to interviewer :)

ANS 7)

Internal implementation of Set/HashSet (How Set Ensures Uniqueness) : Core


Java Collection Interview Question

In core java interview questions , It is common to get bombarded with Collection framework questions . I was
interviewed in Goldman Sachs , and there they asked a question where i got dumbstruck . Interviewer asked How
do you implement Set in Java in other words internal working of Hashset or How hashset works in java. That is ,
how will make sure each and every element is unique without using Set interfaces or Classes that implements Set
Interface .

Read Also : How hash map works in java

I gave the answer , although qualified the interview round as well , but the answer is far from satisfactory .
So I came back to home and do some research . So finally i got the answer and sharing it with you .
Set Implementation Internally in Java

Each and every element in the set is unique . So that there is no duplicate element in set .

So in java if we want to add elements in the set then we write code like this

public class JavaHungry {

public static void main(String[] args)


{
// TODO Auto-generated method stub

HashSet<Object> hashset = new HashSet<Object>();


hashset.add(3);
hashset.add("Java Hungry");
hashset.add("Blogspot");
System.out.println("Set is "+hashset);
}
}

It will print the result : Set is [3, Java Hungry, Blogspot]

135
Now let add duplicate element in the above code

public class JavaHungry {

public static void main(String[] args)


{
HashSet<Object> hashset = new HashSet<Object>();
hashset.add(3);
hashset.add("Java Hungry");
hashset.add("Blogspot");
hashset.add(3); // duplicate elements
hashset.add("Java Hungry"); // duplicate elements
System.out.println("Set is "+hashset);
}
}

It will print the result : Set is [3, Java Hungry, Blogspot]

Now , what happens internally when you pass duplicate elements in the add() method of the Set object , It will
return false and do not add to the HashSet , as the element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Apis that is rt.jar , you will find the
following code in it

public class HashSet<E>


extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map

private static final Object PRESENT = new Object();

public HashSet() {
map = new HashMap<>();
}

136
// SOME CODE ,i.e Other methods in Hash Set

public boolean add(E e) {


return map.put(e, PRESENT)==null;
}

// SOME CODE ,i.e Other methods in Hash Set


}

So , we are achieving uniqueness in Set,internally in java through HashMap . Whenever you create an
object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .
We already discussed How HashMap works internally in java .

As we know in HashMap each key is unique . So what we do in the set is that we pass the argument in the
add(Elemene E) that is E as a key in the HashMap . Now we need to associate some value to the key , so
what Java apis developer did is to pass the Dummy value that is ( new Object () ) which is referred by
Object reference PRESENT .

So , actually when you are adding a line in HashSet like hashset.add(3) what java does internally is that it
will put that element E here 3 as a key in the HashMap(created during HashSet object creation) and some
dummy value that is Object's object is passed as a value to the key .

Now if you see the code of the HashMap put(Key k,Value V) method , you will find something like this

public V put(K key, V value) {


//Some code
}

The main point to notice in above code is that put (key,value) will return

1. null , if key is unique and added to the map


2. Old Value of the key , if key is duplicate

So , in HashSet add() method , we check the return value of map.put(key,value) method with null value
i.e.

public boolean add(E e) {


return map.put(e, PRESENT)==null;
}

So , if map.put(key,value) returns null ,then


map.put(e, PRESENT)==null will return true and element is added to the HashSet.

137
So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null will return false and element is not added to the HashSet .

If you still have any doubts then please write in comments .


NOT COMPANY REATED BUT CRITICAL
1. > Hashtable is suitable for multi-threaded environment.

Hashtable is not suitable for multi-threaded environment. Always use ConcurrentHashMap instead of Hashtable, Hashtable
slow and legacy.

Reply

2.

Konstantin Ignatyev
February 4th, 2013 at 7:45 am
#16 What is UnsupportedOperationException?

Testament to the bad design of the collection package that does not have separate interfaces for modifiable and non
modifiable collections :)

Reply

3.

Sergei
February 4th, 2013 at 7:56 am
> Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom
class.

Very strange practice, implementing equals and hashCode is normally and HashBuilder, EqualsBuilder from ApacheCommons
very helpful.

WEB SERVICE REST INTERVIEW QUESTION AND ANSWER


1) What is REST and RESTful web services ?

this is the first REST interview question on most of interviews as not everybody familiar with REST and also

start discussion based on candidates response. Anyway REST stands for REpresentational State Transfer (REST) its a
relatively new concept of writing web services which enforces a stateless client server design where web services are
treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by
WSDL.

Web services written by apply REST Architectural concept are called RESTful web services which focus on System
resources and how state of Resource should be transferred over http protocol to a different clients written in different
languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD
operations.

138
2) What is differences between RESTful web services and SOAP web services ?

Though both RESTful web series and SOAP web service can operate cross platform they are architecturally different to
each other, here is some of differences between REST and SOAP:

1) REST is more simple and easy to use than SOAP

2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.

3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.

4) REST supports different format like text, JSON and XML while SOAP only support XML.

5) REST web services call can be cached to improve performance.

3) What is Restlet framework ?

Restlet is leading RESTful web framework for Java applications is used to build RESTFul web services it has two part
Restlet API and a Restlet implementation much like Servlet specification. There are many implementation of Restlet
framework available you just need to add there jar in your classpath to use them. By using Restlet web framework you
can write client and server.

4) What is Resource in REST framework ?

139
it represent a "resource" in REST architecture. on RESTLET API it has life cycle methods like init(), handle() and release()
and contains a Context, Request and Response corresponding to specific target resource. This is now deprecated over
ServerResource class and you should use that. see Restlet documentation for more details.

5) Can you use Restlet without any web-container ?

Yes, Restlet framework provide default server which can be used to handle service request in web container is not
available.

6) What is difference between Restlets and Jersey ?

This REST web service interview questions is open for you all, post you answer in comment section.

7) What is RESTEasy ?

RESTEasy is another REST framework introduced in JBoss Application Server. This was rather easy REST interview
questions. you can answer in detail only if you have used this or working in JBoss.

8) What are the tools used for creating RESTFull web services ?

You can use AJAX(Asynchronous JavaScript with XAML) and Direct Web Removing to consume web serives in web
application. Both Eclipse and NetBeans also supported development of RESTFul services.

9) How to display custom error pages using RestFull web services ?

In order to customize error you need to extend StatusService and implement getRepresentation(Status, Request,
Response) method with your custom code now assign instance of your CustomStatusService to appropriate
"statusService property".

10) Which HTTP methods are supported by RestFull web services ?

Another common REST interview questioning RESTFul web service each Resource supports GET, POST, PUT and DELETE
http methods.GET is mapped to represent(), POST - acceptRepresentation(), PUT- storeRepresentation and DELET for
rmeoveRepresentation.

11) What is difference between top-down and bottom-up approach of developing web services ?

In top-down approach first WSDL document is created and than Java classes are developed based on WSDL contract, so
if WSDL contract changes you got to change your Java classes while in case of bottom up approach of web service
development you first create Java code and then use annotations like @WebService to specify contract or interface and
WSDL field will be automatically generated from your build.

12) What happens if RestFull resources are accessed by multiple clients ? do you need to make it thread-
safe?

Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or add
synchronization. multiple client can safely access RestFull resources concurrently.

140
Top 10 RESTful Web Service Interview Questions for Java Developers

REST is an architectural style of developing web services which has become immensely popular in last couple of
years and consequently gained lot of importance in core Java and Java EE interviews. If you are a Java web
developer then you are most likely see couple of questions from web services every time you go for a Java web
developer interview. One of the most frequently one is difference between REST and SOAP web services, which I
have recently answered there, but there are lot many other good questions I have collected from friends and my
readers, which I have not yet published. In this article, I am sharing those questions, mainly based upon REST
style web services for your practice and preparation. Some of them are easy to answer and you will find them
either in my blog or by doing Google but couple of them is really interesting and challenging and required real
solid experience in Java web service domain to answer. I leave it to you guys for now and will probably update
this post with answers in near future. If you don't find answer of any REST interview question then I suggest you
to take a look at these two books, Java Programming Interview Exposed and RESTful Web Services, you will
most likely find your answer there.

RESTful Web Services Interview Questions

Here is my list of RESTful web services questions for senior Java developers who has couple of years of
experience developing both SOAP and REST based web services. This is actually second part of my series of Java
web services based question, in earlier article I have shared some SOAP web services based questions. If you have
not looked already, you may want to take a look.

Question 1 : What is REST?


Answer : REST is an architectural style of developing web services which take advantage of ubiquity of HTTP
protocol and leverages HTTP method to define actions. REST stands for REpresntational State Transfer.

Question 2 : What is RESTFul Web Service?


Answer : There are two popular way to develop web services, using SOAP (Simple Object Access Protocol) which
is XML based way to expose web services and second REST based web services which uses HTTP protocol. Web
services developed using REST style is also known as RESTful web services.

Question 3 : What is HTTP Basic Authentication and how it works?

Question 4 : Can you tell me which API can be used to develop RESTFul web service in Java?
Answer : There are many framework and libraries out there which helps to develop RESTful web services in Java
including JAX-RS which is standard way to develop REST web services. Jersey is one of the popular
implementation of JAX-RS which also offers more than specification recommends. Then you also have
RESTEasy, RESTlet and Apache CFX. If you like Scala then you can also use Play framework to develop
RESTful web services.

141
Question 5 : How do you configure RESTFul web service?

Question 6 : How you apply security in RESTFul web services?

Question 7 : Have you used securing RESTful APIs with HTTP Basic Authentication

Question 8 : How you maintain session in RESTful services?

Question 9 : Have you used Jersey API to develop RESTful services in Java?
Answer : Jersey is one of the most popular framework and API to develop REST based web services in Java.
Since many organization uses Jersey they check if candidate has used it before or not. It's simple to answer, say
Yes if you have really used and No, if you have not. In case of No, you should also mention which framework you
have used for developing RESTful web services e.g. Apache CFX, Play or Restlet.

Question 10 : How you test RESTful web services?

Question 11 : What is WADL in RESTFul?

Question 12 : What do you understand by payload in RESTFul?


Answer : Payload means data which passed inside request body also payload is not request parameters. So only
you can do payload in POST and not in GET and DELTE method

Question 13 : Can you do payload in GET method?


Answer : No, payload can only be passed using POST method.

Question 14 : Can you do payload in HTTP DELETE?


Answer : This is again similar to previous REST interview question, answer is No. You can only pass payload
using HTTP POST method.

Question 15 : How much maximum pay load you could do in POST method?
Answer : If you remember difference between GET and POST request then you know that unlike GET which
passes data on URL and thus limited by maximum URL length, POST has no such limit. So, theoretically you can
pass unlimited data as payload to POST method but you need to take practical things into account e.g. sending
POST with large payload will consume more bandwidth, take more time and present performance challenge to
your server.

Question 16 : What is difference between SOAP and RESTFul web services?


Answer : There are many difference between these two style of web services e.g. SOAP take more bandwidth
because of heavy weight XML based protocol but REST takes less bandwidth because of popular use of JSON as
message protocol and leveraging HTTP method to define action. This also means that REST is faster than SOAP
based web services. You can derive many differences between SOAP and RESTful with the fact that its HTTP
based e.g. REST URLs can be cached or bookmarked. Here are few more differences between them :

142
Question 17 : If you have to develop web services which one you will choose SOAP OR RESTful and why?
Answer : You can answer this question based upon your experience but the key here is if you know difference
between them than you can answer this question in more detail. For example, its easy to develop RESTful web
services than SOAP based web services but later comes with some in-built security features.

Question 18 : What framework you had used to develop RESTFul services?


Answer : This is really experience based question. If you have used Jersey to develop RESTFul web services then
answer as Jersey but expect some follow-up question on Jersey. Similarly if you have used Apache CFX or Restlet
then answer them accordingly.

1. What is differences between RESTful web services and SOAP web services ?
Ans:Though both RESTful web series and SOAP web service can operate cross platform they are architecturally
different to each other, here is some of differences between REST and SOAP:
1) REST is more simple and easy to use than SOAP. REST language is based on use of nouns and verbs (better
readability)
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP,
UDP SMTP, etc.
The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDAs. REST does not
need XML parsing, no message header (to and from), hence less bandwidth
4) REST supports different format like text, JSON and XML while SOAP only support XML.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The
focus is on accessing the named operations and exposing the application logic as a service.
The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used
because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is

143
on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the
XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.
GET represent()
POST acceptRepresention()
PUT storeRepresention()
DELETE removeRepresention()
5) SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
6) Different error handling:
REST: requires HTTP error handling
SOAP: can have user defined error
7) REST only supports synchronous message because of its reliance of HTTP and HTTPS
8) SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like
maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not
just point to point SSL only, securing different parts of the message with different security algorithms, etc.
The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is
sensitive or not.
9) The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions
and compensation based transaction management for long-running transactions. It also supports two-phase commit
across distributed resources.
The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across
distributed transactional resources as it is limited by its HTTP protocol.
10) The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP
intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal
with communication failures by retrying.
2. What is REST and RESTful web services?
Ans:This is the first REST interview question on most of interviews as not everybody familiar with REST and also
start discussion based on candidates response. Anyway REST stands for REpresentational State Transfer (REST) its
a relatively new concept of writing web services which enforces a stateless client server design where web services
are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were
defined by WSDL.
Web services written by apply REST Architectural concept are called RESTful web services which focus on System
resources and how state of Resource should be transferred over http protocol to a different clients written in
different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to
perform CRUD operations.
3.What is difference between top-down and bottom-up approach of developing web services ?
Ans:In top-down approach first WSDL document is created and than Java classes are developed based on WSDL
contract, so if WSDL contract changes you got to change your Java classes while in case of bottom up approach of
web service development you first create Java code and then use annotations like @WebService to specify contract
or interface and WSDL field will be automatically generated from your build.
4.What happens if RestFull resources are accessed by multiple clients ? do you need to make it thread-safe?
Ans:Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or
add synchronization. Multiple clients can safely access RestFull resources concurrently.
5.What will you do when an error code has to be returned to the client
OR
How will you handle application error scenarios in RESTful web service?

144
6.What is a web service?
Ans:A Web service is a method of communication between two electronic devices over the Web (Internet).
The W3C defines a Web service as a software system designed to support interoperable machine-to-machine
interaction over a network. It has an interface described in a machine-processable format (specifically Web
Services Description Language, known by the acronym WSDL). Other systems interact with the Web service in a
manner prescribed by its description using SOAP messages, typically conveyed using HTTP with
an XMLserialization in conjunction with other Web-related standards.
7.Can I use GET request instead of PUT to create resources?
Ans:No, you are supposed to use PUT or POST. GET operations should only have view rights.
8.What all kind of output formats can one generate using RESTful web service?
9.What all tools have you used to write RESTful web service?
10.What is meant by JAX-WS and JAX-RS?
Ans:Java API for XML Web Services(JAX-WS)
Java API for RESTful Web Services (JAX-RS)
11.What are the different application integration styles?
Ans. There are a number of different integration styles like
1. Shared database
2. batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

145
12.What are the different styles of Web Services used for application integration?
Ans. SOAP WS and RESTful Web Service
13.How would you decide what style of Web Service to use? SOAP WS or REST?
Ans. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support
for multiple data formats. SOAP is favored where service requires comprehensive support for security and
transactional reliability.

146
The answer really depends on the functional and non-functional requirements. Asking the questions listed below
will help you choose.
Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS
might be a better choice for logic).Do the consumers and the service providers require a formal contract?
(SOAP has a formal contract via WSDL)
Do we need to support multiple data formats?
Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
Is the call synchronous or asynchronous?
Is the call stateful or stateless? (REST is suited for stateless CRUD operations)
What level of security is required? (SOAP WS has better support for security)
What level of transaction support is required? (SOAP WS has better support for transaction management)
Do we have limited band width? (SOAP is more verbose)
Whats best for the developers who will build clients for the service? (REST is easier to implement, test,
and maintain)
14. What tools do you use to test your Web Services?
Ans:SoapUI tool for SOAP WS and the Firefox poster plugin for RESTFul services.
15.What is the difference between SOA and a Web service?
Ans:SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and
coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI,
IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).
Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based
applications without using Web services for example by using other traditional technologies like Java RMI, EJB,
JMS based messaging, etc. But what Web services offer is the standards based and platform-independent service via
HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as
J2EE and .NET.
16.Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM?
Ans:The traditional middle-wares tightly couple connections to the applications and it can break if you make any
modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do
not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use.
Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction
between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-
usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and
platform independent. You can develop a Web service using any language and deploy it on to any platform, from
small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and
communicates between disparate applications by passing XML messages to each other via a Web API. Do work
across internet, less expensive and easier to use.
17.What are the different approaches to developing a SOAP based Web service?
Ans. Following are the two approaches.
The contract-first approach, where you define the contract first with XSD and WSDL and the generate the
Java classes from the contract.
147
The contract-last approach where you define the Java classes first and then generate the contract, which is
the WSDL file from the Java classes.
Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e. where the
services can be invoked), and simple and complex elements that can be passed in requests and responses.
18.What are the pros and cons of each approach, and which approach would you prefer?
Ans:
Contract-first Web service
PROS:
Clients are decoupled from the server, hence the implementation logic can be revised on the server without
affecting the clients.
Developers can work simultaneously on client and server side based on the contract both agreed on.
You have full control over how the request and response messages are constructed for example, should
status go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e.
Object to XML Mapping) libraries without having to worry if the status would be generated as attribute
instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from
say Apache Axis to Apache CXF, etc
CONS:
More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen
XML, etc to make things easier. The object models need to be written as well.
Developers need to learn XSDs and WSDLs in addition to just knowing Java.
Contract-last Web service
PROS:
Developers dont have to learn anything related to XSDs, WSDLs, and SOAP. The services are created
quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based
wizards, etc.
The learning curve and development time can be smaller compared to the Contract-first Web service.
CONS:
The development time can be shorter to initially develop it, but what about the on going maintenance and
extension time if the contract changes or new elements need to be added? In this approach, since the clients
and servers are more tightly coupled, the future changes may break the client contract and affect all clients or
require the services to be properly versioned and managed.
In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could
cause something that used to be an element to become an attribute with the change of the OXM.
19.So, which approach will you choose?
Ans:The best practice is to use contract-first, and here is the link that explains this much better with examples
> contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the contract-
first. You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.

148
Web Services Interview Questions SOAP and REST

Recently I have written a lot about web services and how we can create SOAP and REST web services in Java.
Here I am providing you a list of web services interview questions to help you in interview. First of all there are
generic questions for web services concept since its not technology or language specific and then we have java
web services interview questions.
1. What is a Web Service?
2. What are the advantages of Web Services?
3. What are different types of Web Services?
4. What is SOAP?
5. What are advantages of SOAP Web Services?
6. What are disadvantages of SOAP Web Services?
7. What is WSDL?
8. What are different components of WSDL?
9. What is UDDI?
10. What is difference between Top Down and Bottom Up approach in SOAP Web Services?
11. What is REST Web Services?
12. What are advantages of REST web services?
13. What are disadvantages of REST web services?
14. What is a Resource in Restful web services?
15. What are different HTTP Methods supported in Restful Web Services?
16. Compare SOAP and REST web services?
17. What are different ways to test web services?
18. Can we maintain user session in web services?
19. What is difference between SOA and Web Services?
20. What is the use of Accept and Content-Type Headers in HTTP Request?
21. How would you choose between SOAP and REST web services?
22. What is JAX-WS API?
23. Name some frameworks in Java to implement SOAP web services?
24. Name important annotations used in JAX-WS API?
25. What is use of javax.xml.ws.Endpoint class?

149
26. What is the difference between RPC Style and Document Style SOAP web Services?
27. How to get WSDL file of a SOAP web service?
28. What is sun-jaxws.xml file?
29. What is JAX-RS API?
30. Name some implementations of JAX-RS API?
31. What is wsimport utility?
32. Name important annotations used in JAX-RS API?
33. What is the use of @XmlRootElement annotation?
34. How to set different status code in HTTP response?

What is a Web Service?


Web Services work on client-server model where client applications can access web services over the
network. Web services provide endpoint URLs and expose methods that can be accessed over network
through client programs written in java, shell script or any other different technologies.
Web services are stateless and doesnt maintain user session like web applications.

What are the advantages of Web Services?


Some of the advantages of web services are:
o Interoperability: Web services are accessible over network and runs on HTTP/SOAP protocol and
uses XML/JSON to transport data, hence it can be developed in any programming language. Web
service can be written in java programming and client can be PHP and vice versa.
o Reusability: One web service can be used by many client applications at the same time.

o Loose Coupling: Web services client code is totally independent with server code, so we have
achieved loose coupling in our application.
o Easy to deploy and integrate, just like web applications.

o Multiple service versions can be running at same time.

What are different types of Web Services?


There are two types of web services:
1. SOAP Web Services: Runs on SOAP protocol and uses XML technology for sending data.

2. Restful Web Services: Its an architectural style and runs on HTTP/HTTPS protocol almost all the
time. REST is a stateless client-server architecture where web services are resources and can be
identified by their URIs. Client applications can use HTTP GET/POST methods to invoke Restful
web services.

What is SOAP?

150
SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard protocol for
designing and developing web services. Since its XML based, its platform and language independent. So
our server can be based on JAVA and client can be on .NET, PHP etc. and vice versa.

What are advantages of SOAP Web Services?


SOAP web services have all the advantages that web services has, some of the additional advantages are:
o WSDL document provides contract and technical details of the web services for client applications
without exposing the underlying implementation technologies.
o SOAP uses XML data for payload as well as contract, so it can be easily read by any technology.

o SOAP protocol is universally accepted, so its an industry standard approach with many easily
available open source implementations.

What are disadvantages of SOAP Web Services?


Some of the disadvantages of SOAP protocol are:
o Only XML can be used, JSON and other lightweight formats are not supported.

o SOAP is based on the contract, so there is a tight coupling between client and server applications.

o SOAP is slow because payload is large for a simple string message, since it uses XML format.

o Anytime there is change in the server side contract, client stub classes need to be generated again.

o Cant be tested easily in browser

What is WSDL?
WSDL stands for Web Service Description Language. WSDL is an XML based document that provides
technical details about the web service. Some of the useful information in WSDL document are: method
name, port types, service end point, binding, method parameters etc.

What are different components of WSDL?


Some of the different tags in WSDL xml are:
o xsd:import namespace and schemaLocation: provides WSDL URL and unique namespace for web
service.
o message: for method arguments

o part: for method argument name and type

o portType: service name, there can be multiple services in a wsdl document.

o operation: contains method name

o soap:address for endpoint URL.

What is UDDI?

151
UDDI is acronym for Universal Description, Discovery and Integration. UDDI is a directory of web services
where client applications can lookup for web services. Web Services can register to the UDDI server and
make them available to client applications.

What is difference between Top Down and Bottom Up approach in SOAP Web Services?
In Top Down approach first WSDL document is created to establish the contract between web service and
client and then code is written, its also termed as contract first approach. This is hard to implement because
classes need to be written to confirm the contract established in WSDL. Benefit of this approach is that both
client and server code can be written in parallel.
In Bottom Up approach, first web service code is written and then WSDL is generated. Its also termed as
contract last approach. This approach is easy to implement because WSDL is generated based on code. In
this approach client code have to wait for WSDL from server side to start their work.

What is REST Web Services?


REST is the acronym for REpresentational State Transfer. REST is an architectural style for developing
applications that can be accessed over the network. REST architectural style was brought in light by Roy
Fielding in his doctoral thesis in 2000.
REST is a stateless client-server architecture where web services are resources and can be identified by their
URIs. Client applications can use HTTP GET/POST methods to invoke Restful web services. REST doesnt
specify any specific protocol to use, but in almost all cases its used over HTTP/HTTPS. When compared to
SOAP web services, these are lightweight and doesnt follow any standard. We can use XML, JSON, text or
any other type of data for request and response.

What are advantages of REST web services?


Some of the advantages of REST web services are:
o Learning curve is easy since it works on HTTP protocol

o Supports multiple technologies for data transfer such as text, xml, json, image etc.

o No contract defined between server and client, so loosely coupled implementation.

o REST is a lightweight protocol

o REST methods can be tested easily over browser.

What are disadvantages of REST web services?


Some of the disadvantages of REST are:
o Since there is no contract defined between service and client, it has to be communicated through
other means such as documentation or emails.
o Since it works on HTTP, there cant be asynchronous calls.

o Sessions cant be maintained.

What is a Resource in Restful web services?

152
Resource is the fundamental concept of Restful architecture. A resource is an object with a type, relationship
with other resources and methods that operate on it. Resources are identified with their URI, HTTP methods
they support and request/response data type and format of data.

What are different HTTP Methods supported in Restful Web Services?


Restful web services supported HTTP methods are GET, POST, PUT, DELETE and HEAD.

Compare SOAP and REST web services?


SOAP REST
SOAP is a standard protocol for creating web
REST is an architectural style to create web services.
services.
SOAP is acronym for Simple Object Access
REST is acronym for REpresentational State Transfer.
Protocol.
SOAP uses WSDL to expose supported methods REST exposes methods through URIs, there are no
and technical details. technical details.
SOAP web services and client programs are bind REST doesnt have any contract defined between
with WSDL contract server and client
SOAP web services and client are tightly coupled
REST web services are loosely coupled.
with contract.
SOAP learning curve is hard, requires us to learn REST learning curve is simple, POJO classes can be
about WSDL generation, client stubs creation etc. generated easily and works on simple HTTP methods.
REST supports any data type such as XML, JSON,
SOAP supports XML data format only
image etc.
SOAP web services are hard to maintain, any REST web services are easy to maintain when
change in WSDL contract requires us to create compared to SOAP, a new method can be added
client stubs again and then make changes to client without any change at client side for existing
code. resources.
SOAP web services can be tested through REST can be easily tested through CURL command,
programs or software such as Soap UI. Browsers and extensions such as Chrome Postman.

What are different ways to test web services?


SOAP web services can be tested programmatically by generating client stubs from WSDL or through
software such as Soap UI.
REST web services can be tested easily with program, curl commands and through browser extensions.
Resources supporting GET method can be tested with browser itself, without any program.

Can we maintain user session in web services?


Web services are stateless so we cant maintain user sessions in web services.

What is difference between SOA and Web Services?

153
Service Oriented Architecture (SOA) is an architectural pattern where applications are designed in terms of
services that can be accessed through communication protocol over network. SOA is a design pattern and
doesnt go into implementation.
Web Services can be thought of as Services in SOAP architecture and providing means to implement SOA
pattern.

What is the use of Accept and Content-Type Headers in HTTP Request?


These are important headers in Restful web services. Accept headers tells web service what kind of response
client is accepting, so if a web service is capable of sending response in XML and JSON format and client
sends Accept header as application/xml then XML response will be sent. For Accept header
application/json, server will send the JSON response.
Content-Type header is used to tell server what is the format of data being sent in the request. If Content-
Type header is application/xml then server will try to parse it as XML data. This header is useful in HTTP
Post and Put requests.

How would you choose between SOAP and REST web services?
Web Services work on client-server model and when it comes to choose between SOAP and REST, it all
depends on project requirements. Lets look at some of the conditions affecting our choice:
o Do you know your web service clients beforehand? If Yes, then you can define a contract before
implementation and SOAP seems better choice. But if you dont then REST seems better choice
because you can provide sample request/response and test cases easily for client applications to use
later on.
o How much time you have? For quick implementation REST is the best choice. You can create web
service easily, test it through browser/curl and get ready for your clients.
o What kind of data format are supported? If only XML then you can go with SOAP but if you think
about supporting JSON also in future then go with REST.

What is JAX-WS API?


JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to build web
services server and client application. Its part of standard Java API, so we dont need to include anything
else which working with it. Refer to JAX-WS Tutorial for a complete example.

Name some frameworks in Java to implement SOAP web services?


We can create SOAP web services using JAX-WS API, however some of the other frameworks that can be
used are Apache Axis and Apache CXF. Note that they are not implementations of JAX-WS API, they are
totally different framework that work on Servlet model to expose your business logic classes as SOAP web
services. Read more at Java SOAP Web Service Eclipse example.

Name important annotations used in JAX-WS API?


Some of the important annotations used in JAX-WS API are:
o @WebService

o @SOAPBinding

154
o @WebMethod

What is use of javax.xml.ws.Endpoint class?


Endpoint class provides useful methods to create endpoint and publish existing implementation as web
service. This comes handy in testing web services before making further changes to deploy it on actual
server.

What is the difference between RPC Style and Document Style SOAP web Services?
RPC style generate WSDL document based on the method name and its parameters. No type definitions are
present in WSDL document.
Document style contains type and can be validated against predefined schema. Lets look at these with a
simple program. Below is a simple test program where I am using Endpoint to publish my simple SOAP web
service.
TestService.java
1
package com.journaldev.jaxws.service;
2
3
import javax.jws.WebMethod;
4
import javax.jws.WebService;
5
import javax.jws.soap.SOAPBinding;
6
import javax.xml.ws.Endpoint;
7
8 @WebService
9 @SOAPBinding(style = SOAPBinding.Style.RPC)

10 public class TestService {


11
12 @WebMethod
public String sayHello(String msg){
13
return "Hello "+msg;
14
}
15
16
public static void main(String[] args){
17
Endpoint.publish("http://localhost:8888/testWS", new TestService());
18 }
19 }
20
When I run above program and then access the WSDL, it gives me below XML.

155
rpc.xml
1 <?xml version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI


2 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!-- Generated by
JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.10 svn-
3
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
4 <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-
wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
5 xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
6 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
7 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
8 targetNamespace="http://service.jaxws.journaldev.com/" name="TestServiceService">
9 <types/>
10 <message name="sayHello">
11 <part name="arg0" type="xsd:string"/>
12 </message>
<message name="sayHelloResponse">
13
<part name="return" type="xsd:string"/>
14
</message>
15
<portType name="TestService">
16 <operation name="sayHello">
17 <input
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHelloRequest"
18 message="tns:sayHello"/>
19 <output
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHelloResponse"
20 message="tns:sayHelloResponse"/>
21 </operation>
22 </portType>
<binding name="TestServicePortBinding" type="tns:TestService">
23
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
24
<operation name="sayHello">
25
<soap:operation soapAction=""/>
26
<input>
27 <soap:body use="literal" namespace="http://service.jaxws.journaldev.com/"/>
28 </input>
29 <output>
30 <soap:body use="literal" namespace="http://service.jaxws.journaldev.com/"/>
156
</output>

</operation>
</binding>
31
<service name="TestServiceService">
32
<port name="TestServicePort" binding="tns:TestServicePortBinding">
33
<soap:address location="http://localhost:8888/testWS"/>
34 </port>

</service>
</definitions>

Notice that types element is empty and we cant validate it against any schema. Now just change the
SOAPBinding.Style.RPC to SOAPBinding.Style.DOCUMENT and you will get below WSDL.

document.xml
1 <?xml version='1.0' encoding='UTF-8'?>
<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI
2
2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!-- Generated by
JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.10 svn-
3
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
4 <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-
wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
5 xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
6 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
7 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
8 targetNamespace="http://service.jaxws.journaldev.com/" name="TestServiceService">
9 <types>
10 <xsd:schema>
11 <xsd:import namespace="http://service.jaxws.journaldev.com/"
schemaLocation="http://localhost:8888/testWS?xsd=1"/>
12
</xsd:schema>
13 </types>
14 <message name="sayHello">
15 <part name="parameters" element="tns:sayHello"/>
16 </message>
17 <message name="sayHelloResponse">
<part name="parameters" element="tns:sayHelloResponse"/>
18
</message>
19
<portType name="TestService">
20

157
<operation name="sayHello">

<input
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHelloRequest"
message="tns:sayHello"/>
21
<output
22 wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHelloResponse"
message="tns:sayHelloResponse"/>
23
</operation>
24 </portType>
25 <binding name="TestServicePortBinding" type="tns:TestService">
26 <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
27 <operation name="sayHello">
28 <soap:operation soapAction=""/>
<input>
29
<soap:body use="literal"/>
30
</input>
31
<output>
32 <soap:body use="literal"/>
33 </output>
34 </operation>
35 </binding>
36 <service name="TestServiceService">
<port name="TestServicePort" binding="tns:TestServicePortBinding">
37
<soap:address location="http://localhost:8888/testWS"/>
38
</port>

</service>
</definitions>

Open schemaLocation URL in browser and you will get below XML.
schemaLocation.xml
1 <?xml version='1.0' encoding='UTF-8'?>
<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI
2
2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
3 <xs:schema xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0"
4 targetNamespace="http://service.jaxws.journaldev.com/">
5
6 <xs:element name="sayHello" type="tns:sayHello"/>

158
7
8 <xs:element name="sayHelloResponse" type="tns:sayHelloResponse"/>

9
10 <xs:complexType name="sayHello">
11 <xs:sequence>
<xs:element name="arg0" type="xs:string" minOccurs="0"/>
12
</xs:sequence>
13
</xs:complexType>
14
15
<xs:complexType name="sayHelloResponse">
16 <xs:sequence>
17 <xs:element name="return" type="xs:string" minOccurs="0"/>
18 </xs:sequence>
19 </xs:complexType>
20 </xs:schema>
So here WSDL document can be validated against the schema definintion.

How to get WSDL file of a SOAP web service?


WSDL document can be accessed by appending ?wsdl to the SOAP endoint URL. In above example, we can
access it at http://localhost:8888/testWS?wsdl location.

What is sun-jaxws.xml file?


This file is used to provide endpoints details when JAX-WS web services are deployed in servlet container
such as Tomcat. This file is present in WEB-INF directory and contains endpoint name, implementation
class and URL pattern. For example;
sun-jaxws.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
3 <endpoint

4 name="PersonServiceImpl"

5 implementation="com.journaldev.jaxws.service.PersonServiceImpl"
url-pattern="/personWS"/>
6
</endpoints>
7

What is JAX-RS API?

159
Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS
uses annotations to simplify the development and deployment of web services. JAX-RS is part of JDK, so
you dont need to include anything to use its annotations.

Name some implementations of JAX-RS API?


There are two major implementations of JAX-RS API.
1. Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-RS
implementation, all we need to configure its servlet in web.xml and add required dependencies. Note
that JAX-RS API is part of JDK not Jersey, so we have to add its dependency jars in our application.
2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

What is wsimport utility?


We can use wsimport utility to generate the client stubs. This utility comes with standard installation of JDK.
Below image shows an example execution of this utility for one of JAX-WS project.

Name important annotations used in JAX-RS API?


Some of the important JAX-RS annotations are:
o @Path: used to specify the relative path of class and methods. We can get the URI of a webservice by
scanning the Path annotation value.
o @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request type for a method.

o @Produces, @Consumes: used to specify the request and response types.

o @PathParam: used to bind the method parameter to path value by parsing it.

What is the use of @XmlRootElement annotation?


XmlRootElement annotation is used by JAXB to transform java object to XML and vice versa. So we have
to annotate model classes with this annotation.

160
How to set different status code in HTTP response?
For setting HTTP status code other than 200, we have to use javax.ws.rs.core.Response class for
response. Below are some of the sample return statements showing its usage.
1 return Response.status(422).entity(exception).build();
2 return Response.ok(response).build(); //200
For a complete example, please read RESTEasy Tutorial.
Does SOAP is a protocol. If SOAP is a protocol , SOAP should be a defined standards which used to
communicate date. But SOAP uses http or https.
Just to add, Restful web services also support PATCH, OPTIONS methods
Reply

Introduction to Restful Web Services Using JAX-RS

RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural
style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable
properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the
REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource
Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined
operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to
use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers
exchange representations of resources by using a standardized interface and protocol.
RESTful Web Services utilize the features of the HTTP Protocol to provide the API of the Web Service. It uses the
HTTP Request Types to indicate the type of operation:

GET: Retrieve / Query of existing records.


POST: Creating new records.
DELETE: Removing records.
PUT: Updating existing records.
Using these 4 HTTP Request Types a RESTful API mimics the CRUD operations (Create, Read, Update & Delete).
REST is stateless, each call the to a RESTful Web Service is completely stand-alone, it has no knowledge of
previous requests.
We are giving simple examples to create restful web services using JAX-RS standards.
- See more at: http://www.java2novice.com/restful-web-services/#sthash.y6c6Aolg.dpuf

REST Web Services - Interview Questions and Answers

Q1. What are RESTful Web Services ?

Ans. REST or Representational State Transfer is a flexible architecture style for creating

161
web services that recommends the following guidelines -

1. http for client server communication,


2. XML / JSON as formatiing language ,
3. Simple URI as address for the services and,
4. stateless communication.

Q2. Which markup languages can be used in restful web services ?

Ans. XML and JSON ( Javascript Object Notation ).

Q3. Why Web services use HTTP as the communication protocol ?

Ans. With the advent of Internet, HTTP is the most preferred way of communication. Most
of the clients ( web thin client , web thick clients , mobile apps ) are designed to
communicate using http only. Web Services using http makes them accessible from vast
variety of client applications.

Q4. What are the HTTP methods used in Rest Services ?

Ans. GET , PUT , POST and DELETE.

Q5. Difference between PUT and POST ?

Ans. PUT puts a file or resource at a specific URI, and exactly at that URI. If there's
already a file or resource at that URI, PUT replaces that file or resource. If there is no file
or resource there, PUT creates one.

POST sends data to a specific URI and expects the resource at that URI to handle the
request. The web server at this point can determine what to do with the data in the
context of the specified resource.

162
Spring MVC Interview Questions with Answers

These Spring MVC interview questions and answers have been written to help you prepare for the
interviews and quickly revise the concepts in general. I will strongly suggest you to go deeper into each
concept if you have extra time. The more you know, more you are confident.
Table of Contents

What is Spring MVC framework?


What is DispatcherServlet and ContextLoaderListener?
What is the front controller class of Spring MVC?
How to use Java based configuration?
How can we use Spring to create Restful Web Service returning JSON response?
Can we have multiple Spring configuration files?
Difference between <context:annotation-config> vs <context:component-scan>?
Difference between @Component, @Controller, @Repository & @Service annotations?
What does the ViewResolver class?
What is a MultipartResolver and when its used?
How to upload file in Spring MVC Application?
How does Spring MVC provide validation support?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
How to handle exceptions in Spring MVC Framework?
How to achieve localization in Spring MVC applications?
How to get ServletContext and ServletConfig object in a Spring Bean?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you relate Spring MVC Framework to 3-tier architecture?

What is Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and ready components that
can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the
different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling
between model, view and controller parts of application. Spring framework provides lots of advantages over other
MVC frameworks e.g.
1. Clear separation of roles -- controller, validator, command object, form object, model object,
DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object.
2. Powerful and straightforward configuration of both framework and application classes as JavaBeans.
3. Reusable business code -- no need for duplication. You can use existing business objects as command or
form objects instead of mirroring them in order to extend a particular framework base class.
4. Customizable binding and validation
5. Customizable handler mapping and view resolution
6. Customizable locale and theme resolution
7. A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier. etc.

163
What is DispatcherServlet and ContextLoaderListener?

Springs web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central
Servlet that handles all the HTTP requests and responses. Springs DispatcherServlet however, does more than just
that. It is completely integrated with the Spring IoC container so it allows you to use every feature that Spring has.
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping (configuration files) to call the
appropriate Controller. The Controller takes the request and calls the appropriate service methods and set model data
and then returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to
pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the
view which is finally rendered on the browser.
<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>spring</servlet-name>

<servlet-class>
org.springframework.web.servlet.DispatcherServlet

</servlet-class>
<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>

By default, DispatcherServlet loads its configuration file using <servlet_name>-servlet.xml. E.g. with above
web.xml file, DispatcherServlet will try to find spring-servlet.xml file in classpath.
ContextLoaderListener reads the spring configuration file (with value given against contextConfigLocation in
web.xml), parse it and loads the beans defined in that config file. e.g.
<servlet>
<servlet-name>spring</servlet-name>

<servlet-class>
org.springframework.web.servlet.DispatcherServlet

</servlet-class>

164
<init-param>

<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

What is the front controller class of Spring MVC?

A front controller is defined as a controller which handles all requests for a Web Application. DispatcherServlet
(actually a servlet) is the front controller in Spring MVC that intercepts every request and then
dispatches/forwards requests to an appropriate controller.
When a web request is sent to a Spring MVC application, dispatcher servlet first receives the request. Then it
organizes the different components configured in Springs web application context (e.g. actual request handler
controller and view resolvers) or annotations present in the controller itself, all needed to handle the request.

How to use Java based configuration?

To configure java based MVC application, first add required dependencies.


<!-- Spring MVC support -->

<dependency>
<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>

<version>4.1.4.RELEASE</version>
</dependency>

<!-- Tag libs support for view layer -->

165
<dependency>

<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>

<version>1.2</version>
<scope>runtime</scope>

</dependency>

<dependency>

<groupId>taglibs</groupId>
<artifactId>standard</artifactId>

<version>1.1.2</version>
<scope>runtime</scope>

</dependency>

Now add DispatcherServlet entry in web.xml file so that all incoming requests come though DispatcherServlet only.
<servlet>

<servlet-name>spring</servlet-name>
<servlet-class>

org.springframework.web.servlet.DispatcherServlet
</servlet-class>

<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>
</servlet-mapping>

Now add below entries in spring configuration file.


<beans>
<!-- Scan all classes in this path for spring specific annotations -->

<context:component-scan base-package="com.howtodoinjava.demo" />

<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

166
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

<!-- Vierw resolver configuration -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />


</bean>

</beans>

Add controller code.


@Controller

@RequestMapping("/employee-module")
public class EmployeeController

{
@Autowired

EmployeeManager manager;

@RequestMapping(value = "/getAllEmployees", method = RequestMethod.GET)

public String getAllEmployees(Model model)


{

model.addAttribute("employees", manager.getAllEmployees());
return "employeesListDisplay";

}
}

Additionally you should add manager and dao layer classes as well. Finally you add the jsp file to display the view.
I will suggest to read above linked tutorial for complete understanding.
Read More : Spring MVC Hello World Example

How can we use Spring to create Restful Web Service returning JSON response?

For adding JSON support to your spring application, you will need to add Jackson dependency in first step.
<!-- Jackson JSON Processor -->

<dependency>

167
<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>

</dependency>

Now you are ready to return JSON response from your MVC controller. All you have to do is return JAXB
annotated object from method and use @ResponseBody annotation on this return type.
@Controller

public class EmployeeRESTController


{

@RequestMapping(value = "/employees")
public @ResponseBody EmployeeListVO getAllEmployees()

{
EmployeeListVO employees = new EmployeeListVO();

//Add employees
return employees;

}
}

Alternatively, you can use @RestController annotation in place of @Controller annotation. This will remove the
need to using @ResponseBody.

@RestController = @Controller + @ResponseBody


So you can write the above controller as below.
@RestController
public class EmployeeRESTController

{
@RequestMapping(value = "/employees")

public EmployeeListVO getAllEmployees()


{

EmployeeListVO employees = new EmployeeListVO();


//Add employees

return employees;
}

Read More : Spring REST Hello World JSON Example

168
Can we have multiple Spring configuration files?

YES. You can have multiple spring context files. There are two ways to make spring read and configure them.
a) Specify all files in web.xml file using contextConfigLocation init parameter.
<servlet>
<servlet-name>spring</servlet-name>

<servlet-class>
org.springframework.web.servlet.DispatcherServlet

</servlet-class>
<init-param>

<param-name>contextConfigLocation</param-name>
<param-value>

WEB-INF/spring-dao-hibernate.xml,
WEB-INF/spring-services.xml,

WEB-INF/spring-security.xml
</param-value>

</init-param>
<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>

</servlet-mapping>

b) OR, you can import them into existing configuration file you have already configured.
<beans>

<import resource="spring-dao-hibernate.xml"/>
<import resource="spring-services.xml"/>

<import resource="spring-security.xml"/>

... //Other configuration stuff

</beans>

169
Difference between <context:annotation-config> vs <context:component-scan>?

1) First big difference between both tags is that <context:annotation-config> is used to activate applied
annotations in already registered beans in application context. Note that it simply does not matter whether bean
was registered by which mechanism e.g. using <context:component-scan> or it was defined in application-
context.xml file itself.
2) Second difference is driven from first difference itself. It registers the beans defined in config file into context
+ it also scans the annotations inside beans and activate them. So <context:component-scan> does what
<context:annotation-config> does, but additionally it scan the packages and register the beans in application
context.
<context:annotation-config> = Scanning and activating annotations in already registered beans.
<context:component-scan> = Bean Registration + Scanning and activating annotations
Read More : Difference between annotation-config and component-scan

Difference between @Component, @Controller, @Repository & @Service annotations?

1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can
pick it up and pull it into the application context. To use this annotation, apply it over class as below:
@Component

public class EmployeeDAOImpl implements EmployeeDAO {


...

2) The @Repository annotation is a specialization of the @Component annotation with similar use and functionality.
In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO
methods) eligible for translation into Spring DataAccessException.

3) The @Service annotation is also a specialization of the component annotation. It doesnt currently provide any
additional behavior over the @Component annotation, but its a good idea to use @Service over @Component in
service-layer classes because it specifies intent better.
4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so
beans marked with it are automatically imported into the DI container. When you add the @Controller annotation
to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

Read More : @Component, @Repository, @Service and @Controller Annotations?

What does the ViewResolver class?

ViewResolver is an interface to be implemented by objects that can resolve views by name. There are plenty of
ways using which you can resolve view names. These ways are supported by various in-built implementations of
this interface. Most commonly used implementation is InternalResourceViewResolver class. It defines prefix
and suffix properties to resolve the view component.

170
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/" />


<property name="suffix" value=".jsp" />

</bean>

So with above view resolver configuration, if controller method return login string, then the /WEB-
INF/views/login.jsp file will be searched and rendered.

What is a MultipartResolver and when its used?

Spring comes with MultipartResolver to handle file upload in web application. There are two concrete
implementations included in Spring:
1. CommonsMultipartResolver for Jakarta Commons FileUpload
2. StandardServletMultipartResolver for Servlet 3.0 Part API
To define an implementation, create a bean with the id multipartResolver in a DispatcherServlets application
context. Such a resolver gets applied to all requests handled by that DispatcherServlet.
If a DispatcherServlet detects a multipart request, it will resolve it via the configured MultipartResolver and
pass on a wrapped HttpServletRequest. Controllers can then cast their given request to the
MultipartHttpServletRequest interface, which permits access to any MultipartFiles.

How to upload file in Spring MVC Application?

Lets say we are going to use CommonsMultipartResolver which uses the Apache commons upload library to
handle the file upload in a form. So you will need to add the commons-fileupload.jar and commons-io.jar
dependencies.
<!-- Apache Commons Upload -->

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>

</dependency>

<!-- Apache Commons Upload -->

<dependency>
<groupId>commons-io</groupId>

<artifactId>commons-io</artifactId>
<version>1.3.2</version>

</dependency>

171
The following declaration needs to be made in the application context file to enable the MultipartResolver (along
with including necessary jar file in the application):
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->

<property name="maxUploadSize" value="100000"/>


</bean>

Now create model class FileUploadForm which will hold the multipart data submitted from HTML form.
import org.springframework.web.multipart.MultipartFile;

public class FileUploadForm

{
private MultipartFile file;

public MultipartFile getFile() {


return file;

public void setFile(MultipartFile file) {

this.file = file;
}

Now create FileUploadController class which will actually handle the upload logic.
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;
import com.howtodoinjava.form.FileUploadForm;

@Controller
public class FileUploadController

172
@RequestMapping(value = "/upload", method = RequestMethod.POST)

public String save(@ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map) {

MultipartFile multipartFile = uploadForm.getFile();

String fileName = "default.txt";

if (multipartFile != null) {

fileName = multipartFile.getOriginalFilename();
}

//read and store the file as you like

map.addAttribute("files", fileName);

return "file_upload_success";
}

The upload JSP file looks like this:


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<body>

<h2>Spring MVC file upload example</h2>


<form:form method="post" action="save.html" modelAttribute="uploadForm"
enctype="multipart/form-data">
Please select a file to upload : <input type="file" name="file" />

<input type="submit" value="upload" />


<span><form:errors path="file" cssClass="error" /></span>

</form:form>
</body>

</html>

How does Spring MVC provide validation support?

Spring supports validations primarily into two ways.


1. Using JSR-303 Annotations and any reference implementation e.g. Hibernate Validator
173
2. Using custom implementation of org.springframework.validation.Validator interface
In next question, you see an example about how to use validation support in spring MVC application.

How to validate form data in Spring Web MVC Framework?

Spring MVC supports validation by means of a validator object that implements the Validator interface. You need
to create a class and implement Validator interface. In this custom validator class, you use utility methods such as
rejectIfEmptyOrWhitespace() and rejectIfEmpty() in the ValidationUtils class to validate the required
form fields.
@Component
public class EmployeeValidator implements Validator

{
public boolean supports(Class clazz) {

return EmployeeVO.class.isAssignableFrom(clazz);
}

public void validate(Object target, Errors errors)


{

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName",


"First name is required.");

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName",


"Last name is required.");

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is


required.");

}
}

If any of form fields is empty, these methods will create a field error and bind it to the field. The second argument of
these methods is the property name, while the third and fourth are the error code and default error message.
To activate this custom validator as a spring managed bean, you need to do one of following things:
1) Add @Component annotation to EmployeeValidator class and activate annotation scanning on the package
containing such declarations.
<context:component-scan base-package="com.howtodoinjava.demo" />

2) Alternatively, you can register the validator class bean directly in context file.
<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />

Read More : Spring MVC Custom Validator and JSR-303 Annotations Examples

174
What is Spring MVC Interceptor and how to use it?

As you know about servlet filters that they can pre-handle and post-handle every web request they serve before
and after its handled by that servlet. In the similar way, you can use HandlerInterceptor interface in your spring
mvc application to pre-handle and post-handle web requests that are handled by Spring MVC controllers. These
handlers are mostly used to manipulate the model attributes returned/submitted they are passed to the
views/controllers.
A handler interceptor can be registered for particular URL mappings, so it only intercepts requests mapped to certain
URLs. Each handler interceptor must implement the HandlerInterceptor interface, which contains three callback
methods for you to implement: preHandle(), postHandle() and afterCompletion().

Problem with HandlerInterceptor interface is that your new class will have to implement all three methods
irrespective of whether it is needed or not. To avoid overriding, you can use HandlerInterceptorAdapter class.
This class implements HandlerInterceptor and provide default blank implementations.

Read More : Spring MVC Interceptor Example

How to handle exceptions in Spring MVC Framework?

In a Spring MVC application, you can register one or more exception resolver beans in the web application context
to resolve uncaught exceptions. These beans have to implement the HandlerExceptionResolver interface for
DispatcherServlet to auto-detect them. Spring MVC comes with a simple exception resolver for you to map each
category of exceptions to a view i.e. SimpleMappingExceptionResolver to map each category of exceptions to a
view in a configurable way.
Lets say we have an exception class i.e. AuthException. And we want that everytime this exception is thrown from
anywhere into application, we want to show a pre-determined view page /WEB-
INF/views/error/authExceptionView.jsp. So the configuration would be.

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

<property name="exceptionMappings">
<props>

<prop key="com.howtodoinjava.demo.exception.AuthException">
error/authExceptionView

</prop>
</props>

</property>
<property name="defaultErrorView" value="error/genericView"/>

</bean>

The defaultErrorView property can be configured to show a generic message for all other exceptions which are
not configured inside exceptionMappings list.
Read More : Spring MVC SimpleMappingExceptionResolver Example

175
How to achieve localization in Spring MVC applications?

Spring framework is shipped with LocaleResolver to support the internationalization and thus localization as well.
To make Spring MVC application supports the internationalization, you will need to register two beans.
1) SessionLocaleResolver : It resolves locales by inspecting a predefined attribute in a users session. If the session
attribute doesnt exist, this locale resolver determines the default locale from the accept-language HTTP header.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">

<property name="defaultLocale" value="en" />


</bean>

2) LocaleChangeInterceptor : This interceptor detects if a special parameter is present in the current HTTP
request. The parameter name can be customized with the paramName property of this interceptor. If such a
parameter is present in the current request, this interceptor changes the users locale according to the parameter
value.
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">

<property name="paramName" value="lang" />


</bean>

<!-- Enable the interceptor -->


<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">

<list>
<ref bean="localeChangeInterceptor" />

</list>
</property>

</bean>

Next step is to have each locale specific properties file having texts in that locale specific language e.g.
messages.properties and messages_zh_CN.properties etc.

Read More : Spring MVC Localization (i10n) Example

How to get ServletContext and ServletConfig object in a Spring Bean?

Simply implement ServletContextAware and ServletConfigAware interfaces and override below methods.
@Controller
@RequestMapping(value = "/magic")

176
public class SimpleController implements ServletContextAware, ServletConfigAware {

private ServletContext context;


private ServletConfig config;

@Override
public void setServletConfig(final ServletConfig servletConfig) {

this.config = servletConfig;

@Override
public void setServletContext(final ServletContext servletContext) {

this.context = servletContext;
}

//other code
}

How to use Tomcat JNDI DataSource in Spring Web Application?

For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration
file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database
operations.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/MySQLDB"/>
</bean>

How would you relate Spring MVC Framework to 3 tier architecture?

3-tier is a Architecture Style and MVC is a Design Pattern.

177
In larger applications MVC is the presentation tier only of an 3-tier architecture. The models views and
controllers are only concerned with the presentation, and make use of a middle tier to populate the models with data
from the data tier.

178

Potrebbero piacerti anche