SERVLETS

1)What is Servlet?

Servlet is a web technology, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request-response paradigm.

2)What is the functionality of Servlet?

Receives request from client(In the form of HTTP request).Extract some information from the request.Create and send response to client (In the form of HTTP response) or forward the request to another servlet or JSP page.


3)What is Servlet Container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME(Multi-Purpose Internet Mail Extensions) -based requests, and formats MIME- based responses. A servlet container also contains and manages servlets through their lifecycle.

4)Explain hierarchy of servlet?

->Servlet is the base interface for all the servlets.It contains 5 method.init,service,destroy methods are callled as lifecycle methods of Servlet and called by web container.(all methods are abstract methods)
->GenericServlet is a abstract class which implements Servlet interface and it provides implementation for init and destroy method.But still service method is abstract method.
->HttpServlet is a abstract class which extends GenericServlet and it provides implementation for all the lifecycle methods ,also this class have two more methods i.e doGet and doPost.
->Whenever we want to write a any servlet class,that class should extends HttpServlet or GenericServlet classes.

Servlet(interface)
.
.
GenericServlet(abstract class)
.
.
HttpServlet(abstract class)
.
.
UserDefinedServlet class


5)What are the important packages belongs to Servlets?

For developing servlet applications we use the following two packages.

1.javax.servlet.*;
2.javax.servlet.http.*;


6) Explain why HttpServlet is declared abstract?

The Constructor HttpServlet( ) does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.

Usually one of the following methods of HttpServlet must be overridden by a subclass:
doGet: if the servlet supports HTTP GET requests
doPost: HTTP POST requests
doPut:HTTP PUT requests
doDelete: HTTP DELETE requests
init and destroy to manage resources getServletInfo to provide information .

However, there doesn’t seem to be any reason why the service method should be overridden because it eventually dispatches the task to one of the doXXX methods

7)Explain servlet life cycle?

A servlet life cycle can be defined as the entire process from its loading/initializing till the destroying the servlet.

The following paths are followed by a servlet.
· The servlet is initialized by calling the init () method.
· The servlet calls service() method to process a client's request.
· The servlet is terminated by calling the destroy() method.

8)who is responsible for creating an object for servlet?

Web Container.

9)when servlet object is created?

At the time of first request.

10)shall we write a constructor instead of init() method in Servlet?

Yes,We can write.But we cannot use it instead of init() method.
First thing is that the constructor of the servlet is called by the container, We cannot call it. So we cannot add anything into the constructor.Moreover, at that time, it is just another java object not a servlet.So it cannot have any servlet specific parameters,like ServletConfig , which we can use.
e.g:
for every request from the client, the servlet has to look into the database(or something of that sort),so we have to set up the database connection set-up,login etc. for every request.
We have to make the servlet ready to have a connection to the database/resource before any client requests come.
How can we do it?Sure,it cannot be put in the constructor.
The init() method has access to the ServletConfig,ServeltCOntext,which can be used for similar purposes,for example, use ServeltContext to get database name,login name,etc.. (that are defined in xml's...)..


11)Difference b/w GET and POST methods?

GET:
• Limited data can be sent,because In GET the entire form submission is encapsulated in one URL.
• The data gets submitted as a part of URL.
•We can send the data into the URL lessthan 2k of parameters.Some servers to handle 64k.

POST:
• Large amount of data can be sent because In POST the data is submitted in the body of HTTP request.
• The data is not visible on the URL and it is more secure.
• 8Mb maximum size for the POST()


12) When init() and Distroy() will be called ?

init() is called whenever the servlet is loaded for the first time into the webserver. it performs certain one time activities which are required during the lifetime of the servlet. It may be some initialization of variables or a database connection.

destroy() will be called whenever the servlet is removed from the webserver. Various resources which are held by the servlet will be released,database connections which were opened will be closed.Later the servlet is destroyed.


13)What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher() ?

request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource.
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

14)What is the difference between ServletContext and ServletConfig ? 

ServletConfig:
One ServletConfig Object is created per servlet.
It can be used to access ServletContext.

ServletContext:
One ServletContext will be created per web application.
Can be used to access web app parameter.


15) How do servlets handle multiple simultaneous requests ?

The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method
e.g:
doGet(),doPost( ) and service( ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

16)What is the use load on startup (load-on-startup tag) in Servlet ?

" lazy loading " means is that servlet is NOT loaded by container on startup.
Servlet in this case is loaded on the first client request - so the first client can experience poor performance.
" Eager loading" means that the servlet is initialised on container startup.
If there are two servelts A & B with values 0 & 1 then it means that Servlet A ( having value = 0 ) will be loaded first.
So if there are more than one servlet this element specifies the order of loading - lower integer values ( including zero ) are loaded first.
If you specify this element but do not provide the value - even then the servlet will be the first servlet that gets loaded
To ensure that servlet follows " lazy loading " - do not provide this entry at all in web.xml file OR provide a negative number.


17)If a servlet is not properly initialized, what exception may be thrown ?

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

18)What is the purpose of RequestDispatcher?

