Friday, March 6, 2015

XML JSON

XML:
xml wellformed and valid xml
A "Well Formed" XML document has correct XML syntax.
The syntax rules were described in the previous chapters:
    XML documents must have a root element
    XML elements must have a closing tag
    XML tags are case sensitive
    XML elements must be properly nested
    XML attribute values must be quoted
Dtd---consist of elements and attributes
What Is JSON?
JSON is a Java library that helps convert Java objects into a string representation. This string, when eval()ed in JavaScript, produces an array that contains all of the information that the Java object contained. JSON's object notation grammar is suitable for encoding many nested object structures. Since this grammar is much smaller than its XML counterpart, and given the convenience of the eval() function, it is an ideal choice for fast and efficient data transport between browser and server.
JSON is designed to be used in conjunction with JavaScript code making HTTP requests. Since server-side code can be written in a variety of languages, JSON is available in many different languages such as C#, Python, PHP, and of course, Java!     
JSON: The Fat-Free Alternative to XML
Extensible Markup Language (XML) is a text format derived from Standard Generalized Markup Language (SGML). Compared to SGML, XML is simple. HyperText Markup Language (HTML), by comparison, is even simpler. Even so, a good reference book on HTML is an inch thick. This is because the formatting and structuring of documents is a complicated business.
Most of the excitement around XML is around a new role as an interchangeable data serialization format. XML provides two enormous advantages as a data representation language:
It is text-based.
It is position-independent.
These together encouraged a higher level of application-independence than other data-interchange formats. The fact that XML was already a W3C standard meant that there wasn't much left to fight about (or so it seemed).
Unfortunately, XML is not well suited to data-interchange, much as a wrench is not well-suited to driving nails. It carries a lot of baggage, and it doesn't match the data model of most programming languages. When most programmers saw XML for the first time, they were shocked at how ugly and inefficient it was. It turns out that that first reaction was the correct one. There is another text notation that has all of the advantages of XML, but is much better suited to data-interchange. That notation is JavaScript Object Notation (JSON).
The most informed opinions on XML (see for example xmlsuck.org) suggest that XML has big problems as a data-interchange format, but the disadvantages are compensated for by the benefits of interoperability and openness.
JSON promises the same benefits of interoperability and openness, but without the disadvantages.Let's compare XML and JSON on the attributes that the XML community considers important.
From http://www.simonstl.com/articles/whyxml.htm
Simplicity
XML is simpler than SGML, but JSON is much simpler than XML. JSON has a much smaller grammar and maps more directly onto the data structures used in modern programming languages.
Extensibility
JSON is not extensible because it does not need to be. JSON is not a document markup language, so it is not necessary to define new tags or attributes to represent data in it.
Interoperability
JSON has the same interoperability potential as XML.
JSON is at least as open as XML, perhaps more so because it is not in the center of corporate/political standardization struggles.
From http://www.karto.ethz.ch/neumann/caving/cavexml/why_xml.html
In summary these are some of the advantages of XML.
XML is human readable
JSON is much easier for human to read than XML. It is easier to write, too. It is also easier for machines to read and write.
XML can be used as an exchange format to enable users to move their data between similar applications
The same is true for JSON.
XML provides a structure to data so that it is richer in information
The same is true for JSON.
XML is easily processed because the structure of the data is simple and standard
JSON is processed more easily because its structure is simpler.
There is a wide range of reusable software available to programmers to handle XML so they don't have to re-invent code
JSON, being a simpler notation, needs much less specialized software. In the languages JavaScript and Python, the JSON notation is built into the programming language; no additional software is needed at all. In other languages, only a small amount of JSON-specific code is necessary. For example, a package of three simple classes that makes JSON available to Java is available for free from JSON.org.
XML separates the presentation of data from the structure of that data.
XML requires translating the structure of the data into a document structure. This mapping can be complicated. JSON structures are based on arrays and records. That is what data is made of. XML structures are based on elements (which can be nested), attributes (which cannot), raw content text, entities, DTDs, and other meta structures.
A common exchange format
JSON is a better data exchange format. XML is a better document exchange format. Use the right tool for the right job.
Many views of the one data
JSON does not provide any display capabilities because it is not a document markup language.
XML and JSON have this in common.
Complete integration of all traditional databases and formats
(Statements about XML are sometimes given to a bit of hyperbole.) XML documents can contain any imaginable data type - from classical data like text and numbers, or multimedia objects such as sounds, to active formats like Java applets or ActiveX components.
JSON does not have a <[CDATA[]]> feature, so it is not well suited to act as a carrier of sounds or images or other large binary payloads. JSON is optimized for data. Besides, delivering executable programs in a data-interchange system could introduce dangerous security problems.
Internationalization
XML and JSON both use Unicode.
Open and extensible
XML’s one-of-a-kind open structure allows you to add other state-of-the-art elements when needed. This means that you can always adapt your system to embrace industry-specific vocabulary.
Those vocabularies can be automatically converted to JSON, making migration from XML to JSON very straightforward.
From http://www.xmlspy.com/manual/whyxml.htm
XML is easily readable by both humans and machines

