Dependencies means how a java bean is dependent on another bean class. That means if we defines any bean reference as a class member to another bean class, then it results in a bean dependent on another. A primitive type or any reference type ( other than a bean reference ) involves no dependencies. Dependencies is only with a bean class references because to inject dependencies we need that bean instance. So this makes the dependency on another bean.

Important points regarding dependency injection
1. Dependency should only be injected if instance of that bean is available in the container.
2. Instance will be created as all the beans are mapped to the XML file.
3. Instance will be created for the current bean and dependency will be injected for the dependent bean.
4. While injecting the dependencies Container need its instance , if not available then try to find the mapped bean of the injecting bean and try to create the instance.
5. Instance creation of the current bean depend on the type of injection i.e on constructor or setter injection.
6. If both the instance for dependency for each other then it is called as Cyclic Dependency.

Basically there are two types of Dependencies Injection :
1. Constructor Injection
2. Setter Injection

Constructor Injection 

Using constructor injection container is injecting the dependencies through constructor, for which instance must be available at the container. If not available then container search for its bean tag and then try to create an instance for that bean.

In the case of constructor injection
a. Container first create the instance of the  current bean.
b. Then try to inject the dependencies.

Constructor Injection should be mapped in the XML file under the bean tag using the < constructor-arg > tag with " ref  " attributes.

Setter Injection

With setter injection container is injecting the dependencies using the setter methods. It is same as the constructor injection with a difference in the order of creating the current bean instance.

In the case of Setter Injection
a. Container first try to inject the dependencies.
b. Then try to create the instance of current bean.

Setter Injection should be mapped in XML file under the bean tag using the < property > tag with the " ref " attribute.

Note : " ref " attribute contains the value of bean id which we have assigned while defining bean in XML. Explicitly writing the dependencies in the XML file is called as Explicit Wiring .

To know about Explicit wiring click here
IOC stands for the Inversion of Container. It is a container used in Spring core Framework. It is responsible for managing the states of the object i.e from its creation till its destruction. Before Spring framework, developer/programmer were responsible for creating and destroying the object, but with the development of Core Spring it is taken care by its Container itself i.e IOC container, but programmer needs to write some configuration in the XML file to indicate Container when and how to create an instance of the bean. In Spring a general java class i.e POJO ( Plain Old Java Object ) are considered as Bean. And its instance is called as Bean Object.    


When to create a Bean object is defined by mapping bean in the XML. As it mapped in the XML, in that way Container tries to create its Object. 

How to create a Bean Object is defined by Dependencies Injection.So Injection can be done in two ways only , either by Constructor or by Getter method. In general ways injection is defined as the way of creating an Bean class Object.     


Responsibility of IOC

Three main responsibility of the IOC is
1. Loading the bean classes .
1. Creating an instance for the bean using Dependencies Injection
3. Injecting the bean dependencies.

Spring Container reads the Configuration metadata where we configured our bean classes with its Dependency Injection. Together using POJO classes and its configuration in the XML file , Container try to load the bean classes and Inject the bean dependencies. 

In Spring There are two types of IOC container ,
1. BeanFactory Container.
2. ApplicationContext Container. ( Supports Annotation )

ApplicationContext was developed after BeanFactory with some extending functionality and over comes all the limitations which was with the BeanFactory and introduced some new features like supporting Annotation etc.

Note : A Container is simply a java object which manages the different states of an object and manages the life cycle of bean.


JVM memory deal with the heap memory which is further divided into two different generations. The two different generations , 
1. Young Generation
2. Tenured Generation
are implemented in the heap area. These generations are used for keeping track of object's state. Newly object got place in the young generation. As it grows old and at the time of garbage collection, those who are not garbage collected are shifted to the tenure generation, which is more likely to live long are compared to which who got garbage collected at the young generation. Like this when garbage collection takes place the state of the object changes from young to tenure generation. 

There is one more generation present in the JVM which is not a part of heap memory are termed as Permanent generation. It is used to stored the java classes and method object meta data information's.It also keep track of JVM generated object's for predefined classes. It has a fixed size of memory at the start of JVM, to change its size we need to do it explicitly by writing some commands. And its minimum and maximum size differs with every JDK. 

At very initial stage of java, there was not concept of permanent generation as both java objects and java classes are stored in the same memory area. Permanent generation comes into existence to enhance the performance as because at the earlier days , after a lot of analysis by the java vendor, they come to know that mostly all the java classes are static, that means no objects are created for that class. To maintain the simplicity and to enhance the performance a Permanent generation is introduced with the fixed memory ( not a part of heap ) to store the java classes meta data information . As we increases dealing with the objects, we need to keep track of its related class information as well which is in a separate memory i.e Permanent generation. It would be different to trace the object and its related class because class changes it state in regular basis. While garbage collecting the object from the tenure generate we need to know about it through its class information which is maintained in the permanent generation as a object. Rather it is possible by parallel collector to trace the old and new memory location of the java classes, but it makes a performance issue and slows down the performance of the JVM. So finally , they feel it would be better to remove the existence of permanent generation but replaces by MetaSpace

