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

Friday, 31 October 2014

Servlet Error Handling

Servlet application will not be perfect until it works on all negative or positive scenario.So, Error handling is also required during servlet programming. In this chapter I will explain about how to handle servlet errors.

Whenever servlet will throw any error by any reason whether it is because of resource not found or authentication issue, etc...then error stack-trace will be taken by web container and converted to html and simply send by response to render to the browser. So, end user will not be having understanding  about stack-trace.

Servlet container provides way to handle any kind of error and sends specific response or it can redirect to other page in case of error happen. So, rather than sending stack-trace as it is to the end user, we can navigate user to some other meaningful page so, that end user easily can understand that something went wrong.But to do this container should aware about this i.e. for which error what action should take or which page should redirect.

Hence to tell to servlet container we need to configure the deployment descriptor (web.xml) i.e. for which error code or which exeception type, which servlet should called.

Web.xml

 <error-page>
    <error-code>404</error-code>
    <location>/ExceptionHandler</location>
  </error-page>
   
  <error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/ExceptionHandler</location>
 </error-page>

error-page tag is used to handle error in servlet. It can either handled for error code or for exception type and location inner tag is used to tell about servlet location.In above example whenever error code 404 will arise or if ServletException will arise then ExceptionHandler Servlet will be invoked.
So, we can say any error can be handled by servlet.

Before servlet container invokes the servlet to handle the exception, it sets some attributes in the request to get useful information about the exception, some of them are javax.servlet.error.exception, javax.servlet.error.status_code, javax.servlet.error.servlet_name and javax.servlet.error.request_uri

For Example Below is given ExceptionHandler shows how to handle the specific error



protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Throwable throwable = (Throwable) request
                .getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request
                .getAttribute("javax.servlet.error.servlet_name");
        String requestUri = (String) request
                .getAttribute("javax.servlet.error.request_uri");
    
        PrintWriter out = response.getWriter();
          out.write("<html><head><title>Error Details</title></head><body>");
           
          if(statusCode != 500){
              out.write("Status Code:"+statusCode+"<br>");
              out.write("Requested URI:"+requestUri);
          }else{
              out.write("<ul><li>Servlet Name:"+servletName+"</li>");
              out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
              out.write("<li>Requested URI:"+requestUri+"</li>");
              out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
              out.write("</ul>");
          }
           
          out.write("<br><br>");
          out.write("</body></html>");
}

If there are multiple error-page entries, let’s say one for Throwable and one for IOException and application throws FileNotFoundException then it will be handled by error handler of IOException.
You can also use JSP page as exception handler, just provide the location of jsp file rather than servlet mapping.


Thanks!!!!

Monday, 27 October 2014

Creating wifi hotspot in windows by CMD/Command Prompt

Creating wifi hotspot-
I know this tutorial is about java but here creating wifi hotspot in windows, is different but should know to all the guys, because sometime situation comes where you don't have wireless router in home or office and still you want to connect your PC's or mobile devices through wifi hotspot.
Don't worry!!! you can still connect your devices through wireless hosted network but this is introduced from window7. You need to create only virtual wireless adapter to connect all the devices. I will explain some steps here to do this by command prompt-
  1. Open command prompt in administrator mode by choosing run as administrator.
  2. Check whether your PC has installed Wlan driver and does it supports hosted network, to check this use netsh command, type in cmd-  netsh wlan show drivers

  3. If hosted network supports yes then again use netsh command to create new hosted network-
    netsh wlan set hostednetwork mode=allow ssid=<user-defined-hotspotname> key=<password>
  4.  Now you start the hosted network by command-  netsh wlan start <user-defined-hotspotname>
  5. Now go to network and sharing center and click on "change adapter settings" select Local area connection on which internet is working, right click and click on property and select sharing tab and enable allow other network users option.

That's it now you can connect wifi hosted network in other devices where ever you want use it. And after usage done you cant stop this by using below command-
netsh wlan stop <user-defined-hotspotname>


As you can see to create wifi hotspot I have used netsh command but what is netsh command?
Netsh is a command-line scripting utility that allows you to, either locally or remotely, display or modify the network configuration of a computer that is currently running. Netsh also provides a scripting feature that allows you to run a group of commands in batch mode against a specified computer. Netsh can also save a configuration script in a text file for archival purposes or to help you configure other servers.

Thanks!!!!

Friday, 24 October 2014

Servlet Filter

Servlet Filter is a object inside web container, which is used to intercept the request and response before sending to server resource and browser.


In above diagram you can see that browser send the request to access the server request but in middle, Filter Object intercept the browser request and take action against the request and forward to server resource. Similarly Filter intercept in response also which is coming from Server Resource and take against it before sending to the browser.

Keeping Filter inside web container has various use-cases like(but use-case are not limited)-
  • User Authentication or Authorization-Blocking requests based on user identity.
  • Server load handle-Reject the request if server load is too much.
  • Logging and auditing -Tracking users of a web application
  • Data compression- Making downloads smaller.
  • Server Code Debug- Debug the server resource for performance tuning
In order to create the servlet filter, Filter interface (javax.servlet.Filter) need to be implemented.
Method decryption of Filter interface is given below-

void destroy()
          Called by the web container to indicate to a filter that it is being taken out of service.
 void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain. 
 void init(FilterConfig filterConfig)
          Called by the web container to indicate to a filter that it is being placed into service.
This filter configuration object used by a servlet container to pass information to a filter during initialization.

Let's take one example- whenever browser will send request along with allow parameter then only filter will allow to send request to the server otherwise it will reject.

MyServletFilter.java
 