JSON is easier to read for both humans and machines.
XML is object-oriented
Actually, XML is document-oriented. JSON is data-oriented. JSON can be mapped more easily to object-oriented systems.
XML is being widely adopted by the computer industry
JSON is just beginning to become known. Its simplicity and the ease of converting XML to JSON makes JSON ultimately more adoptable.
What really makes one data interchange format better than the other? As long as it serves the needs of the developers using it, then the format can at least be said to be adequate. The primary usage of JSON is for data delivery between browsers and servers. Even though it can technically be stored in files and the like, JSON is rarely used outside of the web environment. XML can also be used for data delivery between browsers and servers but also is stored in files and used to extract data from database. For this comparision, I’ll just consider the browser/server usage.
Syntax: JSON syntax is quite light and definitely less verbose than XML, with all of its start and end tags. When it comes down to pure byte-size, JSON can represent the same data as XML using fewer characters.
Weight: Since JSON syntax requires fewer characters, it is lighter on the wire than XML. The question is if this really matters. Any large data set is going to be large regardless of the data format you use. Add to that the fact that most servers gzip or otherwise compress content before sending it out, the difference between gzipped JSON and gzipped XML isn’t nearly as drastic as the difference between standard JSON and XML.
Browser Parsing: On the browser, there’s no such thing as a JSON parser. However, there is eval(), which interprets JavaScript code and returns the result. Since JSON syntax is a subset of JavaScript syntax, a JSON string can be evaluated using eval() and quickly turned into an object that is easy to work with and manipulate. XML parsing on the browser is spotty at best. Each browser implements some different way of dealing with XML and none of them are terribly efficient. In the end, the XML ends up as a DOM document that must be navigated to retrieve data. Native JavaScript objects are much easier to work with in JavaScript than DOM documents, although the playing field would level out considerably if every browser supported ECMAScript for XML (E4X), which makes working with XML data as easy as working with JavaScript objects.
Server Parsing: On the server, parsing is just about equal between JSON and XML. Most server-side frameworks have XML parsing capabilities and many now are starting to add JSON parsing capabilities as well. On the server, these parsers are essentially equal, parsing a text format into an object model. JSON holds no advantage over XML in this realm.
Querying: This is where XML really shines. Using XPath, it’s possible to get direct access to a part of multiple parts of an XML data structure; no such interface exists for JSON. To get data from a JSON structure, you must know exactly where it is or else iterate over everything until you find it.
Format Changes: So you have your data in one format but you want it in another. If the data is in XML, you can write an XSLT template and run it over the XML to output the data into another format: HTML, SVG, plain text, comma-delimited, even JSON. XSLT support in browsers is pretty good, even offering JavaScript-level access to it. XSLT support on the server is excellent. When you have data in JSON, it’s pretty much stuck there. There’s no easy way to change it into another data format. Of course it’s possible to walk the structure and do with it as you please, but the built-in support isn’t there as it is with XSLT for XML.
Security: Since the only way to parse JSON into JavaScript objects is to use eval(), it opens up a huge security hole. The eval() function will execute any arbitrary JavaScript code and so is dangerous to use in production systems. Invalid JSON that contains valid JavaScript code could execute and wreak havoc on an application. The solution, of course, is to build a true JSON parser for browsers, but we’re not there yet. On the other hand, XML data is completely safe. There is never a possibility that parsing XML data will result in code being executed.
With all of this considered, the two main advantages that JSON has over XML are 1) the speed and ease with which it’s parsed and 2) the ease of simple data retrieval from JavaScript object. Note that both of these advantages exist on the browser side of things; on the server-side they are essentially equal, unless you take querying and format changes into account, in which case XML is the clear winner. I don’t think that code size really is an advantage when you’re talking about gzipped data. I also believe that if ECMAScript for XML is implemented in all browsers, that JSON’s advantages go away.
DOM -Tree model parser(Object based) (Tree of nodes).
-DOM loads the file into the memory and then parse the file.
-Has memory constraints since it loads the whole XML file before parsing.
-DOM is read and write (can insert or delete the node).
-If the XML content is small then prefer DOM parser.
-Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.
-Slower at run time.
SAX
-Event based parser (Sequence of events).
-SAX parses the file at it reads i.e. Parses node by node.
-No memory constraints as it does not store the XML content in the memory.
-SAX is read only i.e. can’t insert or delete the node.
-Use SAX parser when memory content is large.
-SAX reads the XML file from top to bottom and backward navigation is not possible.
-Faster at run time.
WebService
JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).
Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.
Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.
JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange.
·         JAX-WS: addresses advanced QoS requirements commonly occurring in enterprise computing. When compared to JAX-RS, JAX-WS makes it easier to support the WS-* set of protocols, which provide standards for security and reliability, among other things, and interoperate with other WS-* conforming clients and servers.

