Monday, October 28, 2013

Path class in java

Java 7 introduces a new set of I/O APIs called NIO.2 that offer convenient ways to perform operations related to a file system. In this post, you will explore Path class and how it is useful.





Initially, Java offered the File class (in the java.io package) to access file systems. 
This class represents a file/directory in the file system and allows you to perform operations such as checking the existence of a file/directory,getting the properties, and deleting a file/directory











Following shortcomings were noticed in the first version of the Java I/O APIs:


  • The File class lacked the significant functionality required to implement even commonly used functionality. For instance, it lacked a copy method to copy a file/directory.
  • The File class defined many methods that returned a Boolean value. Thus, in case of an error, false was returned, rather than throwing an exception, so the developer had no way of knowing why that call failed.
  • The File class did not provide good support for handling symbolic links.
  • The File class handled directories and paths in an inefficient way (it did not scale well).
  • The File class provided access to a very limited set of file attributes, which was insufficient in many situations.



What Is a Path?





A file system stores and organizes files on some form of media, generally one or more hard drives, in such a way that they can be easily retrieved. 

Most file systems in use today store the files in a tree (or hierarchical) structure. At the top of the tree is one (or more) root nodes.

 Under the root node, there are files and directories . Each directory can contain files and subdirectories, which in turn can contain files and subdirectories, and so on, potentially to an almost limitless depth.








Relative or Absolute?





A path is either relative or absolute. 


An absolute path always contains the root element and the complete directory list required to locate the file. 
For example, /home/sally/statusReport is an absolute path.
All of the information needed to locate the file is contained in the path string.



A relative path needs to be combined with another path in order to access a file.
For example, joe/foo is a relative path.
Without more information, a program cannot reliably locate the joe/foo directory in the file system.




Symbolic Links



A symbolic link is a special file that serves as a reference to another file. 

For the most part, symbolic links are transparent to applications, and operations on symbolic links are automatically redirected to the target of the link.

Exceptions are when a symbolic link is deleted, or renamed in which case the link itself is deleted, or renamed and not the target of the link.

In the left figure, logFile appears to be a regular file to the user, but it is actually a symbolic link to dir/logs/HomeLogFile. HomeLogFile is the target of the link.





Java 7 introduces a new programming abstraction for path, namely the Path interface. This Path abstraction is used in new features and APIs throughout NIO.2, so it is an important interface to understand. 
A path object contains the names of directories and files that make the full path of the file/directory represented by the Path object; the Path abstraction provides methods to extract path elements, manipulate them, and append them.

In Java 6 and earlier you do that:

File file = new File("README.TXT");

In Java 7 you do that:

Path path = Paths.get("README.TXT");

To make the migration to Java 7 easier, the File class has a new method toPath() that allows you to transform File to Path:

Path path = new File("README.TXT").toPath();


Lets's have a simple example of Path :
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SimplePathDemo {
 public static void main(String[] args) {
  Path path = Paths.get("C:\\Android\\JavaLatte.txt");
  Path path1 = Paths.get(URI.create("C:\\Android\\JavaLatte.txt"));
  Path path2 = FileSystems.getDefault().getPath("C:\\Android\\JavaLatte.txt");
  //retrieve basic information;
  String str=path.toString();
  System.out.println("path : "+str);
  System.out.println("File Name : "+path.getFileName());
  System.out.println("Root of the path : "+path.getRoot());
  System.out.println("No. of file/directory name in path : "+path.getNameCount());
  System.out.println("Is abosolute : "+path.isAbsolute());
  System.out.println("Path elements : ");
  for(Path element : path){
   System.out.println(element);
  }
 }

}
Sample Output
path : C:\Android\JavaLatte.txt
File Name : JavaLatte.txt
Root of the path : C:\
No. of file/directory name in path : 2
Is abosolute : true
Path elements :
Android
JavaLatte.txt

Important Methods in the Path Interface