RequestDispatcher interface provides the facility of dispatching the request to another resourse like html,servlet,jsp etc.This is also be used to include the contents of another resource.

19)is it possible to call jsp from servlet?

Yes,By using RequestDispatcher interface.

RequestDispatcher rd=request.getRequestDispatcher(“/xxx.jsp”);
rd.forward(req,res);

20)Why don't we write a constructor in a servlet? 

Container writes a no argument constructor for our servlet.

21)When we don't write any constructor for the servlet, how does container create an instance of servlet? 

Container creates instance of servlet by calling Class.forName(className).newInstance().


22)Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time? 

Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.

23)What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext? 


We can give relative URL when we use ServletRequest and not while using ServletContext.


24) what is servlet collaboration?

Communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method .
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods

24)What is the diff b/w include() and forward() method ?

forward():-
In case of forward() method only destination servlet response is sent to the client,But the response of sourse servlet cannot be sent.
Include():-
In case of include() method response of destination servlet is included in the respose of sourse servlet then that is being sent to the client.

25)Is Servlets thread-safe ?

Servlets are not thread safe. If you want to make Servlet as Thread safe, you can implement SingleThreadInterface.

There are two different ways of making a servlet thread safe namely

1. By implementing SingleThreadModel: By implementing a SingleThreadModel it will be possible to create a Thread safe servlet.There can only be one user at a given point of time.
2. Synchornize the part of sensitive code: We can allow a single user at a given point of time by making that part of the code which is sensitive as synchronized.

26)What is the difference between Server and Container ?

A server provides many services to the clients, A server may contain one or more containers such as EJB containers, servlet/jsp container. Here a container holds a set of objects.
Container refers to the component that manages lifecycle of servelet/JSP or EJB. Server refers to the infrastructure which contains those containers.


27)what is the diff b/w forward() and sendRedirect() methods?

-> forward() method belongs to RequestDispatcher interface,where as sendRedirect() method belongs to HttpServletResponse interface.
->forward() method sends the same request to other resource,where as sendRedirect() method sends new request always because it uses the URL bar of the browser.
->forward() method works at server side,where as sendRedirect() method works at client side.
->forward() method works with in the server side,where as sendRedirect() method works within the server and outside the server also.

28)what is Session Tracking?

Session means time period b/w login and logout i.e particular interval of time.Http is stateless protocol i.e each time user request to the server,then server treats the request as a new request.So we need to maintain the state of the user to recognize particular user.

29)In web.xml file 1 is defined between tag means?

Whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this 1startup> is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request.

30)What are the session tracking mechanisms?


1.Cookies.
2.URL Rewriting.
3.Hiddenform Fields
4.HttpSession

31) in your project where you used session management techniques?


· To remember the password of certain account on a specific computer.
· To identify the user during an e-commerce session of online shopping website
· To customize the look of a web site according to user choice.
· While working with direct advertisements in web site development hidden form fields
· An invisible textbox available in a html form is called hidden form field

32) How can you create Session Object ?

First way :

1.public HttpSession getSession();

Example : HttpSession session = req.getSession();
First it checks is there any session object is already associated with this request or not.
If it is available then this method returns exiting session object instead of creating new one.

Second way :

public HttpSession getSession(boolean b)

If the argument is true, then this method acts exactly same as getSession().
if argument is “false”,If the session is available then this method returns exiting session otherwise it returns null.


33) what are the ways to invalidate the session ?

We can invalidate a session by using the following two ways


1.By Invalidate method:
HttpSession interface defines the following methods to invalidate a session whenever it is required.
public void invalidate()

2.By Time-out mechanisam:
If we are not performing any operation on the session object for a predefined amount of time. Then session will be expire automatically .This predefined amount of time is “ Session time out “ or “max inactive Interval”.

3.Configuring session Time-out at Server Level.
Most of the web servers provides default support for “session- time-out”. And mostly it is 30 minutes. We can change the values by server level configuration changes.


34)In which of the following cases session will be expired immediately?


1.session.invalidate(); ------>session expires immediately.
2.session.setMaxInactiveInterval(-10)
3.session.setMaxInactiveInterva(0);----->session expires immediately.



35) What are the disadvantages in session tracking ?

Data secrecy is not there because hidden fields data can be viewed using view -> source option of browser software.
When multiple dynamic forms are there in the application then lot of hidden fields will travel over the network .Due to cause of this network traffic between browser and server will be increase.

36) can you explain about cookie ?

1. Cookie is a small amount of information (key,value). which is created by server and send to the browser (in response object). Browser retrieves that cookie from the response and stores in the local files system.
2. broswer sends those cookies with every consecutive requirement to the server. By accessing those cookies , server can able to remember client information across multiple requests.
3. To exchange cookie between client and server can be done using setCookie() response Header and cookie request header.
4. exchanging session id .In both cases we have to depends on set-cookie response header and request header.

37)What is servlet lazy loading?

A container doesnot initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
->The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
->The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

38)What are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
· Security checks
· Modifying the request or response
· Data compression
· Logging and auditing
· Response compression

Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

Comments

Popular posts from this blog