·         JAX-RS: makes it easier to write web applications that apply some or all of the constraints of the REST style to induce desirable properties in the application, such as loose coupling (evolving the server is easier without breaking existing clients), scalability (start small and grow), and architectural simplicity (use off-the-shelf components, such as proxies or HTTP routers). You would choose to use JAX-RS for your web application because it is easier for many types of clients to consume RESTful web services while enabling the server side to evolve and scale. Clients can choose to consume some or all aspects of the service and mash it up with other web-based services.

Struts & IBatis

Struts:
What is Struts?
                The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.
What is Jakarta Struts Framework?
                Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
What is ActionServlet?
                The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.
How you will make available any Message Resources Definitions file to the Struts Framework Environment?
                T Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag.
.
What is Action Class?
                The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
 What is ActionForm?
                An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
What is Struts Validator Framework?
                Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.
Give the Details of XML files used in Validator Framework?
                The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.
Struts1 vs Struts 2
Struts1:
Needs ActionForm
No interceptor
Html tags
Needs req and response
Struts2:
Not need form class
Has interceptor
OGNL tags
No need of req and response
Types of Action classes in struts
1.ForwardAction class
2.DispatchAction class
3.IncludeAction class
4.LookUpDispatchAction class
5.MappingDispatchAction class
6.SwitchAction class
7.LocaleDispatchAction class
8.DownloadAction class
IBatis:
What is iBatis ?
A JDBC Framework
Developers write SQL, iBATIS executes it using JDBC.
No more try/catch/finally/try/catch.
An SQL Mapper
Automatically maps object properties to prepared statement parameters.
Automatically maps result sets to objects.
Support for getting rid of N+1 queries.
A Transaction Manager
iBATIS will provide transaction management for database operations if no other transaction manager is available.
iBATIS will use external transaction management (Spring, EJB CMT, etc.) if available.
Great integration with Spring, but can also be used without Spring (the Spring folks were early supporters of iBATIS).
What isn't iBATIS ?
An ORM
Does not generate SQL
Does not have a proprietary query language
Does not know about object identity
Does not transparently persist objects
Does not build an object cache
Essentially, iBatis is a very lightweight persistence solution that gives you most of the semantics of an O/R Mapping toolkit, without all the drama. In other words ,iBATIS strives to ease the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.
Configuring the Environment:
Let see how to configure the iBatis-Spring environment. When working with Spring and iBATIS, you will have a minimum of three XML configuration files, and you will often have even more. It is important that you become familiar with these config files. So how do you make iBATIS available to your application? There are a couple of ways:
Using Spring - iBATIS with a stand-alone application:
You should place the ibatis-2.3.0.677.jar in the application's classpath. At minimum, you must define and place the following three configuration files in the classpath
Spring config - This file defines the database connection parameters, the location of the SQL Map config file, and one or more Spring beans for use within the application. ( applicationContext.xml).
SQL Map config - This file defines any iBATIS-specific configuration settings that you may need and declares the location for any SQL Map files that should be accessible through this config file. (SqlMapConfig.xml)
SQL Map(s) One or more SQL Map files are declared in the SQL Map config and typically mapped to a single business entity within the application ,often represented by a single Java class (domainObject.xml).
Assuming you have no other knowledge of the data and have to use a generic sort method, the best theoretical in-place sort algorithm is O(n*log(n)). The Arrays.sort method should be using one of those, and is your best choice without more info.
If you're willing to use a lot of memory, you can use a non-in place sort such as radix or counting. These can be quicker than n*log(n), some as quick as O(n), but may use O(n) or worse memory. If you have knowledge of the data having special properties (such as it being almost already sorted) an insertion sort or similar algorithms could be quicker than O(n*log(n)) without using memory, but without more info one of those can't be suggested.


