Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Friday, January 29, 2016

Spring

Spring


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.
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

    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.
      What are ORM’s Spring supports ? 
      Spring supports the following ORM’s :
      • iBatis
      • Hibernate
      • JPA (Java Persistence API)
      • TopLink
      • JDO (Java Data Objects)
      • OJB
      What are the ways to access Hibernate using Spring ?
      There are two approaches to Spring’s Hibernate integration:
      • Inversion of Control with a HibernateTemplate and Callback
      • Extending HibernateDaoSupport and Applying an AOP Interceptor
      How to integrate Spring and Hibernate using HibernateDaoSupport?
      Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
      Configure the Hibernate SessionFactory
      Extend your DAO Implementation from HibernateDaoSupport
      Wire in Transaction Support with AOP
      What are the types of the transaction management Spring supports ?
      Spring Framework supports:
      Programmatic transaction management.
      Declarative transaction management.
      What are the benefits of the Spring Framework transaction management ?
      The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
      Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
      Supports declarative transaction management.
      Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
      Integrates very well with Spring’s various data access abstractions.
      Why most users of the Spring Framework choose declarative transaction management ?
      Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.
      When to use programmatic and declarative transaction management ?
      Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.
      On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
    Click here for more Hadoop Interview Questions

Java Script frameworks and Dev tools

Java Script frameworks and Dev tools


jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Ref :http://jquery.com/
Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.
Ref:http://www.prototypejs.org/
Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.
Ref: http://getfirebug.com/
Click here for more J2EE Interview Questions

JSON

JSON


JSON: JavaScript Object Notation.
JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.

JSON Example

{
“employees”: [
{ “firstName”:”John” , “lastName”:”Doe” },
{ “firstName”:”Anna” , “lastName”:”Smith” },
{ “firstName”:”Peter” , “lastName”:”Jones” }
]
}
The employees object is an array of 3 employee records (objects).

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is language independent
  • JSON is “self-describing” and easy to understand
JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

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
  • eval() the JSON string
Click here for more J2EE Interviw Questions

SAX Vs DOM parsers

Difference between SAX and DOM parsers?
SAX Parser:
  • A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
  • A SAX parser serves the client application always only with pieces of the document at any given time.
  • A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.
  • Parses node by node
  • Does not store the XML in memory
  • We can not insert or delete a node
  • Top to bottom traversing
  • SAX Parser is faster and uses less memory than DOM parser.
DOM Parser:
  • A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
  • A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
  • A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.
  •  Stores the entire XML document into memory before processing
  • Occupies more memory
  • We can insert or delete nodes
  • Traverse in any direction.

Java Servlet

Java Servlet


What Is a Servlet?
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
What is life cycle of a servlet?
Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). The init() and destroy() methods are called only once in the lifecycle of a servlet.
What is Servlet interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.
Servlet
Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.
What is the difference between doGet() and doPost()?
#
doGet()doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won’t show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.You can send much more information to the server this way – and it’s not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encryptedParameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performancedoPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many timesThis method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsibleThis method does not need to be either safe
8
It allows bookmarks.It disallows bookmarks.
When to use doGet() and when doPost()?
Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
If data is sensitive
Data is greater than 1024 characters
If your application don’t need bookmarks.
How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:
1
2
3
4
5
6
public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
                  throws ServletException, IOException
    {
        this.doGet(servletRequest,servletResponse);
 
    } //end of doPost() method
What is the directory structure of a WAR file?
What is the load-on-startup element?
The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The element is written in the deployment descriptor as follows:
1
2
3
ServletName
ClassName
1
Note: The container loads the servlets in the order specified in the element.
How can an existing session be invalidated?
An existing session can be invalidated in the following two ways:
1. Setting timeout in the deployment descriptor: This can be done by specifying timeout between the tags as follows:
1
 
This will set the time for session timeout to be 10 minutes.
2. Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
1
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.
How are filters?
Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
  • Security checks
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.
What is difference between Servlets and JSP?
The difference between Servlets and JSP is that Servlets typically Java code embed HTML inside that, while JSPs are HTML embed Java code in it.
What mechanisms are used by a Servlet Container to maintain session information?Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.
What is session? 
The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests.
Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
What are the types of Session Tracking ?
Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
    • URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.
    • Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.
    • Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie’s value can uniquely identify a client.
    • Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL’s support via HTTPS for generating a unique session key as part of the encrypted conversation.
In web.xml file, <load-on-startup>1</load-on-startup> is defined between<servlet></servlet> tag. what does it means?
Ans: whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this 1is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request.When this servlet question was asked to me in an interview few years back , I was not even aware of this element but this questions pointed me to look DTD of web.xml and understand other elements as well..
what is servlet collaboration?
Ans:  communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method.
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods
How many instances will be created for a servlet in servlet container? 
Ans: Only one instance will be created for every servlet. Generally servlet instantiation is done by the container. But based on the number of requests coming to the servlet that many no.of threads are created. Each thread will serve one request.
Servlet Filters:
The Servlet filters are basically used 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 achieve this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter.
Filters have a wide array of uses; the Servlet 2.3 specification suggests the following uses:
authentication filters
logging and auditing filters
image conversion filters
data compression filters
encryption filters
tokenizing filters
filters that trigger resource access events
XSL/T filters that transform XML content
MIME-type chain filters
A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).
Writing a simple filter
To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we’ll ignore these and focus on doFilter(), which is important.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 SimpleFilter 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 {
        //add code to initialize any thing which is used by Filter.
    }
    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.
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<filter>
    <filter-name>SimpleFilter </filter-name>
    <filter-class>
        net.viralpatel.servlet.filters.SimpleFilter
    </filter-class>
    <init-param>
        <param-name>test-param</param-name>
        <param-value>This parameter is for testing.</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SimpleFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
In this entry, we have added SimpleFilter 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.