Monday, 17 November 2014

Spring Introduction

Spring is open source framework, created by Rod Johnson. Prior to Spring a lot of framework came in market but they were not modularize, light weighted, broader, loose coupled and developers need to put a lot of effort to include any layer, whether it is Database layer or any other. So, the idea is to create spring resolve all the above issue. I will discuss all of them in later in this chapter.

Spring does many things, but when you strip it down to its base parts, Spring is a lightweight dependency injection and aspect-oriented container and framework.

Spring feature are given below-
  • Lightweight—Spring is lightweight in terms of both size and overhead. The bulk of the Spring Framework can be distributed in a single JAR file that weighs in at just over 2.5 MB. And the processing overhead required by Spring is negligible.
  • Dependency Injection—Spring supports loose coupling through a technique known as dependency injection (DI). When DI is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of DI as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.
  • Aspect-oriented—Spring support aspect-oriented programming (AOP) that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for other system concerns, such as logging or transactional support.
  • Container—Spring is a container in the sense that it contains and manages the lifecycle and configuration of application objects. In Spring, you can declare how each of your application objects should be created, how they should be configured, and how they should be associated with each other.
  • Framework—Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.

Wednesday, 12 November 2014

web.xml servlet configuration

In this chapter I will explain about deploy descriptor file (web.xml), as I mention in previous chapter that deployment descriptor file is per application and contain the configuration information of servlet, and servlet container read this file and behave accordingly. web.xml file present inside WEB-INF folder.

Root element/tag of web.xml file is web-app. It denote one web application,where all the web related configuration present. See below to understand-

  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaeexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0" metadata-complete="true">
  3.  ..............................
  4. .....................................
  5. </web-app>

Inside web-app normally we declare the servlet configuration. Below the <servlet> element declares the HelloServlet, the examples.Hello Java class implements the servlet, and the <servlet-mapping> element specifies the /hello URL pattern that invokes the servlet in a browser. This URL pattern is used in the index.html file.



    <display-name>HelloWorld Application</display-name>
    <description>
        This is a simple web application
    </description>

    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>examples.Hello</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


Sometime we need to pass some parameter to servlet so in this case 
we can use <init-param> element. see below servlet- 



<servlet>
        <servlet-name>Servlet</servlet-name>
         <servlet-class>mysite.server.TeamServlet</servlet-class> 
          <init-param>            
              <param-name>bgColor</param-name>              
              <param-value>#CC0000</param-value>         
          </init-param>  
 </servlet>


 If user wants to show some page when user try to hit simply domain name rather than full qualified path of resource then in this case we can open by default page i.e. welcome file list- and from welcome file user can navigate to other page

<welcome-file-list> 
    <welcome-file>index</welcome-file> 
</welcome-file-list>
 
If we are using filters in our application (filter already described in previous chapter). so in this case-
filter tag is required see below-


<filter>
        <filter-name>logSpecial</filter-name>
        <filter-class>mysite.server.LogFilterImpl</filter-class>
        <init-param>
            <param-name>logType</param-name>
            <param-value>special</param-value>
        </init-param>
</filter>      
 
<filter-mapping>
        <filter-name>logSpecial</filter-name>
        <url-pattern>*.special</url-pattern>
</filter-mapping> 
 
 
 If user want to handle error then error tag is required. see below -

<error-page>
        <error-code>500</error-code>
        <location>/errors/servererror.jsp</location>
</error-page>
 
If user want to pass application related parameter then context-param 
can be used.This should be used outside of servlet. see below-
 

<context-param>  
       <param-name>bgColor</param-name> 
        <param-value>#CC0000</param-value>  
</context-param>
 

If we are using listener in the application then we need to register this first by using listener tag. see below-

<listener>
    <listener-class>com.rkclass.listener.MyContextListener</listener-class>
</listener>

Some more tags is there but I will explain them in advance chapter.

Thanks !!!

Sunday, 2 November 2014

RequestDispatcher

As the name suggest of "RequestDispatcher" means dispatching request. Dispatching request means dispatching request from one servelet to another servlet. This means suppose if you want call another servlet within servlet then you have to dispatch the request to other servlet so, in this case you have to use RequestDispatcher.

RequestDispatcher is a interface and defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.


Method summery of this interface-
void forward(ServletRequest request, ServletResponse response)
          Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
 void include(ServletRequest request, ServletResponse response)
          Includes the content of a resource (servlet, JSP page, HTML file) in the response.

To understand methods see below diagram-


Get the RequestDispatcher Object-

For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or ServletContext.getRequestDispatcher() method.
They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp.

Suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:

   RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");
   dispatcher.forward( request, response );

where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by

  RequestDispatcher dispatcher=
           getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );
  dispatcher.forward( request, response );

Once you get the RequestDispatcher object, you can either forward to the resource or include the resource.

Example-
If user login process is getting success then navigate to home page-
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.   
  4.     response.setContentType("text/html");  
  5.     PrintWriter out = response.getWriter();  
  6.           
  7.     String userName=request.getParameter("userName");  
  8.     String password=request.getParameter("userPass");  
  9.           
  10.     if(authenticateUser(userName, password)){  
  11.         RequestDispatcher rd=request.getRequestDispatcher("homeServlet");  
  12.         rd.forward(request, response);  
  13.     }  
  14.     else{  
  15.         out.print("Sorry User doesn't exist");  
  16.         RequestDispatcher rd=request.getRequestDispatcher("/index.html");  
  17.         rd.include(request, response);  
  18.                       
  19.         }  
  20.     } 

Thanks!!!!