JSP Servlet

Servlet:
Explain the life cycle methods of a Servlet.
                 The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
                 The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
Explain the directory structure of a web application.
                 The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.
WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory
What are the common mechanisms used for session tracking?
                 Cookies
SSL sessions
URL- rewriting
Explain ServletContext.
                 ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
What is preinitialization of a servlet?
                 A container doesn't initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
What is the difference between Difference between doGet() and doPost()?
                 A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
What is the difference between HttpServlet and GenericServlet?

                 A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.
What is the difference between ServletContext and ServletConfig?
 ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.
What is a output comment?
                A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
Example 1
Displays in the page source:
What is a Hidden Comment?
                A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
A Hidden Comment
<%-- This comment will not be visible to the colent in the page source --%>
What is a Expression?
                An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
What is a Declaration?
                A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>
What is a Scriptlet?
                A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
What are implicit objects? List them?
                Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
request
response
pageContext
session
application
out
config
page
exception
Difference between forward and sendRedirect?
                When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
                 You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
How does JSP handle run-time exceptions?
                 You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
                You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .
How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
<%-- scriptlets calling bean setter methods go here --%>
How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
then use it inside your JSP form, like
What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
                Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.
How can I enable session tracking for JSP pages if the browser has disabled cookies?

                We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>

hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
                 Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.
Is there a way to execute a JSP from the comandline or from my own application?
There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber & Peter Rossbach ) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website.
How you will display validation fail errors on jsp page?
                Following tag displays all the errors:
How you will enable front-end validation based on the xml in validation.xml?
                The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form \"logonForm\" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.