MethodDesciption
Path getRoot() Returns a Path object representing the root of the given path,
or null if the path does not have a root.
Path getFileName() Returns the file name or directory name of the given path. Note
that the file/directory name is the last element or name in the
given path.
Path getParent() Returns the Path object representing the parent of the given
path, or null if no parent component exists for the path
int getNameCount() Returns the number of file/directory names in the given path;
returns 0 if the given path represents the root.
Path subpath(int beginIndex, int endIndex) Returns a Path object that is part of this Path object; the
returned Path object has a name that begins at beginIndex
till the element at index endIndex - 1. In other words,
beginIndex is inclusive of the name in that index and
exclusive of the name in endIndex. This method may throw
IllegalArgumentException if beginIndex is >= number of
elements, or endIndex <= beginIndex, or endIndex is > number
of elements.
Path normalize() Removes redundant elements in path such as . (dot symbol
that indicates current directory) and .. (double dot symbol that
indicates parent directory).
Path resolve(Path other)
Path resolve(String other)
Resolves a path against the given path. For example, this
method could combine the given path with the other path and
return the resulting path.
Boolean isAbsolute() Returns true if the given path is an absolute path; returns false
if not (
Path startsWith(String path)
Path startsWith(Path path)
Returns true if this Path object starts with the given path, or
else returns false.
Path toAbsolutePath() Returns the absolute path


We'll see first some methods details and then example of each of them.

Removing Redundancies From a Path

Many file systems use "." notation to denote the current directory and ".." to denote the parent directory. You might have a situation where a Path contains redundant directory information.
Perhaps a server is configured to save its log files in the "/dir/logs/." directory, and you want to delete the trailing "/." notation from the path.

The normalize method removes any redundant elements, which includes any "." or "directory/.." occurrences. 

Converting a Path
The toUri() method returns the URI (a path that can be opened from a browser) from the path.
The toAbsolutePath() method returns the absolute path from a given relative path. In case the input path is already an absolute path, the method returns the same object. The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not need to exist for this method to work.
The toRealPath method returns the real path of an existing file. This method performs several operations in one:
  1. If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
  2. If the Path is relative, it returns an absolute path.
  3. If the Path contains any redundant elements, it returns a path with those elements removed.
This method throws an exception if the file does not exist or cannot be accessed. You can catch the exception when you want to handle any of these cases


Joining Two Paths
You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.
                Path joinPath = Paths.get("/home");
System.out.println("Join Path : "+joinPath.resolve("pkumar/test"));


Creating a Path Between Two Paths

A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.
Path p1 = Paths.get("/home");
Path p2 = Paths.get("/home/pkumar/test/BlogCode");


To navigate from home to BlogCode, you first navigate one level down to pkumar, one leve down to test and then one more level down to BlogCode.
Navigating from BlogCode to home requires moving up 3 levels.

Comparing Two Paths

The Path interface provides two methods to compare two Path objects: equals() and compareTo().

The equals() method checks the equality of two Path objects and returns a Boolean value.
when compareTo() compares two Path objects character by character and returns an integer: 0 if both Path objects are equal; a negative integer if this path is lexicographically less than the parameter path; and a positive integer if this path is lexicographically greater than the parameter path.



import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathDemo2 {
 public static void main(String[] args) {
  Path path = Paths.get("./JavaLatte.txt");
  Path normalizePath = path.normalize();
  System.out.println("Normalized path : "+normalizePath.toString());
  System.out.println("Normalized path : "+normalizePath.toUri());

  Path path1 = Paths.get("test.txt");
  Path AbsolutePath = path1.toAbsolutePath();
  System.out.println("Absoulete path (your current working dir) : "+AbsolutePath.toString());

  Path path2 = Paths.get("/home/pkumar/test.txt");
  Path AbsolutePath2 = path2.toAbsolutePath();
  System.out.println("Absoulete path (already absoulete) : "+AbsolutePath2.toString());
  System.out.println();

  Path realPath = null;
  Path path3 = Paths.get("JavaLatte.txt");
  try {
   realPath = path3.toRealPath();
  } catch (NoSuchFileException e) {
   //Logic for case when file doesn't exist
  }catch (IOException e1){
   //Logic for other sort of file error
  }
  System.out.println("Real Path : "+realPath.toString());
  System.out.println();  
  Path subPath = realPath.subpath(3, 4);
  System.out.println("SubPath(3,4) : "+subPath.toString());
  Path subPath1 = realPath.subpath(2, 3);
  System.out.println("SubPath(3,4) : "+subPath1.toString());
  System.out.println("Root (/ - linux or C:\\ - windows) : "+realPath.getRoot().toString());

  Path joinPath = Paths.get("/home");
  System.out.println("Join Path : "+joinPath.resolve("pkumar/test"));

  Path connectPath1 = Paths.get("/home");
  Path connectPath2 = Paths.get("/home/pkumar/test/BlogCode");
  System.out.println();
  System.out.println("Creating a Path Between Two Paths");
  System.out.println();
  System.out.println("home to BlogCode : "+connectPath1.relativize(connectPath2).toString());
  System.out.println("BlogCode to home : "+connectPath2.relativize(connectPath1).toString());
  System.out.println();
  Path connectPath3 = Paths.get("/pkumar");
  Path connectPath4 = Paths.get("/home/pkumar/test/BlogCode");
  System.out.println("pkumar to BlogCode : "+connectPath3.relativize(connectPath4).toString());
  System.out.println("BlogCode to pkumar : "+connectPath4.relativize(connectPath3).toString());
  System.out.println();
  System.out.println("Comparing path");
  Path comparePath1 = Paths.get("/home/pkumar/test/BlogCode");
  Path comparePath2 = Paths.get("/BlogCode");
  System.out.println("/home/pkumar/test/BlogCode compareto /BlogCode : "+comparePath1.compareTo(comparePath2));
  System.out.println("/BlogCode compareto /home/pkumar/test/BlogCode : "+comparePath2.compareTo(comparePath1));
  System.out.println("/BlogCode compareto /BlogCode : "+comparePath2.compareTo(comparePath2));

 }


Sample Output

Normalized path : JavaLatte.txt
Normalized path : file:///home/pkumar/test/BlogCode/JavaLatte.txt
Absoulete path (your current working dir) : /home/pkumar/test/BlogCode/test.txt
Absoulete path (already absoulete) : /home/pkumar/test.txt

Real Path : /home/pkumar/test/BlogCode/JavaLatte.txt

SubPath(3,4) : BlogCode
SubPath(3,4) : test
Root (/ - linux or C:\ - windows) : /
Join Path : /home/pkumar/test

Creating a Path Between Two Paths

home to BlogCode : pkumar/test/BlogCode
BlogCode to home : ../../..

pkumar to BlogCode : ../home/pkumar/test/BlogCode
BlogCode to pkumar : ../../../../pkumar

Comparing path
/home/pkumar/test/BlogCode compareto /BlogCode : 38
/BlogCode compareto /home/pkumar/test/BlogCode : -38
/BlogCode compareto /BlogCode : 0




Note : Implementations of java.nio.file.Path interface are immutable and safe for use by multiple concurrent threads.



If you know anyone who has started learning java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Thursday, October 24, 2013

Basic Servlet Interview Question Answers

In this post, I'm gonna provide basic Servlet concepts with few diagram, so it will be easy to understood and remember. I hope you like these exclusive question-answers and if you like it please share or comment !



  1. What does your Web Server do?
    In simple term, " A web server takes a client request and gives something back to client".
    A web browser lets a user request a resource. The Web server get the request, find the resources, and returns something to the user. Resources can be HTML page, a picture, a sound file and even pdf file.
  2. What is 404 Not Found error?
    When user or web browser ask a resources, unless the thing isn't there or at least it's not where server is expecting it to be then you will get 404 error.
  3. What does web client do?
    Simply to say, "A web client lets the user request something on the server, and shows the user the result of the request".
    Client can be human user or the browser application. Generally, we don't care whether we are talking about human user or the browser app.
  4. How Client and Server talk to each other?
    In order to communicate, they must share a common language. On the web, clients and servers must speak HTTP and browsers must know HTML.
    HTML : tell the browser how to display content to the user.
    HTTP : is the protocol clients and servers use on the web to communicate.
    The server uses the HTTP to send HTML to the client.
  5. What is HTTP protocol?
    HTTP runs on top of TCP/IP.
    TCP is responsible for making sure that file send from one network to another node ends up in a complete file at the destination, even though file split into pieces when it is sent.
    IP is the underlying protocol that moves/routes the pieces from one host to another on their way to the destination.
    HTTP is another protocol that has web-specific features, but it depends on TCP/IP to get the complete request and response from one place to another.

  6. What is the structure of HTTP conversation?
    It's a simple Request/Response sequence; a browser requests and a server response.

    Key elements of request stream :
    HTTP method - action to be performed
    The page to access ( URL )
    Parameters

    Key elements of response stream :
    A status code like 404 etc.
    Content-type like text, picture etc
    The actual content like HTML, image etc

  7. What is in request or what we send in a request?
    First thing you will find is a HTTP method name. These methods tell the server the kind of request that's is being made and how the rest of the message will be formatted. The HTTP protocol has several methods, but we here discuss only the basic ones GET and POST.
  8. What is in response or what server send in a response?
    An HTTP response contain HTML. HTTP adds header information to the top of whatever content is in the response. The HTML browser uses the header info to process the HTML page.
    When the browser finds the opening html tag it goes into HTML -rendering and display the page to the user.
    when the browser get to an image tag, it generate another HTTP request.
  9. What is GET and POST methods?
    GET is a simplest HTTP method, and its main job in life is to ask the server to get a  resources and send it back. The resources can be image, sound file, pdf etc.
    It's also true that amount of characters in a GET is really limited.
    The data send with the GET is appended to the URL.
    POST is more powerful request. It's like GET ++ . With POST, you can request something and at the same time send form data to the server.
  10. Difference between GET and POST?
    1. GET is a safe method (idempotent) where POST is non-idempotent method
    2. We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.
    3. GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.
    4. GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.
    5. Hyperlinks in a page uses GET method.
  11. What is the Structure of HTTP GET request?


  12. What is the Structure of HTTP POST request?


  13. What is MIME type?
    In response header, content-type header's value is known as a MIME type. The MIME type tell the browser what kind of data the browser is going to receive so that the browser will know how to render it.
    Note : MIME type value relates to HTTP request's "Accept" header.
  14. What is the structure of HTTP response?


     
  15. What is URL and it's format?
    Uniform Resources Locators. Every resources on the web  has it's own unique address, in the URL format.

    http://www.java-latte.blogspot.in:80//2013/08/garbage-collection-in-java.html

    http:// Tells the server which communications protocol will be used.
    www.java-latte.blogspot.in The unique name of the physical server you're looking for. This name maps to unique IP address
    80 This part of URL is optional.
    /2013/08/  The path to the location on the server, of the resources being requested.
    garbage-collection-in-java.html The name of the content being requested. This could be HTML page, a servlet, an image, PDF, music, video etc
    Optional Query String If this was GET request, the extra info would be appended to the end of the URL, starting with a question "?" mark.
  16. What is a TCP port number?
    A TCP port is just a number. A 16-bit number that identifies a specific software program on the server hardware. The TCP port numbers from 0 to 1023  are reserved for well-known  services.
    Some well known ports :
    FTP : 21
    TELNET : 23
    SMTP : 25
    TIME : 37
    HTTPS : 443
    POP3 : 110
    HTTP : 80
  17. What two things web server alone can't do?
    First, it can't serve dynamic content. The web server application serves only static web pages, but a separate helper application (servlets) that the web server can communicate with can build non-static, just-in-time pages.
    Secondly, it can't save data on the server.
  18. What is a servlet?
    Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
  19. What is difference between PrintWriter and ServletOutputStream?
    PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.
    We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

  20. What is SingleThreadModel interface?
    SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used
  21. Basic steps of request and response flow?
    The user type the URL.
    The browser create an HTTP get request as you seen above diagram.
    The HTTP GET is sent to the server.
    The server find the page.
    Then server generate the response.
    The HTTP response sent to the browser.
    The browser render the page.
    User see the result on the browser.
  22. What is a container?
    Servlets don't have main method. They are under the control of another Java application called a container. For instance, Tomcat.
  23. How Container and Servlets works?
    When your web server application like apache gets a request for a servlet as opposed to a static HTML page, the server hands the request not to the servlet itself, but to the container in which servlet is deployed. It's the container that give servlet the HTTP request and response and it's the container that calls the servlet methods like doGet() and doPost().
  24. What is the advantages of Container?
    It's the container that help you to concentrate on business logic instead of worrying about code for threading, security and networking.
    Container gives you following benefits:
    Communication support : You don't have to build a server socket, listen to port etc for your servlets to talk to your web server.
    Lifecycle Management : It control the life and death of your servlets. It takes care of loading the classes, instantiating and initializing the methods, invoking the servlets methods etc.
    Multithreading support : The container automatically creates a new java thread for every servlet request it receives.
    Declarative Security : With the help of XML deployment descriptor you can configure security without having to hard code it in your sevlet. The same thing can be done with the help of annotations on servlet 3.0+.
    JSP support : Container take care of translating JSP code into real java.
  25. How container handles the a request?
    1. When user clicks on the URL to a sevlet instead of a static page.
    2. The container sees the request is for a servlet, so the container creates 2 objects:
    HttpServletResponse
    HttpServletReqeust
    3. The container finds the correct servlet based on the URL in the request, creates or allocated a thread for that request and passes the request and response object to the servlet thread.
    4. The container calls the service() method. Depending on the type of request, the service method call the doGet() or doPost() method.
    5. The doGet() method generate the page and stuffs the page into response object. The container still has a reference to the response object.
    6. The thread completes, the container convert the response object into HTTP response, sent it back to the client, the delete the request and response objects.
  26. How container found the servlet?
    The URL that comes in as part of the request from the client is mapped to a specific servlet on the server.
    A servlet can have THREE names.
    1. Actual file name : The developer servlet class has a fully qualified name that includes both the class name and package name. The servlet class file has a real path and file name, depending on where the package directory structure lives on the server.
    2. Deployer-known secret internal name : The deployer can create a name that's known only to the deployer and others in operational environment. This name is fake name, made just for the deplyoment of the servlet.
    3. Client -known URL name : The client sees a URL for the servlet, but doesn't really know that servlet name maps to real directories and files back to the server.

    We use deployment descriptor to map URL to servlets.
  27. How to declare URL mapping to servlet?
    Basically, two DD elements  are used for URL mapping.
    1. <servlet> : this maps internal name to fully qualified class name
    2. <servlet-mapping> : this maps internal name to public name.

    Example:
    <servlet>
    <servlet-name>InternalName1</servlet-name>
    <servlet-class>java.latte.Servlet1</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>InternalName1</servlet-name>
    <url-pattern>/publicServlet</url-pattern>
    </servlet-mapping>
  28. What are the benefits of DD ( deployment descriptor )? 
    Minimize touching source code.
    Fine tune your application, even if you don't have the code.
    Lets you application to adapt different resources like databases without compiling and test any code.
    Easier to maintain dynamic security like access control lists.
    Let Non-programmers to modify and deploy your web applications
  29. What is MVC and what it does?
    Application is structured in 3 layers:
    Model : containing all data and operations, implemented as java classes
    View : create various presentations, implemented as JSP
    Controller: receive requests, update model and delegating to views, implemented as single servlet.

    The essence of MVC is that you separate the business logic from presentation, but put something between them so that the business logic can stand on its own as reusable class, and doesn't have to know anything about the view.
  30. How MVC use in Servlet and JSP?
    Controller (servlet) : Takes user input from the request and figures out what is means to model. Tell the model to update itself and make the new model state available for JSP (view)
    View : Responsible for the presentation. It gets the state of the model from the controller not directly. It's also the part that gets the user input that goes back to the controller.
    Model : Hold the real business logic and state.It know the rules for getting and updating the state. It's the only part of the system that talks to databases.

  31. Servlet Life cycle methods?
    The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
    1. If an instance of the servlet does not exist, the web container
        Creates an instance of the servlet class.
    2. Initializes the servlet instance by calling the init method. Initialization is covered in Creating and Initializing a Servlet.
    If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method. For more information, see Finalizing a Servlet.


  32. How request is handle by Thread?
    You might hear that "Each instance of the servlet.." but that's just wrong.
    There are not multiple instance of any servlet class, except in one special case called SingleThreadModel.
    The container runs multiple thread to process multiple request to a single servlet.
    Have a look at the picture.


  33. What is ServletConfig object?
    1. There is only one servletConfig object per servlet.
    2. Use it to pass deploy time information to the servlet that you don't want to hard-code into the servlet.
    3. Use it to access the ServletContext.
    4. Parameters are configured in the DD.
  34. What is ServletContextConfig?
    1. There is only one ServletContext per web app.
    2. Use it to access web app parameters.
    3. Use it as a kind of notice board, where you can put up messages application can access.
    4. Use it to get servlet info, including the name and version of the container, and the version of the API that's supported.

  35. Servlet key API's?


  36. What is difference between GenericServlet and HttpServlet?
    GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that’s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol
  37. What are the different HTTP request methods?
    GET : Asks to get the resources at the request URL
    POST : Asks the server to accept the body info attached to the request, and give it to the resources at the requested URL.
    HEAD : Asks only for the header part of whatever a GET would return. So it's just like GET, but with no body in the response. Gives you info about the requested URL without  actually getting back the real thing.
    TRACE : Asks for loopback of the request message, so that the client can see what is being received on the other end, for testing.
    PUT :  To put the enclosed info at the requested URL
    DELETE : To delete the resources at the requested URL
    OPTIONS : To list of the HTTP methods to which the resources at the requested URL can respond.
    CONNECT : To connect for the purpose of tunneling.
  38. what is idempotent request?
    Idempotent request means you can do the same thing over and over again, with no unwanted side effects. or A HTTP method is said to be idempotent if it returns the same result every time
    GET,HEAD and PUT are idempotent.
  39. what else you can get besides parameters from request Object?
    1. The client's platform and browser info.
          request.getHeader("User-Agent")
    2. The cookies associated with the request
          reqeust.getCookies()
    3. Session associated with the request
          request.getSession()
    4. The HTTP method of the request
          request.getMethod()
    5. An input Stream from the request
          request.getInputStream()
  40. What is the difference between getServerPort(), getLocalPort() and getRemotePort()?
    getRemotePort() :  means "get the client's port". In other words, the port number on the client from which request was sent. If you are a servlet, remote means client.
    getLocalPort() : means on which port did the request end
    getServerPort() :  means to which port was the request originally sent.
  41. What it Redirect?
    You can choose to have something else handle the response for your request. In that case, you redirect the request to a completely different URL.
         response.sendRedirect("http://java-latte.blogspot.in/2013/10/linkedblockingdeque-in-java.html");

    You can use relative URL as the argument to sendDirect(), instead of specifying the whole "http://www....." thing.
    Relative URL come in two flavors: with or without slash (/)

    Imagine client type the following URL
    http://java-latte.blogspot.in/myapp/cool/bar.do and your send redirect method URL does not start with /
    sendRedirect("foo/stuff.html");
    The container build the full URL relative to the original request URL
    http://java-latte.blogspot.in/myapp/cool/foo/stuff.html

    But if the argument in send redirect start with /
    sendRedirect("/foo/stuff.html");
    The container build the complete URL relative to the web container itself, instead of relative to the original URL of the request.
    http://java-latte.blogspot.in/foo/stuff.html

    You can't do a sendRedirect() after writing the response and it takes a string Not a URL object.
  42. What is request dispatch?
    It means something else on the server do the work while redirect makes the client do the work . So remember, redirect=client and dispatch=server.
    RequestDispatcher has only two methods - forward() and include() and you get requestDispatcher  from the request or from the context.

    ReqeustDispatcher view = request.getRequestDispatcher("result.jsp");
    ReqeustDispatcher view = getServletContext().getRequestDispatcher("/result.jsp"):
  43. Difference between redirect and dispatch?
    When a servlet does a request dispatch, it's like asking a co-worker to take over working with a client . The co-worker ends up responding to client, but the client doesn't care as long as someone responds. The user never knows someone else took over, because URL in the browser bar doesn't change.
    When a servlet does a redirect, it's like asking the client to call someone else instead. In this case, the client is the browser, not the user. The browser makes the new call on the user's behalf, after the originally-requested servlet says," sorry call this guy instead". The user sees the new URL in browser.
  44. What is init Parameters in Servlet?
    Init Parameters are used to define properties that you don't want to hard code in java class. For instance, you email address.

    <servlet>
    <init-param>
    <param-name>email</param-name>
    <param-value>pardeep131085@gmail.com</param-value>
    </init-param>

    </servlet>

    When the container makes a servlet, it read the DD and creates the name/value pairs for servletConfig. The container never read the inits parameter again! Once the parameters are in servletConfig, they won't be read again until you redeploy the app.

    In servlet code:
    getServletConfig().getInitParameter("email");
  45. What is Context init parameters?
    Contexts init parameters work just like init parameters, except context parameters are available to the entire webapps, not just a single servlet. So that means any servlet and JSP in the app automatically has access to the context init parameters.

    <web-app>
    ...
    <context-param>
    <param-name>email</param-name>
    <param-value>pardeep131085@gmail.com</param-value>
    </context-param>

    </web-app>
    The <context-param> is for the WHOLE app, so its not nested inside an individual <servlet> element.

    In servlet code:
    getServletContext().getInitParameter("email");
  46. What you do with ServletContext?
    1. Get the init parameters and get/set attributes.
    2. Get info about the servlet/container
    3. Do the request dispatcher.
    4. Write to server log file.

    You can get ServletContext in 2 different ways:
    getServletConfig().getServletContext().getInitParameter()
    this.getServletContext().getInitParameter();
  47. What is ServletContextListener?
    There may a situation where you want to run any code before start of app can serve a client such as db connection. In this case, ServletContextListener come into picture. In ServletContextListener interface, there are two method that are notified when the context is initialized and when the context is destroyed.
             contextInitialized(ServletContextEvent)
             contextDestroyed(ServletContextEvent)


    To implement ServletContextListener, write a listener class that implements the ServletContextListener, put it in a WEB-INF/ classes directory and tell the container by putting a <listener> element in the DD.
  48. What are other Listeners and it's purpose?
    ServletContextAtttributeListener : when you want to know if an attribute in a web app context has been added or replaced.
    HttpSessionListener : When you want to know how many concurrent users there are
    ServletRequestListener : When you want to know each time a request comes in, so that you log it.
    ServletRequestAttributeListener : When you want to know when a request attribute  has been added, removed or replaced.
    HttpSessionBindingListener : You have an attribute class and you want objects of this type to be notified when they are bounded or removed from a session.
    HttpSessionAttributeListener : You want to know when session attributes are  added, removed or replaced.
    ServletContextListener : You want to know if a context has been created or destroyed.
    HttpSessionActivationListener : You have an attribute class, and you want objects of this type to be notified when the session to which they're bound is migrating to and from another JVM
  49. Difference between attribute and parameters?


  50. What are the three attribute scope?
    Context Attributes : Everyone in the application has access.
    Not thread safe. To synchronize you must lock on the servlet context
    synchronized(getServletContext);
    Session Attributes : Accessible to those with access to specific HttpSession.
    These are also not thread safe.To synchronize you must lock on the HttpSession.
    synchronized(session);
    Request Attributes : Accessible to only those with access specific to ServletRequest.
    The request attributes and local variable are thread safe.
  51. How to maintain client specific state across multiple requests?
    1. Use a stateful session enterprise javabean
    2. Use a database
    3. Use an HttpSession
    An HttpSessionObject can hold conversational state across multiple request from the same client. In other words, it persists for an entire session with a specific client. we can use it to store everything we get back from the client in all the requests the client makes during a session.
  52. How session is maintained?
    The Http protocol uses stateless connections. The client browser takes a connection to the server, send the request, got the response and close the connection. In other words, the connection exists only for a single request/response.

    The idea is simple: on the client first request, the container generates a unique session ID and gives it back to the client with the response. The client sent back the session ID with each subsequent request.
  53. How do the client and container exchange session info?
    The simplest and the most common way is through cookies.


     
  54. How cookies works?
    You do have to tell the Container that you want to create or use a session, but the container takes care of generating session ID, creating a new cookie object, stuffing the session ID into the cookie, setting the cookie as part of response. And on subsequent requests, the Container gets the session ID from a cookie in the request, matches the session ID with an existing session and associate the session with the current request.

    Sending a session cookie in the response
    HttpSession session =  request.getSession();
    You ask the request for a session, and the container kicks everything else into action. You don't have to do anything.
    You don't make the new HttpSession object yourself.
    You don't generate the session ID.
    You don't make the new Cookie Object.
    You don't associate the session ID with Cookie.
    You don't set the Cookie into the response.
    ALL the cookie works happens behind the scene.

    Getting the session ID from the request
    HttpSession session =  request.getSession();
    It's exactly the same method used to generate the session ID and cookie for the response.
    IF ( request include a session ID cookie )
        find the session matching that ID
    ELSE IF( no session ID cookie OR no current session matching the session ID)
       create a new session.
    ALL the cookie works happens behind the scene.
  55. What happens if client won't accept cookies?
    URL rewriting : something to fall back on.
    If the client won't take cookies, you can use URL rewriting as a backup.  URL rewriting always works.
    Image  a web page where  every link has a little bit of extra info tacked onto the end of the URL. When a user  clicks , the request goes to the container with that extra bit on the end, and the container simply strips off the extra  part of the request URL and  uses it to find the session.







    URL rewriting is automatic... but only if you encode your URL's. You have to run all your URL's through  a method of the  response object  - encodeURL() and the container does everything.
  56. How a session can die?
    It times out
    You call invalidate() on the session object.
    The application goes down.
  57. How to set timeout for a specific session?
    session.setMaxInactiveInterval(20*60); // 20 minutes
  58. What are the different ways of session tracking?
    Cookies
    URL rewriting
    HttpSession
    Hidden form fields.
  59. What are the Key milestones for an HttpSession?
    1.
    The session is created or destroyed.
    2. Session attributes are added, removed or replaced by other parts of the app.
    3. The session is passivated in one VM and activated in another within  a distributed app.
  60. What happened to ServletContext, ServletConfig and HttpSession in case of clustered environment app is on different JVM?
    Only HttpSession objects and their attributes move from one VM to another.
    There is one ServletContext per VM. There is one ServletConfig per servlet, per VM.
    But there is only one HttpSession object for a given session ID per web app regardless of how many VM's the app is distributed across.

  61. Simple Client and web server interaction?
    1. User click a link in the browser.
    2. Browser formats the request and sends it to the server.
    3. Server find the requested page.
    4. Server formats the response and sends it to the browser.
    5. Browser gets the HTML and renders it into a display for the user.
  62. How the container handles the request?
    1. User clicks a link that has a URL to a servlet instead of a static page.
    2. The Container sees that the request is for a servlet, so the container creates 2 objects: HttpServletResponse and HttpServletRequest.
    3. The container finds the correct servlet based on the URL in the request, creates or allocates a thread for that request and passes the request and response object to the servlet.
    4. The container calls the servlet's service() method. Depending on the type of request, the service() method calls either the doGet() or doPost() method. We assume doGet().
    5. The doGet() method generates the dynamic page and stuffs the page into the response object. Remember, the container stills has a reference to the response object.
    6. The thread completes, the container converts the response object into an Http response, sends it back to the client, then deletes the request and response object.
  63. The story of non-idempotent request?Assume you are purchasing a book from a online website and you have already saved your credit detail.

    1. User hits the checkout button. ( bank details are already submitted).
    2. Browser sends an HTTP request to the server with the book purchase info and user customer ID.
    3. The container sends the request to the checkout servlet for processing.
    4. Servlet debits the user back account.
    5. Servlet update the database i.e, takes the book out of the inventory creates a new shopping cart.
    6. Servlet does not send an obvious response, so User still see the same  shopping cart page and think I better hit the checkout button again.
    7. Browser sends an HTTP request to the server with the book purchase info and customer ID number.
    8. The container sends the request to the checkout servlet for processing.
    9. The servlet does not have a problem with user buying the same book again.
    10. Servlet debits the user bank account second time.
    11. User accept the debit, but charges double than normal price.
    12. When User navigates to the check order status page and sees that user has two orders for the same book.
    13. Boooooom..........
  64. The story of a redirect response?
    1. Client types  a URL into the browser bar.
    2. The request goes to the server/container.
    3. The servlet decides that the request should go to a completely different URL.
    4. The servlet call the sendRedirect(astring) on the response and that's it.
    5. The HTTP response has a status code 301 and location header with a URL as the value.
    6. The browser gets the response, sees the 301 status code, and looks for a location header.
    7. The browser makes a new request using the URL that was the value of a location header in the previous response. The user might notice that the URL in the browser bar changed.
    8. There is nothing unique about the request, even though it happened to be triggered by a redirect.
    9. The server gets the thing at the request URL. Nothing special here.

    10. The Http response is just like any other response,... except is isn't coming from the location the client typed in..
    11. Client surprised to see the new URL....
  65. The Story of a Dispatch response?
    1.
    User types a servlet's URL into the browser bar.
    2. The request goes to the server/container.
    3. The servlet decides that the request should go to another part of the web app ( in this case, a JSP)
    4. The servlet call the requestDispatcher and the JSP takes over the response.
    5. The browser gets the response in the usual way, and renders it for the user. Since the browser location bar didn't change, the user does not know that the JSP generated the response.
  66. The story of session migration?
    1. User hit the submit button.
    2. The Load-Balancing server decides to send the request to container A-1 in VM one.
    3. The Container makes a new session, ID#111. The "JSESSIONID" cookie is sent  back to the user in the response.
    4. User select another option and hit the submit button again.
    5. This time, Load-Balancing server decides to send the request to container A-2 in VM two.
    6. The container gets the request, sees the session ID, and realizes that the session is on a different VM. VM one.
    7. The session #111 migrates from VM one to VM two. In other words, it no longer exists on VM one once it moves to VM two. This migration means session was passivated on VM on and activated on VM two.
    8. The container makes a new thread for ServletA, and associate the new request with the recently moves session #111. User new request is sent to the thread, and everybody is happy. User has no idea what happened.
  67. The Role of Web server, Container and Servlet?

    TaskWeb serverContainerServlet
    Create the request and response objectJust before starting the thread
    Call service() methodThen service() method call the doGet() o r doPost()
    Start a new thread to handle requestStart a servlet thread
    Convert a response object to an HTTP response.Generate the HTTP response stream from the data in response object
    Knows HTTPUses it to talk to client browser
    Adds HTML to the responseThe dynamixc content for the client
    Has a reference to the response objectsContainer gives to the servletUses it to print a response.
    Finds URL in the DDTo find the correct servlet for the request
    Deletes the request and respons objectonce the servlet is finished
    Coordinate making dynamic contentKnow how to forward to the containerKnows who to call
    Manages lifecyclesCalls service() method
    Has a name that matches the <servlet-class> element in the DDpublic class whatever






Related Post
120+ Core java interview question answers



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...