package com.rkclass; 
import javax.servlet.*;
import java.io.IOException;


public class MyServletFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain)
    throws IOException, ServletException {
 
       String myParam = request.getParameter("allow");

       if("allow".equals(myParam)){
          filterChain.doFilter(request, response);
       }
    }

    public void destroy() {
    }
}
 

 
Web.xml
 
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>com.rkclass.MyServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping> 

Sunday, 12 October 2014

Servlet Listener

ServletListener is a small program which will listen to some events. Events can be anything like session event, context event, context attribute event, request event.
In this chapter I will explain-
  1. ServletContextListener
  2. ServletContextAttributeListener
  3. HttpSessionListener
  4. HttpSessionAttributeListener
  5. ServletRequestListener
ServletContextListener-
I explained the ServletContext in previous chapter. So, I am assuming you know about ServletContext.
ServletContext is a object that consist config to Share among Servlets.

Now assume you want execute some piece of code, when ever application context initialize or destroyed. In this scenario you need to know some events when context is initialize or destroyed.
Don't worry!!! javax.servlet.ServletContextListener interface provide this.

Below is the methods description of SessionContextListener-

 void contextDestroyed(ServletContextEvent sce)
          Receives notification that the ServletContext is about to be shut down.
 void contextInitialized(ServletContextEvent sce)
          Receives notification that the web application initialization process is starting.

For example I want to load the property file when I start the server.

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        try {
          String fileName = ctx.getInitParameter("configFile");
          System.out.println(fileName);
          File file = new File(fileName);
          FileInputStream fis = new FileInputStream(file);
  
          Properties p = new Properties();

          p.load(fis);
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        System.out.println("Context destroyed");
       
    }
     
}

Web.xml-

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

Now Property is ready to use.Whenever context will initialize Property will be loaded.

ServletContextAttributeListener
This interface and extends the java.util.EventListener class.Whenever attribute of SessionContext added/changed/removed this listener receive the notification event. But to get the notification, your servlet context attribute listener class should be register in the web container i.e. web.xml.

Below is the method description of this listener-
void attributeAdded(ServletContextAttributeEvent event)
          Receives notification that an attribute has been added to the ServletContext.
 void attributeRemoved(ServletContextAttributeEvent event)
          Receives notification that an attribute has been removed from the ServletContext.
 void attributeReplaced(ServletContextAttributeEvent event)
           

For Example-

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextAttributeListener implements ServletContextAttributeListener {
     
    public void attributeAdded(ServletContextAttributeEvent scab){      
            System.out.println("attribute Added");
    }

    public void attributeRemoved(ServletContextAttributeEvent scab) {
       System.out.println("attribute Removed"); 
    }

    public void attributeReplaced(ServletContextAttributeEvent scab) {       
       System.out.println("attribute Replaced");       
    }
     
}


Web.xml-

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

MyServlet.java-

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
     PrintWriter out = response.getWriter();
     ServletContext sc = getServletContext();
     sc.setAttribute("name", "XXX");
     sc.setAttribute("age", "23");
     sc.removeAttribute("name");
}    

you can verify the output log and you will get to know that when setting the attribute in ServletContext then attributeAdded() is getting invoked and when removeAttribute() is called then attributeRemoved() method is getting invoked by container.

HttpSessionListener
Whenever changes to the list of active sessions happen in a web application. i.e. new session is created or destroyed then this listener is notified.

Below is the method descriptor of this listener-
void sessionCreated(HttpSessionEvent se)
          Notification that a session was created.
 void sessionDestroyed(HttpSessionEvent se)
          Notification that a session is about to be invalidated.

For example suppose we want count the active session-

MyHttpSessionListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener{
  private int activeSession=0;  
   
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
 activeSession++;
 System.out.println("sessionCreated");
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
 activeSession--;
 System.out.println("sessionDestroyed");
  } 
     
}

Web.xml-

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

 MyServlet.java-


public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    

  HttpSession session = request.getSession(); //sessionCreated() will be execute
  //do something with session 
  session.invalidate();  //sessionDestroyed() will be execute
}    


HttpSessionAttributeListener
Whenever attibute added/deleted/replaced to the session object this listener will be notified by web container.

Below is the method descriptor of this listener
void attributeAdded(HttpSessionBindingEvent se)
          Notification that an attribute has been added to a session.
 void attributeRemoved(HttpSessionBindingEvent se)
          Notification that an attribute has been removed from a session.
 void attributeReplaced(HttpSessionBindingEvent se)
          Notification that an attribute has been replaced in a session.

MyHttpSessionAttributeListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener{

   
     @Override
     public void attributeAdded(HttpSessionBindingEvent event) { 
      String attributeName = event.getName(); 
      Object attributeValue = event.getValue(); 
      System.out.println(attributeName + " : " + attributeValue);
     }
 
     @Override
     public void attributeRemoved(HttpSessionBindingEvent event) {
 String attributeName = event.getName(); 
        Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue);
    }
 
     @Override
     public void attributeReplaced(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
 Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue); 
     }
}

Web.xml-

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

 MyServlet.java-


public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    

  HttpSession session = request.getSession(); 
  session.setAttribute("name", "xxx"); //attributeAdded() will be execute
  session.setAttribute("name", "yyy"); //attributeReplaced() will be execute
  session.removeAttribute("name"); //attributeRemoved() will be execute
  session.invalidate(); 
}    

ServletRequestListener 
Whenever request coming into the the web container or request going out from the web container then this listener is notified.

Below is the method description of this listener
void requestDestroyed(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to go out of scope of the web application.
 void requestInitialized(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to come into scope of the web application.