How to get data from the velocity page in a action class?
                We can get the values in the action classes by using data.getParameter(\"variable name defined
200-299
Success – The action was successfully received, understood, and accepted.
300-399
Redirection – Further action must be taken in order to complete the request.
400-499
Client Error – The request contains bad syntax or cannot be fulfilled.
500-599
Server Error – The server failed to fulfill an apparently valid request.
200
OK— The request has succeeded.
302
Moved Temporarily — The request resides temporarily under a different URI. If the new URI is a location, the location header field in
the response will give the new URL. This is typically used when the client is being redirected.
400
Bad Request— The server couldn’t understand the request due to malformed syntax.
401
Unauthorized— The request requires authentication and/or authorization.
403
Forbidden— The server understood the request, but for some reason is refusing to fulfill it. The server may or may not reveal why it has refused the request.
404
Not Found— The server has not found anything matching the request  URI.
500
Internal Server Error— The server encountered an unexpected condition  which prevented it from fulfilling the request.
Why mvc:
Layer separation, scalability, security, reusability
MVC1 vs MVC2
MVC1:JSP interacts model directly without controller
MVC2:JSP requests pass to controller and contoller interacts model
Connection pooling
It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database
RiskControlAnalysis(RCA)
Baseline
|
Production
|
Testing
|
if Faullt  then goes to production
|
Analyse the problem with senior
|
Action Team meeting
|
Find solution and prevents in future
Defect Prevention
Load Testing using jmeter
Session
URLRewriting, Cookies,
Session obj creation:
HttpSession obj=request.getSession();
Why session----associate with objects in whole appln.transer data from 1 page to other page or servlet
Web server vs app server
Web server:
Handles http req and resp with html pages
App server:
Connection pooling, multithreading, transaction mgmt
Version Control
Cvs, svn, git
Mercurial,  IBM Clearcase, IBM Clearquest.
Load on startup
May have negative - if negative servlet container load at any time where it needs
if positive from 0 to 128 then it loads from lower order to higher integers
ServletFilters
Servlet Filters are the latest components that are added in Servlet 2.3 specifications. These filters are used basically for intercepting and modifying requests and response from server.  Consider a scenario where you want to check session from the every users request and if it is valid then only you want to let the user access the page. You can acheive this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter.
package net.viralpatel.servlet.filters;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class LogFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        //Get the IP address of client machine.
        String ipAddress = request.getRemoteAddr();
        //Log the IP address and current timestamp.
        System.out.println("IP "+ipAddress + ", Time "
                           + new Date().toString());
        chain.doFilter(req, res);
    }
    public void init(FilterConfig config) throws ServletException {
        //Get init parameter
        String testParam = config.getInitParameter("test-param");
        //Print the init parameter
        System.out.println("Test Param: " + testParam);
    }
    public void destroy() {
        //add code to release any resource
    }
}
In this filter example, we have implemented an interface javax.servlet.Filter and override its methods init, doFilter and destroy.
The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor).
The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc.
The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications.
Step 4: Create Servlet Filter Mapping in Web.xml
Open web.xml file from WEB-INF directory of your Project and add following entry for filter tag.
    LogFilter
   
        net.viralpatel.servlet.filters.LogFilter
   
   
        test-param
        This parameter is for testing.
   
    LogFilter
    /*
In this entry, we have added LogFilter class in Web xml and mapped it with URL /*. Hence any request from client will generated a call to this filter. Also we have passed a parameter test-param. This is just to show how to pass and retrieve a parameter in servlet filter.

Spring J2EE

Spring:
1.  What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.
2. What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection
3. What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
4.  What is Spring ?
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.
5. What are the advantages of Spring framework?
The advantages of Spring are as follows:
Spring has layered architecture. Use what you need and leave you don't need now.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
6. What are features of Spring ?
Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS
7. How many modules are there in Spring? What are they?
       Spring comprises of seven modules. They are..
The core container:
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
Spring context:
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
Spring AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
Spring ORM:
The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
Spring MVC framework:
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
8. What are the types of Dependency Injection Spring supports?
Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.

BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
10. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
A means for resolving text messages, including support for internationalization.
A generic way to load file resources.
Events to beans that are registered as listeners.
11. What is the difference between Bean Factory and Application Context ? 
On the surface, an application context is same as a bean factory. But application context offers much more..
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
What are the Core container module and Application context module?
Core Container Module: This module is the fundamental module of spring framework. For a spring-based application, BeanFactory is the core. The Spring framework was developed on top of this module.
What is a BeanFactory and XMLBeanFactory?
BeanFactory: Bean factory is a container. It configures, instantiates and manages a set of beans. These beans are collaborated with one another and have dependencies among themselves.
What is AOP Alliance?
AOP Alliance: AOP Alliance is an open source project. Promoting adoption of AOP and interoperability among different AOP implementations with the help of interfaces.
Explain the concepts and purpose of Spring configuration file.
 A spring configuration file is an XML file which contains the information about classes and describes the process of configuration.
What does a simple spring application contain?
 A spring application is like any other Java application. The applications contain classes, each of them perform a specific task with the application. All these classes are.
Explain Bean lifecycle in Spring framework.
 The bean’s 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.
What is bean wiring?
 Bean wiring is the process of combining beans with Spring container. The required beans are to be informed to the container.
Explain how to add a bean in spring application.
 The id attribute of the bean tag specifies the name of the bean and the fully qualified class name is specified by the class attribute.
What are singleton beans and how can you create prototype beans?
 All beans defined in the spring framework are singleton beans. The bean tag has an attribute by name ‘singleton’.
What are Inner Beans?
 A bean inside another bean is known as Inner Bean. They are created and used on the fly, and can not be used outside the enclosing beans.
What is Auto wiring? What are different types of Autowire types?
 Searching for objects with the same name of object property is called auto wiring in Spring. By default, Spring framework enables the auto wiring.
What is meant by Weaving? What are the different points where weaving can be applied?
 The process of applying aspects to a target object for creating a new proxy object is referred to as weaving. These aspects are woven at the following specified join points.
Explain the different types of AutoProxying.
 BeanNameAutoProxyCreator: This proxy is used to identify beans to proxy through a list of names. It checks the matches that are direct, “xxx” and “*xxx”.
What is DataAccessException?
 DataAccessException is an unchecked RuntimeException. These type of exceptions are unforced by users to handle.
Explain about PreparedStatementCreator.
 To write data to database, PreparedStatementCreator is the most commonly used interface. The interface contains one method by name createPreparedStatement().
Explain about BatchPreparedStatementSetter.
 Updating more than one row at a time, the BatchPreparedStatementSetter is used. This interface has setValues() and getBatchSize() exceptions.
Explain about RowCallbackHandler and why it is used.
 ResultSet is generally used to navigate the records. The spring framework is provided with RowCallbackHandler interface.
Spring beanfactory : Heart of spring core
Bean autowiring: Collection of bean
Spring mvc:
ModelAndView(hello,"msgName",new String("hihello"))
web.xml---servlet class--->SpringDispatcher
Servlet name---spring
spring xml name====  spring-servlet.xml
Reqeust=/save
Spring life cycle:
init
Destroy
Spring Flow:
1.HttpRequest à Handler Mapping i.e web.xml
Org.springframework.DispatcherServlet
2.àWeb_app_name-servlet.xml
Bean namespace
3.View
/WEB-INF/pages/*.jsp
.jsp
4.View
@Controller
Class SpringController{
@RequestMapping(value=/listurl)
Public String method(ModelMap model){
Model.addAttribute(“hello”,”message to be displayed”);
Return “listurl”;
}
MVC Annotation Driven:
RequestMapping, Controller, RequestBody, ResponseBody etc.,
Context Annotation Driven:
Configured for Autowired, Required etc.,
@PathVariable(“url/{variable}”) – Query Params in the browser url.
@Autowired
byName, byType, byMethod
Autowired can be set to field, constructor
@Autowired(required=false)
private ObjectType objectType;
@Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.
@Autowired and @Inject
1.     Matches by Type
2.     Restricts by Qualifiers
3.     Matches by Name
@Resource
1.     Matches by Name
2.     Matches by Type
3.     Restricts by Qualifiers (ignored if match is found by name)
@Required
Can be set true or false while bean configuration
If @Required is not then it will give Bean Initialization Exception

Ex: @Autowired(required = false | true)

Spring-DAO
Spring-DAO is not stricto senso a spring module, but rather conventions that should dictate you to write DAO, and to write them well. As such, it does neither provide interfaces nor implementations nor templates to access your data. When writing a DAO, you should annotate them with @Repository so that exceptions linked to the underlying technology (JDBC, Hibernate, JPA, etc.) are consistently translated into the proper DataAccessException subclass.
As an example, suppose you're now using Hibernate, and your service layer catches HibernateException in order to react to it. If you change to JPA, your DAOs interfaces should not change, and the service layer will still compile with blocks that catches HibernateException, but you will never enter these blocks as your DAOs are now throwing JPA PersistenceException. By using @Repository on your DAO, the exceptions linked to the underlying technology are translated to Spring DataAccessException; your service layer catches these exceptions and if you decide to change the persistence technology, the same Spring DataAccessExceptions will still be thrown as spring have translated native exceptions.
Note however that this has limited usage for the following reasons:
  1. Your should usually not catch persistence exceptions, as the provider may have rolled back the transaction (depending on the exact exception subtype), and thus you should not continue the execution with an alternative path.
  2. The hierarchy of exceptions is usually richer in your provider than what Spring provides, and there's no definitive mapping from one provider to the other. Relying on this is hazardous. This is however a good idea to annotate your DAOs with @Repository, as the beans will be automatically added by the scan procedure. Further, Spring may add other useful features to the annotation.
Spring-JDBC
Spring-JDBC provides the JdbcTemplate class, that removes plumbing code and helps you concentrate on the SQL query and parameters. You just need to configure it with a DataSource, and you can then write code like this:
int nbRows = jdbcTemplate.queryForObject("select count(1) from person", Integer.class);

Person p = jdbcTemplate.queryForObject("select first, last from person where id=?", 
             rs -> new Person(rs.getString(1), rs.getString(2)), 
             134561351656L);
Spring-JDBC also provides a JdbcDaoSupport, that you can extend to develop your DAO. It basically defines 2 properties: a DataSource and a JdbcTemplate that both can be used to implement the DAO methods. It also provides an exceptions translator from SQL exceptions to spring DataAccessExceptions.
If you plan to use plain jdbc, this is the module you will need to use.
Spring-ORM
Spring-ORM is an umbrella module that covers many persistence technologies, namely JPA, JDO, Hibernate and iBatis. For each of these technologies, Spring provides integration classes so that each technology can be used following Spring principles of configuration, and smoothly integrates with Spring transaction management.
For each technology, the configuration basically consists in injecting a DataSource bean into some kind of SessionFactory or EntityManagerFactory etc. bean. For pure JDBC, there's no need for such integration classes (apart from JdbcTemplate), as JDBC only relies on a DataSource.
If you plan to use an ORM like JPA or Hibernate, you will not need spring-jdbc, but only this module.
Spring-Data
Spring-Data is an umbrella project that provides a common API to define how to access data (DAO + annotations) in a more generic way, covering both SQL and NOSQL data sources.
The initial idea is to provide a technology so that the developer writes the interface for a DAO (finder methods) and the entity classes in a technology-agnostic way and, based on configuration only (annotations on DAOs & entities + spring configuration, be it xml- or java-based), decides the implementation technology, be it JPA (SQL) or redis, hadoop, etc. (NOSQL).
If you follow the naming conventions defined by spring for the finder method names, you don't even need to provide the query strings corresponding to finder methods for the most simple cases. For other situations, you have to provide the query string inside annotations on the finder methods.
When the application context is loaded, spring provides proxies for the DAO interfaces, that contain all the boilerplate code related to the data access technology, and invokes the configured queries.
Spring-Data concentrates on non-SQL technologies, but still provides a module for JPA (the only SQL technology).
What's next
Knowing all this, you have now to decide what to pick. The good news here is that you don't need to make a definitive final choice for the technology. This is actually where Spring power resides : as a developer, you concentrate on the business when you write code, and if you do it well, changing the underlying technology is an implementation or configuration detail.
  1. Define a data model with POJO classes for the entities, and get/set methods to represent the entity attributes and the relationships to other entities. You will certainly need to annotate the entity classes and fields based on the technology, but for now, POJOs are enough to start with. Just concentrate on the business requirements for now.
  2. Define interfaces for your DAOs. 1 DAO covers exactly 1 entity, but you will certainly not need a DAO for each of them, as you should be able to load additional entities by navigating the relationships. Define the finder methods following strict naming conventions.
  3. Based on this, someone else can start working on the services layer, with mocks for your DAOs.
  4. You learn the different persistence technologies (sql, no-sql) to find the best fit for your needs, and choose one of them. Based on this, you annotate the entities and implement the DAOs (or let spring implement them for you if you choose to use spring-data).
  5. If the business requirements evolve and your data access technology is not sufficient to support it (say, you started with JDBC and a few entities, but now need a richer data model and JPA is a better choice), you will have to change the implementation of your DAOs, add a few annotations on your entities and change the spring configuration (add an EntityManagerFactory definition). The rest of your business code should not see other impacts from your change.
Note : Transaction Management
Spring provides an API for transaction management. If you plan to use spring for the data access, you should also use spring for transaction management, as they integrate together really well. For each data access technology supported by spring, there is a matching transaction manager for local transactions, or you can choose JTA if you need distributed transactions. All of them implement the same API, so that (once again) the technology choice is just a matter a configuration that can be changed without further impact on the business code.
  • The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.
  • The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications.
Difference between spring modules 

pring-DAO
Spring-DAO is not stricto senso a spring module, but rather conventions that should dictate you to write DAO, and to write them well. As such, it does neither provide interfaces nor implementations nor templates to access your data. When writing a DAO, you should annotate them with @Repository so that exceptions linked to the underlying technology (JDBC, Hibernate, JPA, etc.) are consistently translated into the proper DataAccessException subclass.
As an example, suppose you're now using Hibernate, and your service layer catches HibernateException in order to react to it. If you change to JPA, your DAOs interfaces should not change, and the service layer will still compile with blocks that catches HibernateException, but you will never enter these blocks as your DAOs are now throwing JPA PersistenceException. By using @Repository on your DAO, the exceptions linked to the underlying technology are translated to Spring DataAccessException; your service layer catches these exceptions and if you decide to change the persistence technology, the same Spring DataAccessExceptions will still be thrown as spring have translated native exceptions.
Note however that this has limited usage for the following reasons:
  1. Your should usually not catch persistence exceptions, as the provider may have rolled back the transaction (depending on the exact exception subtype), and thus you should not continue the execution with an alternative path.
  2. The hierarchy of exceptions is usually richer in your provider than what Spring provides, and there's no definitive mapping from one provider to the other. Relying on this is hazardous. This is however a good idea to annotate your DAOs with @Repository, as the beans will be automatically added by the scan procedure. Further, Spring may add other useful features to the annotation.
Spring-JDBC
Spring-JDBC provides the JdbcTemplate class, that removes plumbing code and helps you concentrate on the SQL query and parameters. You just need to configure it with a DataSource, and you can then write code like this:
int nbRows = jdbcTemplate.queryForObject("select count(1) from person", Integer.class);

Person p = jdbcTemplate.queryForObject("select first, last from person where id=?", 
             rs -> new Person(rs.getString(1), rs.getString(2)), 
             134561351656L);
Spring-JDBC also provides a JdbcDaoSupport, that you can extend to develop your DAO. It basically defines 2 properties: a DataSource and a JdbcTemplate that both can be used to implement the DAO methods. It also provides an exceptions translator from SQL exceptions to spring DataAccessExceptions.
If you plan to use plain jdbc, this is the module you will need to use.
Spring-ORM
Spring-ORM is an umbrella module that covers many persistence technologies, namely JPA, JDO, Hibernate and iBatis. For each of these technologies, Spring provides integration classes so that each technology can be used following Spring principles of configuration, and smoothly integrates with Spring transaction management.
For each technology, the configuration basically consists in injecting a DataSource bean into some kind of SessionFactory or EntityManagerFactory etc. bean. For pure JDBC, there's no need for such integration classes (apart from JdbcTemplate), as JDBC only relies on a DataSource.
If you plan to use an ORM like JPA or Hibernate, you will not need spring-jdbc, but only this module.
Spring-Data
Spring-Data is an umbrella project that provides a common API to define how to access data (DAO + annotations) in a more generic way, covering both SQL and NOSQL data sources.
The initial idea is to provide a technology so that the developer writes the interface for a DAO (finder methods) and the entity classes in a technology-agnostic way and, based on configuration only (annotations on DAOs & entities + spring configuration, be it xml- or java-based), decides the implementation technology, be it JPA (SQL) or redis, hadoop, etc. (NOSQL).
If you follow the naming conventions defined by spring for the finder method names, you don't even need to provide the query strings corresponding to finder methods for the most simple cases. For other situations, you have to provide the query string inside annotations on the finder methods.
When the application context is loaded, spring provides proxies for the DAO interfaces, that contain all the boilerplate code related to the data access technology, and invokes the configured queries.
Spring-Data concentrates on non-SQL technologies, but still provides a module for JPA (the only SQL technology).
What's next
Knowing all this, you have now to decide what to pick. The good news here is that you don't need to make a definitive final choice for the technology. This is actually where Spring power resides : as a developer, you concentrate on the business when you write code, and if you do it well, changing the underlying technology is an implementation or configuration detail.
  1. Define a data model with POJO classes for the entities, and get/set methods to represent the entity attributes and the relationships to other entities. You will certainly need to annotate the entity classes and fields based on the technology, but for now, POJOs are enough to start with. Just concentrate on the business requirements for now.
  2. Define interfaces for your DAOs. 1 DAO covers exactly 1 entity, but you will certainly not need a DAO for each of them, as you should be able to load additional entities by navigating the relationships. Define the finder methods following strict naming conventions.
  3. Based on this, someone else can start working on the services layer, with mocks for your DAOs.
  4. You learn the different persistence technologies (sql, no-sql) to find the best fit for your needs, and choose one of them. Based on this, you annotate the entities and implement the DAOs (or let spring implement them for you if you choose to use spring-data).
  5. If the business requirements evolve and your data access technology is not sufficient to support it (say, you started with JDBC and a few entities, but now need a richer data model and JPA is a better choice), you will have to change the implementation of your DAOs, add a few annotations on your entities and change the spring configuration (add an EntityManagerFactory definition). The rest of your business code should not see other impacts from your change.
Note : Transaction Management
Spring provides an API for transaction management. If you plan to use spring for the data access, you should also use spring for transaction management, as they integrate together really well. For each data access technology supported by spring, there is a matching transaction manager for local transactions, or you can choose JTA if you need distributed transactions. All of them implement the same API, so that (once again) the technology choice is just a matter a configuration that can be changed without further impact on the business code.

SpringBatch

Spring batch Overview:
    Job
   JobLauncher
   JobParameters
   joblauncher.run(job,params)

JobLauncher
JobRepository

Itemreader
It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemReader.

Itemwriter

It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemWriter.

Itemprocessor

It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemProcessor.

commit-interval

It is used to specify the number of items to be processed before committing the transaction.


    
       
         
            processor = "itemProcessor" commit-interval = "10"> 
         
      
    


MongoItemReader To read data from MongoDB.
FlatFIleItemReader To read data from flat files.
JDBCPagingItemReader To read data from relational databases database.

MongoItemWriter To write data into MongoDB.

To run the application, we need to use @SpringBootApplication annotation. Behind the scenes, that’s equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan together.

@Transactional(readOnly=trye) used in Spring-Data
@Reposoitory- used to handle unchecked SQL Exception called DataAccessException

Spring ResponseBody:
---------------------
if you put @ResponseBody annotation in the method level, Spring will convert the return object in to the http response body.

ResponseEntity
---------------
ResponseEntity works similar as @ResponseBody annotation. But when you create ResponseEntity object, you can add the response header to the http response as well.

Spring Life cycle

Initializing Bean

Disposable Bean