Note: Now there will not be an issue of java.lang.OutOfMemoryError: PremGem .  
Like Javac its a tool a compiler ( APT compiler ) is designed to compiler the source file having the annotations code. It is basically designed for the Annotations( metadata ) which come with the release of Java 5 . Internally APT uses AnnotationProcessor which is an Interface. No use of describing much because its a lot to describe if i start describing it. So basically it was developed to process Annotation based code but later a API was added to the javac i.e Pluggable Annotation Processing API with the release of JDK 6 . So javac would be more preferable for programmers rather then apt. By this reason it should be better to remove this facility. That is the reason why it comes with JDK 5 and gets deprecated in JDK 7 and finally removed with the release of JDK 8. 

Note: 

* Deprecated apt tool gets replaced with the development of Pluggable Annotation Processing API with the release of JDK 6 . So recommended to use javac only for Annotation processing as well.  

* APT was never be the part of Java SE , only was of JDK. 
Lambda Expression is one of the most important features come with the release of Java 8 version. It gives the way java can also deal with the functional approach. The aim behind this invention is to keep java in a row with all others functional oriented languages , like JavaScript . Lambda Expression is a concept of an anonymous function ( a function without name ), which wraps with the functional interface with its object creation.

Syntax of lambda Expression :

( arg1, arg2,......argN ) - > {  // No of statements }; 

It contains :
1. Zero or more number of parameters separated by comma within parenthesis.
2. -> is a token indicating lambda expression.
3. After -> contains one or more number of statements within curly braces.

Functional Interface :
It is an interface containing single abstract method only. It cannot contain more than one abstract method, but can have methods of Object class. Finally a functional interface can contain only one method or if it is containing more then one method then all others methods should be from Object class only.

For ex- Comparator interface of java.util package.

public interface Comparator {

  int compare(Object, Object); //Own method
  boolean equals(Object);     // From Object class

}

Comparison with Anonymous class
Anonymous class is also an expression. Anonymous class implementing single interface functions equally as compared to lambda expression, but considering writing code it looks unclear and little confusing.

 * Passing functionality as a method argument is not possible with the Anonymous class which is with the Lambda Expression.

 * With the Lambda expression we can able to pass functionality with the methods as a argument after the creation of instance for the functional interface.

 * No need to writing new operator for creating the instance of its functional interface, it is created internally by the JVM. But we need to do in case of writing anonymous class expression.

 * No need to override the abstract method of the functional interface because lambda expression is itself an method implementing the code for that abstract method. But need to override in the anonymous class curly braces.

Task performed by Lambda Expression
After declaring its expression, it basically perform two important tasks :

1. Creating the instance of functional interface to which it wraps and return the instance to its reference.
2. After executing the blocks within the parenthesis it returns the required value or void if not returning anything.

Note : Lambda Expression is an expression so it need to be assigned to the right side declaration statement which should be the reference of the functional interface because lambda expression first returns the instance of it.

Example showing Lambda Expression

public class Hello {

   interface hi{
 String display(); //abstract method with 
                            String return type
   }

   public static void main(String args[]){
  
      hi h= () ->{    //Start of Expression
     return "Lambda Expression"; //returns String
   };              //End of Expression

      System.out.println(h.display()); //Display the returned value
  
   }
}


Step of execution of the above example :

1. hi is the Functional interface.
2. Lambda expression wraps with the functional interface.
3. Creates the instance of interface " hi " .
4. Calls the display method.
5. After calling executes the Lambda expression and returns the String to the calling method " display ".
6. Print the returned value.

Note:
 * Arguments of the lambda expression depends on the abstract method present in the functional interface,otherwise give compilation error saying,

lambda expression's signature doesn't match the signature of functional interface method. 

* If Lambda Expression is having single statement then no need to writing curly braces.For ex :

() -> System.out.println("lambda expression");//Print string
() -> "lambda expession" ;       // returns String
() -> 10;                        // returns int value
  

* But if the single statement is a return statement then need to write within curly braces, otherwise produces      syntax error.

* Lambda Expression must return either required value or void.

* Lambda Expression doesn't have their own scope because it is just a method implementation.

What is SessionID?


Many users are interacting with the server and for each user a session is created in the server and it get identified uniquely by the SessionID. At the time of creation of session for each user a unique ID is generated by the Container which keep every user's session different from each other, is called as jsessionid.

How SessionID is managed internally?


To identify the request uniquely  from a particular client machine within its session, the SessionID is used .This ID is fed into the client machine in the  Cookies with the first response after session creation with other some other information like domain and server name.It comes with every request in the request header from the client machine and get matched with the jsessionid value present in the server. If it gets matched then it confirms that the request is valid for this active session, and if not matched then a new session is again created by the Container and again a new jsessionid created and returned back to the client machine with the response.

Note : 
*jsession is managed both by the client and the server. In the client machine it is stored in the cookie with the name jsessionid and at the server side also it is stored with the name jsessionid. 

*Request header carries the jsessionid information with every request.

*Response header carries the cookies which is having the jsessionid information with the first response after creating the session object. 

Cookies is the concept of storing the client's information in the client machine itself but in the form of a file called as Cookies. So it contains all the information sent by the Web server with the response header. previously all the required information of a client is managed, handled, kept and carried by the server itself. Now with the concept of Cookies all get stored in the client browser in the form a file. So in context of session tracking, session data is transmitted to the client machine and fed in the client browser as a Cookie with all other required information's like domain,server etc. So it makes it client dependent. Whenever a client sends request for a resource to a web server, the cookies having matching information of the requested domain and server also sent to the Web server as a request header so that the session will be maintained for the current active member.

Servlet API has a class named as Cookie which is used to store cookie information from a web server to client machine using addCookie() method. To do so we have to follow few steps.

1. Need to create cookie object with the argumented constructor.

Cookie ck = new Cookie(String, String);

name --> Represents name of the cookie.
value --> Represents value of the cookie.

2. Need to add Cookie in the response object.

res.addCookie(ck); 

Here, " res " is the HttpServletResponse object which is at the service() method of the servlet.

Note : Cookies class is present under the package javax.servlet.http. To get the cookies information from the request header we have a method i.e getCookie() which returns the array of cookie object (Cookie[] ) .

Advantages of cookie

1. It reduces the network traffic and reduces the server responsibility of managing client's information as well.

2. Cookies can able to maintain the client's data, which speed up the request processing.

Disadvantage of cookie 

1. Cookies can be disabled in the clients browser which makes it client dependent.

2. If user deletes the cookies then again session tracking would lead to the failure.

3. Cookies are still not secure, it can be steal using cookies stealing concept.

4. Due to the limited cookie size it cannot store large data's.


One of the major disadvantage with the URL Rewriting is that passing session data with the URL makes visible to every one who are requesting for the resource. To over come this problem the concept of hidden form field is introduced so that all the required session data can be able to pass to the requested resource without viewing to the user. Hidden field is one of the form element which is used to pass value keeping information abstract to the user. Hidden forms are not visible to the browser but it keeps the information secretly and can able to get the session data from the form fields using method getParameter(String).

Syntax of hidden form field :

<input type="hidden" name="sessioninfo" value="xxx"/>

We are getting the information present in the hidden text field by passing the string used in the name attribute i.e sessioninfo here to the getParameter(String).

Advantages with Hidden form field

1. It is possible with both POST and GET method type.
2. Information is not visible to the end user.

Disadvantages with Hidden form fields

1. Limited to the JSP ( supporting HTML form elements ), cannot be used with the servlet.

2. It is used in place of passing session data openly with the URL with the form submission .

3. Session tracking mechanism is not always possible only with the hidden form field. Somewhere hyperlinks are required which again follow the URL rewriting approach.

Note: It does not support full session tracking mechanism, but advantageous over URL rewriting.  
URL Re-writing is a technique by which session data can be handled within the server side only.Client is not responsible for keeping any information regarding session. In this process at every request the required session data is appended to the URL path to make the next request. All session information is retrieved by the web Server as a request parameter.

There is a way by which session data get appended to the URL path is by
1. Using Query String

Using Query String
A Complete URI is the combination of context path + Servlet path + path info . Query String is appended after Requested URI with the " ? " symbol containing name and value pair.

For example :
http://localhost:9999/myApp/loginServlet?name=xyz&pass=123&.........

In the above example is a complete URL under this,

localhost      ->  Server name
9999           ->  Port Number
/myApp       ->  Context path
/loginServlet ->  Servlet path
jsessionid="" -> Query String.

Value of jsessionid can be retrieved in the servlet  using the getParameter(String) method with the HTTP request object.

Note: Session ID is appended to the URI using the HTTP GET method request type, which allows to send small data with the request in the form of Query String and hence restricted to maximum 255 character. So with Query we are appending client's session information with every request to maintain the clients activity with each proceeding request.

This is how all the session data can be passed to a servlet/jsp with the URL using GET request type from a jsp page.

If we want to transfer the session data from a servlet to another using URL rewriting then we have to use hyperlink and append the same in the url using the " ? " symbol and can able to get the value using the getParameter(String) .

Advantage of URL Rewriting 

1. Doesn't depend on client to store client's session information.

Disadvantages of URL Rewriting

1. Every we need to pass the value as a query string produces heavy loads to the traffic.

2. Through GET method type maximum 255 characters are allowed to pass, it would not be possible it passing parameters exceeds 255 characters.

3. Visible with very request with the request URL. So it may cause security issue and hence not secure.

4. It works only when every page is dynamically generated that means cannot be possible with the html.

5. Passing jsessionid as a Query String needs some Javascript code to submit the form, otherwise it is not possible with the general form submission.

6. It is only possible with GET method type and hence cannot with POST method type.

7. very difficult to maintain the required session data with each proceeding request by the client.
Handling session defines how session should be managed internally. Session is meant for keeping track of user's information which is required further for the next proceeding requests. Scope of a session is alive from its creation till user finishes its consequent requests for a particular task. With the introduction of HttpSession interface session is get destroyed either by calling invalidate() or by setting the timer using setMaxInactiveInterval(int seconds). Session management is completely at the developer level, Servlet Container is not at all responsible for it. 

Session data can be handled or managed by following four way .

1. URL Re-writing.      --> To know more about URL Rewriting Click here
2. Hidden Form Field  --> To know more about Hidden Form Field Click here
3. Cookies                  --> To know more about Cookies Click here
4. HTTP Session         --> To know more about HTTP Session Click here

Step by step evaluation of each session tracking mechanism

At very first URL Rewriting technique was used to handle all the required session data by the client for the next consequent requests. With its many advantages and one of the major advantage of keeping the session data visible to the end users to the requested URL, next technique i.e Hidden Form field comes into existence which over comes the problem of keeping data visible but was only possible with the HTML form elements, cannot be used in servlet requesting for another servlet. Then a class is designed termed as Cookie which is capable of carrying session data to the client machine which reduces the server traffic, but was client dependent. All the session data was stored in the client machine in the form of a cookie. If by mistaken it gets  disabled or deleted then all the previous session data get destroyed, which is a big drawback. So to make it at the server side a new interface was designed i.e HttpSession which is capable of managing session data effectively using the session object. 

Both client and server having required information to track the session with every HTTP request over period of time with the use of HttpSession interface.

Note:
*Cookie  is a class and HttpSession is an interface.
*Internally, Web container is using cookie for storing the jsessionid generated with the creation of session object and uses URL rewriting for managing jsessionid in case if
   a. cookie is get disabled in the client's browser
   b. its get deleted from the client machine.

To know more about jsessionid --- > Click Here..!!



include() is a method defined in the RequestDispatcher interface with ServletRequest and ServletResponse as a parameter. It is same as forward with slight difference of storing the content of both source and target resource to the response object of the source servlet . Only matters is when we are calling include(), accordingly it adds the content to the response buffer and finally displayed to the browser. That means it dispatches the control to the target resource i.e servlet/jsp to include the processed data to the response object.

Signature of include()

include(ServletRequest, ServletResponse)

How to call include() method ?
It must be called with the RequestDispatcher object. And RequestDispatcher object is created by calling the getRequestDispacther() method by HttpServletRequest object. 


public void service(HttpServletRequest req, HttpServletResponse res) {

          ........
    RequestDispatcher rd = req.getRequestDispatcher("login.do"); 
    rd.include(req, res);

}

In the above code we are calling include with the RequestDispatcher object i.e "rd" and which includes the content of  "Login" servlet after processing the code of the service() method and returns the response object to the source servlet.




forward() is a method in RequestDispatcher interface which is used to dispatch the control from a servlet to another servlet/jsp. Container is responsible to dispatch the the control by finding the full path internally either with the context or request. But there is no full dispatch of control, after calling forward with the RequestDispatcher() object control will back to the source servlet. If we want to have full dispatch of control then we must go for sendRedirect(). By calling the forward() method some task is being forward by this method internally. Steps details of which are as under:

Task performed by forward() :

1. First check the response buffer whether data any exist or not. If exist and committed then gives the IllegalStateException and if exist and not committed then erase the existing data.

2. After checking response buffer, preparing path for the requested resource and adds the final path to the request attribute.

3. Then control dispatched to the requested source either a jsp or servlet by invoking the service() method of that servlet.

4. Pass the request and response object of the source servlet to the requested resource service() method as a parameter.

5. Process the code written in the service() method and then ready the response object with the final content from the requested source.

6. Finally returns the response to the RequestDispatcher.

7. RequestDispatcher will commit the response and then control back to the source servlet.

8. Finally that response must be returned to the browser to display the result of the request processing.

Note: Here the response object get committed by the RequestDispatcher object so writing the content further to the reponse in the source servlet will not be reflect. 

Here saying dispatching the control to the another servlet/jsp that means we are writing whole content of target servlet the source servlet response object and get displayed in the browser. 

Note : 
1. Writing any content to the response object before calling the forward will be erased if not committed. IF committed then throw IllegalStateException


2. Writing content to the response object after calling forward() method will not be written to the response object because it already get committed before by the RequestDsiaptcher. 

Why we are saying not completely dispatching the control to the target resource?
As source response object has full content of processed target resource without fully dispatching the control to the target servlet/jsp.

Limitation of forward()
From the above all statements we can conclude that source servlet is not capable of generating any response or cannot add any content to the response object before and after calling the foward(). This is the limitation of the forward(). 

Sevlet Attributes are the functionality given to have communication between servlet to servlet/jsp or jsp to servlet/jsp. Attributes can be used with the request object or session object, both are having different scopes of communication and stability for a web application. These attributes are implemented through two methods i.e setAttribute() and getAttribute(). In servlet we have basically two major scopes of communication i.e request and session. Both the methods are defined in the javax.servlet.ServletRequest and javax.servlet.http.HttpSession interfaces for request and session scope respectively.

Design of getAttributes()
getAttributes() is capable of storing information in key and value format. It is internally implemented using map concept.

setAttribute(String, Object)

key is represented in the form of string and must be unique.
value can be any object.

We can set the object using setAttribute() with the following two scope,
1. Request Attributes.
2. Session Attributes.

Request Attributes
Through the request attribute we are storing the value ( any object ) in the request object using the setAttribute(). It is used by the servlet for communicating with the other servlet and Jsp.

public void service(HttpServletRequest req, HttpServletResponse res){

         .......
   List<String> list= new ArrayList<String>();
   list.add("JAVA");
   list.add("CPP");
   req.setAttribute("NAME", list);

}

In the above example we are calling setAttribute() with the HttpServletRequest object and setting the value as a list object with the name as String value "NAME"

We can get the list object in the another servlet/jsp with the use of getAttribute(String) with the request object only by passing the string value which is used as a key in the setAttribute(). 

Note: getAttribute() returns the Object class object which must be type casted in the required form to access the value stored in the value of the setAttribute().

Session Attribute
It is same as the Request Attribute with only difference of storing procedure. Previously we stored list object in the request object , now in session Attribute we are storing the same list object in the HttpSession object. 

public void service(HttpServletRequest req, HttpServletResponse res){

         .......
   List<String> list= new ArrayList<String>();
   list.add("JAVA");
   list.add("CPP");
   HttpSession session=req.getSession();
   session.setAttribute("NAME", list);

}

In the above example we are calling the setAttribute() with the session object which internally storing the list object in the session object. 

We can get the value stored in the list from the session object by calling the getAttribute(String) with the session object and passing the String value which is used as a key in the getAttribute() method. 

public void service(HttpServletRequest req, HttpServletResponse res){

         .......
   
   HttpSession session=req.getSession();
   List<String> list=(ArrayList<String>)session.getAttribute("NAME");

}

As getAttribute() returns the Object class object so it must be type casted to the following object type in which the typed object is stored. 


We can get RequestDispatcher object with HttpServletRequest object by calling getRequestDispatcher(String url) and passing the url as a String paramter but its not mandatory to start with " / " as it was in case of ServletContext . In this case path is taken as relative to the request. Container id responsible to dispatch the control from one servlet/jsp to another jsp/servlet.

How container is getting the path internally ?
Internally container is getting the whole path from the request object and completes the request URI by getting and appending the url from the getRequestDispatcher(String url).

Two important points :

1. If we are writing "/ " before the url then container consider the path relative to the context and
2. If we are not writing " / " before the url then container consider the path relative to the request  and hence no chance of getting any exception in either case.

Summary: So if we are getting the RequestDispatcher object with Request object then its not mandatory to write " / " before the url .If we are writing then container take it as relative to the context and if not then taking relative to the request. 




We can get the RequestDispatcher object with the ServletContext simpley by calling getRequestDispatcher(String url) with the ServletContext object which finally returns the RequestDispatcher object. We have two possible options to dispatch the control after getting the object of RequestDispatcher by using include(req,res) and forward(req,res). 

We must mention the resource to which control has to be dispatched as a String parameter in getRequestDispather(String url) method  but should be start with " / " otherwise container throws IllegalArgumentException.

Why should be start the resource name with " / " ?
It is because we are getting RequestDispactcher object with ServletContext and which follows the context path. For any Servlet Application its context path is always web apps. So for the requested resource container always takes the path relative to the context. So its mandatory to mention " / " before writing url otherwise container will throw IllegalArgumentException.



If we are not writing " / " then container always search for the requested resource under the context path ( i.e web Apps ) which can never be possible because our all the resources are available under the web content folder.

A diagrammatic representation showing what is a context path


From the above directory structure let consider,
Current Resource - home.jsp
Requested Resource - login.jsp

Container always consider the relative path for the requested resource as context path in case of getting RequestDispatcher object with ServletContext that means dispatch must be with the context path. 
So here the context path is " /Application 1 ".

By writing " / " container understands that the requested resource is not in the current directory i.e here Application 1 , then search in the relevant directory either Web-content or src folder if request resource is a html/jsp or servlet respectively. 

To know about RequestDispatcher with Request object. 
RequestDispatcher is an interface which has two important abstract methods defined.
1. include()
2.  forward()
Both the methods are used to delegates the control
from one Servlet to another Servlet / JSP or
from one JSP to another JSP/Servlet .

How to create object of RequestDispatcher ?
This can be achieved in two ways:-

1. With HttpServletRequest object : It can be created by calling getRequestDispatcher(String resourceName) method  by HttpServletRequest object.

public void service(HttpServletRequest req,HttpServletReponse res){
    
           ......
    RequestDispatcher rd= req.getRequestDispatcher("xxx.jsp");

}

To know more about this click here..!!

2. With ServletContext object : It can be created by calling getRequestDispatcher(String resourceName) method by ServletContext object.

public void service(HttpServletRequest req,HttpServletReponse res){
    
           ......
    ServletContext ctx= this.getServletContext();
    RequestDispatcher rd= ctx.getRequestDispatcher("xxx.jsp");

}

To know more about this click here..!!

The above two ways will create the object of RequestDispatcher. To dispatch the control we need to call either include(req,res) or forward(req,res) with RequestDispatcher object. 

Note : To know the difference between getting RequestDsipatcher object with HttpServleRequest and ServletContext , Click Here..!!

Signature of forward(req,res) 

public void forward(ServletRequest req,ServletReponse res)
                        throws ServletException, IOException {
   
}

Forward() method has two parameter of ServletResquest and ServletResponse but we are storing HttpServletRequest and HttpServletResponse object as a parameter. 

It is possible because internally HttpServletRequest extends ServletRequest which means we can able to wrap HttpServletRequest object to ServletRqeuest reference.  This is same with HttpServletResponse and ServletResponse.

public abstract interface HttpServletRequest extends ServletRequest {  

}

Signature of include(req,res)

public void include(ServletRequest req,ServletReponse res)
                        throws ServletException, IOException {
   
}

Include() has same signature as forward() method has. Difference is with the operation.

Note : To know the difference between using include() and forward(),  Click Here..!!
In servlet we are getting the session Object in terms of HttpSession by calling getSession() method with the HttpServletRequest object.

What is a session ?
Session is a object which uniquely identifies the active user so that each activity of that user can be traced or identified internally with the session object. here in servlet we are achieving this by creating HttpSession object.

Important points regarding HttpSession

1. It is created by calling getSession() with HttpServletRequest object.
2. Its scope is till we call invalidate() method or set the timer by calling setMaxInactiveInterval(int val).
3. Session Object is handled by developer only, container is not responsible for creating and destroying.
4. Session uniquely identifies active users.
5. Every active is get stored in the session object of that user.
6. By creating HttpSession object a sessionID is generated by the container which fed in the client browser in the form of cookie with the first response after creating httpSession object.
7. SessionID is responsible to identify the particular request from a particular client machine.
8. SessionID is managed internally by the container only.

How to create Httpsession Object?
It is created by calling getSession() with HttpServletRequest object.

protected void service(HttpServletRequest req, HttpServletResponse res) {
    
             .....
    HttpSession session=req.getSession(); //Session Created

}

We are calling with the HttpServletRequest object because getSession() is defined in it.

How to destroy HttpSession object?
It can be destroyed by two ways :-

1. Explicitly by calling invalidate() with the HttpSession object.

HttpSession session=req.getSession(); //Session created
        .......
session.invalidate() // Session Destroyed

 2. Implicitly by calling setMaxInactiveInterval(int val) with HttpSession object. It works as the timer that means if a user will be inactive for the time specified as its parameter then the Session will be destroyed automatically.

HttpSession session=req.getSession(); //Session created
        .......
session.setMaxInactiveInterval(int val) //Time set for Inactive 
                                        period of active member. 

How to get the SessionID?
We can get the sessionID which is internally created by the container with the creation of HttpSession by calling getId() which is defined in the HttpSession interface as a abstract method and returns Id as a string. 


HttpSession session=req.getSession(); //Session created
        .......
String id = session.getId(); // Getting SessionID

How to set the values/list object in the Session object?
It can be done by using the setAttribute(String , Object) which stores the information in the key and value format.
1st parameter is string which acts as a key an can be any user-defined string.
2nd parameter is a object which acts a value which we want to store in the HttpSession object. 


HttpSession session=req.getSession(); //Session created
        .......
List<String> list= new ArrayList<String>();//list Object
list.add("JAVA");
list.add("C");
list.add("PHP");
session.setAttribute("NAME",list); //List object is stored in 
                                     the session with Key "NAME" 

Again list object can be retrieved from the Session object by calling setAttribute(String) with the HttpSession Object and passing the key as a parameter.

HttpSession session=req.getSession(); //Session created
        .......
List<String> = (List<String>)session.getAttribute("NAME");
                            //Retrieving list Object from 
                               Session object

Note: Need to typecast because getAttribute() returns Object class object.
          Session is used to uniquely identifying active user
          SessionID is used to uniquely identifying request coming from particular client machine. 



ServletContext object is common to all the servlet but ServletConfig object is different for all the servlets and must be created at the time of container start-up for every Servlet. ServletConfig object of one servlet is abstract from ServletConfig object of another servlet.

Important points regarding ServletConfig object

1. It is once created for every servlet designed in the Application at container start-up.
2. init() life cycle method is responsible for initializing ServletConfig object.
3. Container is responsible for calling init() and is the first life cycle method to be called at the container start-up.
4. Initializing value must be mapped in the web.xml under particular < servlet > tag with < init-param > tag.
5. < param-name > and < param-value > tag is used to provide initializing value for ServletConfig instance.
6. We can have more than one servletConfig object in a single web Application.

How to get the ServletConfig Object ?
It is possible with the help of getServletConfig() method which returns ServletConfig object.

How do we get control over ServletConfig object in our Servlet class?
This can be possible in one ways :

1. With current servlet class Object : By calling getServletConfig() method.

ServletConfig config = this.getServletConfig() ; 

Note : getServlteConfig() method is defined in the abstract class GenericServlet which is extended by HttpServlet. And our Servlet class also extends HttpServlet that means our servlet class is indirect sub-class of GenericServlet class and hence its method can be accessible with its Object.

How to initialize ServletConfig object with some values?
It should be done at web.xml file under <  init-param > tag using < param-name > and < param-value > and shouble be mapped with particular servlet  under < servlet > tag and hence will be specif to that servlet only.

How to get the < init-param > value ?
We can get through getInitParameter() method which is defined in the ServletConfig interface so can be called by its sub-class object.

Note : Not recommended to override init(ServletConfig config) method because it is internal call by the container to initialize ServletConfig instance with the mapped value in the web.xml under < init-param > tag.


ServletContext is only a single object to a whole Servlet Application. It is once created and initialized by the web container at the container start-up.

A Web application has many Servlet classes and for every servlet there is common object called as ServletContext. So if we have the requirement to have some common service between those servlets then we can be able to provide by initializing ServletContext object with < context-param > tag in the web.xml and hence can be accessed with any of the Servlet instance or ServeletConfig object.

About ServletContext interface

ServletContext is a interface defined in the servlet-api which has many methods defined and can give any required informations about a Servlet Application.

Context object is created by the web container so how we can get this object in our servlet class?
By calling getServletContext() method by our own defined servlet object or ServletConfig object.

1. With ServletConfig Object -->  Our Servlet class extends HttpServlet class which internally extends GenericServlet which implements Servlet and ServeletConfig  interfaces. And ServletConfig has getServletContext() method.

ServletConfig config = this.getServletConfig();
ServletContext ctx = config.getServletContext();

2.  With our own Servlet Object --> This can be achieved by calling getServletContext() method with " this " keyword.

ServletContext ctx = this.getServletContext();

3. With HttpSession object --> This can be done by calling getServletContext() with HttpSession object.

HttpSession session = request.getSession();
ServletContext ctx = session.getServletContext();


How to initialize ServletContext with some values ?
It should be done at the web.xml file under < context-param > tag using  < param-name > and < param-value > but should not be under < web-app > because it is common to all the servlet so must be mapped globally. 

<context-param>
    <param-name>   </param-name>
    <param-value>  </param-value>
</context-param>

< param-name > contain any logical name. 
< param-value > contains value initialized to ServlteContext Object.  




There are many task happening internally inside the Web-Server. Following are the list of task performed at the container start-up :

1. Reads the web.xml file or Annotations specified on various web components and stores all the required information in the main memory.

2. Container creates the ServletContext object and initialized with ServletContext object parameter specified in the web.xml file.

3. Thread Pool will be created by the container.

4. All the listener will be initialized.

5. All the filter will be initialized.

6. Checks whether any servlet is configured with < load-on-startup > tag must be loaded first and the instance will be created by calling the default constructor.
    For ex: Servlet confiured with < load-on-startup > value ' 1' is loaded first.

7. If no < load-on-startup > tag is mentioned then loads the servlet class when request will come.

8. Container creates the ServletConfig object and initialized it with the ServletConfig parameter specified in the web.xml file or Annotation.

9.  ServletConfig object will be initliazed with the ServletContext object.

10. Finally after creating all the instance and initialization the ServletLife cycle method will be called by the container and first to call is init() by passing ServletConfig instance as parameter.

Note : 

* Init() method is internally called by the container to initialize the ServletConfig instance with the required parameters.

* If any of the process failed before loading and initializing the servlet class then class will not be loaded and initialized.



After developing Servlet Application we need to deploy and run our application at theWeb-Server. When a Web-server starts it internally starts a web-container which is also termed as servlet container. 

What is a web-container ?
A web-container is nothing but a simple java program which is used to delegate the incoming request from the browser to the respective Servlet Object running inside a web-container. 

Originally a request from the client machine(web browser) comes to the web-server which is capable of handling static pages request and for generating dynamic page a Servlet Object is responsible which runs inside a web-container , so after receiving the request by the web-server it forwards to the web-container and then from a web-container to the respective Servlet Object for dynamic page generation and finally to the clients machine as a display to the web browser. 


                              ( Diagram showing how request follows from client to web-container)

What is the use of web container?
It is used to delegate the incoming request to the servlet object running inside the web-container to process the request and generate the dynamic content.

What are the limitations with the Web-Server?
Web-server is only capable of forwarding the static page only in response to the client machine. For processing the the request and generating the dynamic page we need to have a web-container inside a web-server.

How the Servlet instance created and what happened at the container start up. To know about the thing happens at the container start-up click here..!!


Life Cycle of Servlet starts when a servlet application get deployed in the web server. Web container is responsible for calling all the life cycle methods. Servlet has following three life cycle methods :

1. init()
2. service()
3. destroy()

init() method :  init() is the first method to be called in every servlet application. It is a parametrized method with ServletConfig reference as a parameter. When the servelt application is been deployed and run in the web server then a servletConfig object is created by the web container and this is once created at the container start-up only. It must be initialized with ServletConfig parameter mentioned in the web.xml file with the < init-param > tag .
So instance of ServletConfig is created at the container start-up and initialized by calling init() method with the ServletConfig parameter which is mapped in the web.xml file using < init-param > tag.

<init-param > tag has sub-tags < param-name > and < paran-value > .

< param-name > is a logical on basic of which value can be retrieved by hard-coding the name as a string in the following method.

getInitParameter(String paramName)
< param-value >  SevletConfig instance get initialized with the value mentioned in this tag. 

Why we are configuring < init-param > tag in web.xml ?

It is because SerlectConfig object is created once at the container start-up so value must be passed in the web.xml file so it must be read and initialized to the ServletConfig object at the container start-up.

Syntax of init() method :

 public abstract void init(ServletConfig sc)  throws ServletException 

It is the abstract method declared in servlet interface and overridden in GnericServlet class which implements servlet interface and finally GenericServlet class is extended  by HttpServlet class which we are extending with our java class.

Note: We must not override because it is internally called by the container to initialize the ServletConfig instance with the ServelConfig parameters.

service() method : service() method is the method we override in the our servlet class to get the control of HttpServletRequest and HttpServletResponse to handle the request from client and processed to get ready the response and store the required information in the HttpServletResponse object to get displayed in the JSP page.
So we need to override to have our own implementation of processing the client request by connecting with database. It may be retrieving ,storing or editing to the database.

Syntax of service() method :
protected void service(HttpServletRequest req, HttpServletResponse resp)                                                                       throws ServletException, IOException

This is the method we are overriding from HttpServlet class.


Servlet is a web technology, which is used to develop web application. It is used to process the HTTP request by the client. Servlet was first introduced by the Sun MicroSystems with released of  version 1.0 in 1997.
Now in 2013 its recent release is with version 3.1.
First Annotation concept introduced with the release of version 2.5

Previously CGI ( Common Gateway Interface ) was used for request processing and to generate dynamic context. But it has many limitations like platform dependency which is overcome with the introduction of servlet which is simply a java class and solves the platform dependency problem. 

Servlet is capable of understanding, handling and processing the different ' requests ' requested by the client where client is nothing but the browsers. So servlet forms the bridge between the client and server so that communication can take place effectively through HTTP protocol. Due to request handling and processing Servlet stands at Controller Layer.


Complete Request Processing

A request is done by the client to the server where servlet is running which handles the request, get processed, interact with the database if required and finally stores the requested information in the response object which is displayed in the JSP.  

* To run and deploy Servlet we need a web container which is also called as the servlet container responsible for managing the life cycle of Servlet, mapping the requested URL to the particular servlet. 

   
( Diagram showing how request processed by Servlet and present the response to Browser )

Servlet API is provided by server vendors. Java Vendor has implemented some of the interfaces required and its sub-classes are written by the server vendors in the servlet API. So finally the server we are using must have their own implemented servlet-api. 

How do we call a Java class as Servlet class?

A simple java class extending the javax.servlet.http.HttpServlet class which has parametrized service method with HttpServletRequest and HttpServletRespons as the parameters.

To know about Servlet Life Cycle   click here . 

  1. Model
  2. Scope
  3. Controller
  4. View
  5. Services
  6. Data Binding
  7. Directives
  8. Filters
  9. Validation
  10. Testing

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic