Saturday 27 September 2014

Cookies

As you know Http is stateless protocol. So, each time when any user request in web application, it will be new request. Hence we can not identify the user that user is already accessed the web resource or not.To avoid this web application has provided cookie mechanism to identify the user states.

Cookie is nothing but small filesystem in client browser, that can store some information. Cookie can be of two types-
  • Session cookies – Session cookies are stored in memory and are accessible as long as the user is using the web application. Session cookies are lost when the user exits the web application. Such cookies are identified by a session ID and are most commonly used to store details of a shopping cart.
  • Permanent cookies – Permanent cookies are used to store long-term information such as user preferences and user identification information. Permanent cookies are stored in persistent storage and are not lost when the user exits the application. Permanent cookies are lost when they expire.
Cookie is good option to store minimal value around 4k bytes of data to the client browser. Data always should be textual format. And cookie will not work if cookie option is disabled from the browser.



Creating the Cookie
 javax.servlet.http.Cookie class provide the functionality to create the cookie.

Cookie cookie = new Cookie("cookie-name" , "cookie-value")

You know now how to create the cookie but as earlier explain cookie stored inside client browser, so  response object help us to send cookie to the client browser by addCookie() method.

response.addCookie(cookie)

Reading Cookie
Whenever client sends new request, it submit cookie also. So cookie read by getCookies() method of request object.

Cookie[] cookies = request.getCookies();

for(Cookie cookie : cookies){
    if("cookie-name".equals(cookie.getName())){
        System.out.println(cookie.getValue());
    }
}

Removing Cookies
Removing the cookie is control by setMaxAge() method. This method takes int value from parameter expiry in second, if the passed parameter value is 0 then cookie will be removed immediately. And if passed parameter is -1 then cookie will be live until browser shutdown.

Cookie cookie = new Cookie("cookie-name" , "cookie-value");
cookie.setMaxAge(0);
response.addCookie(cookie);
 
Next chapter I will explain the next way of session tracking- next chapter 

Saturday 20 September 2014

Session Tracking

Session Tracking
Http is stateless protocol, this means that one request and response for this request is one cycle. These cycles are not dependent to each other. Hence each cycle's states are independent. But sometime during development we get scenario where maintaining state is required. e.g. Login module of application need to know which user is loggedin so, here user state is require to maintained

So, To recognize the user It is used to recognize the particular user.

In servlet there are four techniques used in Session tracking:
  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

GenericServlet vs HttpServlet

You have seen in servlet tutorial here, I have given idea about Servlet APIs, Servlet interface implemented by GenericServlet Class and GenericServlet class extended by HttpServlet. So, why HttpServlet if GenericServlet? What is the advantage you will achieve by HttpServlet?
Let us know about more about GenericServlet and HttpServlet-

GenericServlet- This is Generic class and used to create protocol independent Servlet. When you create servlet class, need to ovverride service() method. service() method has two parameter ServletRequest and ServletResponse. These parameter is also Generic and used to pass protocol independent parameter. This means it can handle any type of request e.g. http, ftp, smtp.

Example is given in previous chapter, to go click here,

HttpServlet- This class is extended from GenericServlet. This is specific to Http protocol which used to create http protocol dependent Servlet. When you create servlet class, you have choices to ovverride either service(), doGet() or doPost()  method. doGet() and doPost() method has two parameter HttpServletRequest and HttpServletResponse. These parameter is specific to http and used to pass http protocol dependent parameter. This servlet class is introduced to make life easier, so that developer no need to worry about http protocol things separately.

E.g.

package example; 
import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class MyServlet extends HttpServlet{ 
 
 //this will handle http get
  public void doGet(HttpServletRequest req,HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    out.println("Basic http servlet example");
    out.close();
  }
 
//this will handle http post 
  public void doPost(HttpServletRequest req,HttpServletResponse res)
    throws ServletException, IOException
  {
   doGet(req,res);
  } 
}
 
 
To go next chapter click here 

Saturday 13 September 2014

Servlet

Servlet is java Object and it is used to create dynamic web pages, which deployed in web server or application server (e.g tomcat, jboss). And invoked from web browser to run inside servelet container.
It is part of J2EE. Servlet works on client-server architecture. clients are browser and servers are container (webservers or application servers)where java codes deployed.


Server should have servlet container to handle request and response.When browser sends Http requests, servlet container checks the request of type servlet then it find the appropriate servlet and delegate the request to servlet and after finishing the execution of servlet, Http response is generated and response sent back to browser.

Servlet container is responsible to handle lifecycle for servlet. 

Servlet Lifecycle
A servlet passes through the following stages in its life.
  • Initialize
  • Service
  • Destroy



Servlets instance gets created by the web container which calls the init() method for first Http request. At init() method completion, Servlets is present in a ready state to service the requests from client. But make sure init() method execute once for first request not for all request.

Servlets service method is being called by container to handle every request, by spawning new threads. For every request, from thread pool of the web container there also exists the possibility to have one threaded servlet.

Before the instance gets destroyed, the destroy() method will be called by the container. After destroy(), the servlet is considered as a potential candidate, for collection of garbage.

Hence init(), service() and destroy() methods are the main methods of Servlet. Apart from these methods some other method are also present in the Servlet interface. To understand in more let's see below diagram, which present in javax.servlet package-




The Servlet interface is the base interface for all servlets. The GenericServlet interface, described later, implements this interface. The interface defines the basic methods that a servlet running inside a servlet engine defines to process client requests. The Servlet interface defines the following life cycle methods:
  • init()— Servlet initialization routine
  • service()— All-purpose routine to process client requests
  • destroy()— Clean-up routine for freeing resources, storing state information, and so forth
The interface also defines the getServletConfig() method, which returns the ServletConfig object that holds the initialization parameters and other configuration of the servlet defined by the user. These parameters are usually defined in the deployment descriptor of the Web application. Developers who want to implement the Servlet interface should take care of storing the ServletConfig object passed to the init method if the getServletConfig() method has to return the object when the servlet needs the configuration object. This interface also provides a getServletInfo() method, which can return information about the servlet, such as its author, version, and copyright text.

The ServletConfig interface is configuration object, which is passed into the servlet when it's instantiated (through the init method), provides user configuration information as name-value pairs.
getInitParameter
Takes a string representing the initialized parameter as argument and returns the value of the parameter.
getInitParameterNames
Returns all the names of the parameters.
getServletContext
Returns the ServletContext object, which represents the servlet's runtime environment. The ServletContext object is explained later.

The ServletContext interface is the servlet's view of the Web container. The getServletContext() method of ServletConfig returns the ServletContext object. This interface provides a lot of methods, and for easier understanding we can classify the methods into the categories in the following sections. 
getMajorVersion
the major version of the Servlet API supported by the container.
getMinorVersion
the minor version of the Servlet API supported by the container.
getMimeType(String file)
Returns the MIME type of the file. text/html is one of the common MIME types.
getRealPath
For the SimpleServlet2 example, the path returned is c:\bea\user_projects\mydomain\applications\wlsUnleashed\SimpleServlet2. As you can see, it's with respect to the location of the file in the computer and the OS on which the WebLogic Server is running. This method will return null if WebLogic Server cannot translate the virtual path to a real path.
getServerInfo
Returns the name and version of the servlet container. In our case, you'll an output similar to the following: WebLogic Server 8.1 Thu Mar 20 23:06:05 PST 2003 246620.
   


Let's create the first servlet example.


 
Above is the directory system to create web application (hope you have some idea).Create application name is mywewapp. create the below Servlet class and put inside classes folder inside WEB-INF.
 
package example; 
import java.io.*;

import javax.servlet.*;

public class MyServlet extends GenericServlet{ 
 
  public void service(ServletRequest req,ServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    out.println("Basic servlet example");
    out.close();
  }
}

Here we have created MyServlet class which extends GenericServlet. we have overrided here service method.Now write the servlet mapping to web.xml (deployment descripter) file  like below-

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

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

    <servlet>
        <servlet-name>MyServletClass</servlet-name>
        <servlet-class>examples.MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyServletClass</servlet-name>
        <url-pattern>/myservlet</url-pattern>
    </servlet-mapping>

</web-app> 

web.xml deployment descriptor file, the <servlet> XML element declares the MyServlet, the examples.MyServlet Java class implements the servlet, and the <servlet-mapping> XML element specifies the /myservlet URL pattern that invokes the servlet in a browser.

Now put application in server and start the server.

URL will be  http://localhost:8080/mywewapp/myservlet invoked from browser. If this is first request then init() method calls first then service() method later. But if this is second request then directly service() method will be call.

service() method has two parameter ServletRequest and ServletResponse. One ServletRequest and one ServletResponse Object is always created per request and response. When request reached to the servlet it gives the ServletRequest Object to service() method This ServletRequest Object contains all the detail about request e.g. remotehost, remoteport, scheme, request parameter, header.This service() method is uses, value from ServletRequest to execute business logic and put response to the second parameter of service() method. This response is later given to the browser. Browser read and render  response object.

To go next chapter click here

Servlet vs JSP

Servlet is java code and it is used to create dynamic web pages, which deployed in server (e.g tomcat, jboss).
see below simple servlet example -

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class MyServlet extends HttpServlet { 
 
  public void doGet (HttpServletRequest 
                       req,HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    out.println("Basic servlet example");
    out.close();
  }
}
 
Here we have created MyServlet class which extends HttpServlet. we
have overrided here doGet method which will invoked by GET method 
of http request.

Servlet class before putting to the server,need to compile it 
manually. To know more about servlet click here 
 
JSP a scripting language and it is used to create web pages, which 
deployed in server. It is easy to understand.This is different than 
other scripting language.
 
JSP class before putting to server, no need to compile it. Because 
JSP container will compile it automatically and convert it into 
servlet classes. 
 
JSP has some components-
1) Declaration - <%! declaration; [ declaration; ]+ ... %>
2) Scriptlet - <% code fragment %>
3) Expression - <%= expression %>
4) Directive-  <%@ directive attribute="value" %> 
 
JSP provide by default implicit Object e.g.(out, page, request, 
response, session and so on..) 

Thursday 4 September 2014

Executor and ExecutorService in Java

Executor Framework (java.util.concurrent.Executors) included in jdk1.5. Before explaining what, why and how? I will explain little background about Thread. As you know Thread in java is used for parallel execution in new VM stack and it created by two ways Thread class and Runnable interface. To know more about thread click here
When you use Executor Framework then no need to create Thread explicitly. And multiple thread can execute  tasks concurrently. These multiple Thread maintained inside pool called Thread pool. Once Thread will be allocated to process one task it can't allocated to process other task until Thread is free. Whenever any Thread finish it execution it notify to executor framework to take up another task. Hence we can say that Executor Framework implicitly maintain the Thread allocation for the task.
We can have n number of Treads in the Thread pool. Thread can be reused by multiple time. So, Executor is very useful from performance point of view. because it will save the time to create the Thread again and again, as you know creating Thread inside is very heavy process.
An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 
So, java.util.concurrent.ExecutorService provide us the way to execute the task by Thread which present in the pool. And Executors factory class provide the factory method to create the Thread pool.
e.g-

ExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Runnable task");
    }
});

executorService.shutdown();
 
ExecutorService is created here using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
Later on, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.
And last line we are shutting the executorService.When you are done using the ExecutorService you should shut it down, so the threads do not keep running.

Apart from newFixedThreadPool() factory method some other method are also present in Executors factory class to create the ExecutorService e.g.-
newFixedThreadPool(),
newScheduledThreadPool().
As you have seen in above example that Runnable task is executed by execute() method of executorService. But apart from this we have some other ways to submit/execute the task, which is listed below-
execute(Runnable)- Only Runnable task can be execute by this and it doesn't return any value. as you have seen in above example.

submit(Runnable/Callable)- Runnable and Callable task both can be execute by submit method. and it always return Future.e.g.-
 
Future future = executorService.submit(new Runnable() {
    public void run() {
        System.out.println("Runnable task");
    }
});

future.get(); 

or

Future future = executorService.submit(new Callable(){
    public Object call() throws Exception {
        System.out.println("Callable task");
        return "Callable Result";
    }
});

System.out.println("future.get() = " + future.get());



invokeAny(collection)-
The invokeAny() method takes a collection of Callable objects, or subinterfaces of Callable. Invoking this method does not return a Future, but returns the result of one of the Callable objects. You have no guarantee about which of the Callable's results you get. Just one of the ones that finish.
If one of the tasks complete (or throws an exception), the rest of the Callable's are cancelled.

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();
 
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "First task ";
    }
});  
...................
......................
String result = executorService.invokeAny(callables);

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

executorService.shutdown(); 
 
invokeAll(collection)-
The invokeAll() method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of each Callable.
Keep in mind that a task might finish due to an exception, so it may not have "succeeded". There is no way on a Future to tell the difference.

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "First task ";
    }
}); 
 
..................................
.................................
 
List<Future<String>> futures = executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}

executorService.shutdown();