October 04, 2016

JSP Servlet Interview Questions and Answers

What is called servlet container?
A servlet container is a part of Web server that provides network services depends on request and response are sent, MIME based requests and responses. It contains and manages servlets through their life cycle.



What is the difference between Server and Container?
A server can provide service to the client and it contains one or more containers such as EJBs, Servlet, JSP containers. Containers hold set of objects.

Why HttpServlet class is declared abstract?
HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because there is no implementation logic in service methods such as doGet() and doPost() and we should override at least one of the service methods. That’s why there is no point in having an instance of HttpServlet and is declared abstract class.

What are the functions of Servlet container?
1. Lifecycle management : Managing the lifecycle events of a servlet like class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
2. Communication support : Handling the communication between servlet and Web server.
3. Multithreading support : Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.
4. Declarative security : Managing the security inside the XML deployment descriptor file.
5. JSP support : Converting JSPs to servlets and maintaining them.

What is the difference between JSP and Servlets?
  • JSP is a webpage scripting language that can generate dynamic content. Where as Servlets are Java programs that are already compiled which also creates dynamic web content.
  • JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets.
  • It’s easier to code in JSP than in Java Servlets.
  • In MVC, jsp act as a view, where as servlet act as a controller.
  • The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.
  • JSP supports HTTP protocol which mainly used for presentation. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

Which interface should be implemented by all servlets?
Servlet interface should be implemented by all servlets.

What is the difference between HttpServlet and GenericServlet in Servlet API?
GenericServlet provides framework to create a Servlet for any protocol e.g. you can write Servlet to receive content from FTP, SMTP etc, while HttpServlet is built-in Servlet provided by Java for handling HTTP requests.

What is life cycle of Servlet?
The Web container is responsible for managing the servlet’s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in ready state to service requests from clients.

The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool.

Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
When servlet is loaded?
1. First request is made
2. Auto loading and Server starts up
3. There is a single instance that answers all requests concurrently which saves memory
4. Administrator manually loads.

When Servlet is unloaded?
1. Server shuts down
2. Administrator manually unloads

What is difference between GET and POST method in HTTP protocol?
1). GET method passes request parameter in URL String while POST method passes request parameter in request body.
2). GET request can only pass limited amount of data while POST method can pass large amount of data to server.
3). GET request can be bookmarked and cached unlike POST requests.
4). GET is mostly used for view purpose (e.g. SQL SELECT) while POST is mainly use for update purpose (e.g. SQL INSERT or UPDATE).

Can you override service method in servlet?
Yes. When we override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method.

When a request is made, the Sun Java System Web Server hands the incoming data to the servlet engine to process the request. The request includes form data, cookies, session information, and URL name-value pairs, all in a type HttpServletRequest object called the request object. Client metadata is encapsulated as a type HttpServletResponse object called the response object. The servlet engine passes both objects as the servlet's service() method parameters.

The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, GET, and so on). For example, HTTP POST requests are routed to the doPost() method, HTTP GET requests are routed to the doGet() method.

This enables the servlet to perform different request data processing depending on the transfer method. Since the routing takes place in service(), there is no need to generally override service() in an HTTP servlet. Instead, override doGet(), doPost(), and so on, depending on the expected request type.

The automatic routing in an HTTP servlet is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In a Sun Java System Web Server, request data is already preprocessed into a name-value list by the time the servlet sees the data, so simply overriding the service() method in an HTTP servlet does not lose any functionality. However, this does make the servlet less portable, since it is now dependent on preprocessed request data.

Override the service() method (for generic servlets) or the doGet() or doPost() methods (for HTTP servlets) to perform tasks needed to answer the request. Very often, this means collating the needed information (in the request object or in a JDBC result set object), and then passing the newly generated content to a JSP for formatting and delivery back to the client.

How can we create deadlock condition on our servlet?
Call doPost() method inside doGet() and doGet()method inside doPost().

Can you declare constructor inside Servlet class?
Yes, Servlet can have Constructor, but it's not the right way to initialize your Servlet. You need to use the init() method provided by the Servlet interface to initialize the Servlet correctly.

A servlet container creates a pool of multiple Servlets to serve multiple clients at the same time. They instantiate Servlet by calling the default no-argument constructor and suppose you have declared another constructor which takes a parameter e.g. LoginServlet(String username), than Java compiler will not add the default no-argument constructor and Servlet container will not able to initialize the Servlet. That's why it's important not to provide a constructor in Servlet, but if you do, make sure you also add a default constructor there for Servlet container.

When developer declared a parameterized constructor, default constructor is not added ( Java compiler doesn't add default no argument constructor, if there is a parametric constructor present in class), and if Servlet container e.g. Tomcat tries to instantiate a Servlet in order to serve the first request from client, it will throw "java.lang.InstantiationException: LoginServlet"

For initializing a servlet can we use a constructor in place of init()?
No, we can not use constructor for initializing a servlet, because a Servlet require ServletConfig object for initialization which is created by container as it also has reference of ServletContext object, which is also created by container.

Why super.init(config) is the first statement inside init(config) method?
This will be the first statement if we are overriding the init(config) method, by this way we will store the config object for future reference and we can use by getServletConfig() to get information about config object. Without doing this if we call the ServletConfig method will get NullPointerException.

What happens if you call destroy() from init() in java servlet?
The destroy() gets executed and then the servlet initialization gets completed. Ideally destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? Well the answer is NO, it will not.

destroy() method is not supposed to and will not destroy a java servlet. The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues.

What is a filter, and how does it work?
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource (from the Servlet or JSP before sending it back to client), or both.

Filters improve reusability by placing recurring tasks in the filter as a reusable unit. A good way to think of Servlet filters is as a chain of steps that a request and response must go through before reaching a Servlet, JSP, or static resource such as an HTML page in a Web application.

The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and the response, site hit count etc. The filters are configured through the web.xml file as follows:

< web-app >
< filter >
< filter-name >TestCountFilter< /filter-name >
< filter-class >test.TestCountFilter< /filter-class >
< /filter >
< filter-mapping >
< filter-name >TestCountFilter< /filter-name >
< url-pattern >/TespApp/*< /url-pattern >
< /filter-mapping >
...
< /web-app >


What are the important functions of filters?
  • Security check
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
What is the significance of load-on-startup tag in web.xml?
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. If < load-on-startup > 1 < /load-on-startup > is defined inside < servlet > < servlet >, then the servlet for which we have defined this tag will be initialized in starting when context is loaded before getting any request. It is called pre-initialization.

What is JSP?
JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code.

While Java Servlet technology is capable of generating HTML with out.println("< html >...< /html >") statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

Explain the life cycle methods of a JSP?
  • Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
  • Translated: The JSP file has been translated and compiled as a Servlet.
  • Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
  • Servicing: Services the client requests. Container calls this method for each request.
  • Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method. 
What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

What is the _jspService() method?
The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects. Below are the implicit objects available in JSP:
request, response, pageContext, session, application, out, config, page, exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

How do you get ServletContext reference inside Servlet ?
Its easy to get reference of ServletContext in jsp using application implicit variable, but in Servlet is not available in HttpServletRequest until version 3.0. We need HttpSession object to retrieve ServletContext in any Servlet.

What is difference between ServletContext and ServletConfig in Java?
Both ServletContext and ServletConfig are basically configuration objects which are used by servlet container to initialize various parameter of web application. But they have a difference in terms of scope and availability.

ServletConfig : Its an interface in Servlet API and ServletConfig object represents or used to initialize single servlet in web application by servlet container. Inside deployment descriptor known as web.xml, we define Servlet initialization parameter related to that servlet inside < init-param> tag. Its a set of name /value pair. By using ServletConfig and combination of init-param you can configure any Servlet in J2EE environment.

ServletContext: It is even more important than ServletConfig and its one per web application, also known as Context. This object is common for all the servlet and they use this object to communicate with the servlet container to get the detail of whole web application or execution environment important thing to remember is, it represents a web application in single JVM.

By using ServletContext object you can share objects to any Servlet or JSP in whole web application.

Difference:
1. ServletConfig object represent single servlet, where as ServletContext represent whole web application running on particular JVM and common for all the servlet.
2. ServletConfig is like local parameter associated with particular servlet. ServletContext is like global parameter associated with whole application.
3. ServletConfig is a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope. Where as ServletContext has application wide scope so define outside of servlet tag in web.xml file.
4. getServletConfig() method is used to get the config object and getServletContext() method is  used to get the context object. 
How to set the context amd config parameters in web.xml?
To set config parameters:
< servlet >
     < display-name >GermanLogisticsServlet< /display-name >
     < servlet-name >GermanLogisticsServlet< /servlet-name >
     < init-param >
         < param-name >City< /param-name >
         < param-value >Kempten< /param-value >
     < /init-param >
< /servlet >


To access config parameters : getServletConfig().getInitParameter("City");

To set context parameters:
< web-app >
    < context-param >
        < param-name >Country< /param-name >
        < param-value >Germany< /param-value >
    < /context-param >
< /web-app >


To access context parameters in a JSP or Servlet : getServletContext().getInitParameter("Country");

How can you get the information about one servlet context in another servlet?
In context object, we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet.
Context.setAttribute ("logincontext", "value");
Context.getAttribute (logincontext);

What are JSP directives?
JSP directives are messages for the JSP engine. i.e. JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page. They are used to set global values such as a class declaration, method implementation, output content type, etc.

They do not produce any output to the client. Directives are always enclosed within < %@...% > tag. e.g: page directive, include directive, etc.

In short, The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives: page, include, taglib. 

What is page directive?
page directive provide attributes that gets applied to the entire JSP page.
A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Typically, the page directive is found at the top of almost all of our JSP pages.

What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL. The following directive displays myErrorPage.jsp when all uncaught exceptions are thrown:
< %@ page errorPage="myErrorPage.jsp" % >

isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP. The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false. For example, the myErrorPage.jsp sets the isErrorPage option to true because it is supposed to handle errors:
< %@ page isErrorPage="true" % >

import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.

< %@ page import="java.sql.*" % >

To import multiple packages you can specify them separated by comma, e.g: < %@ page import="java.sql.*,java.util.*"  % >

info attribute lets you provide a description of the JSP. The following is a coding example:

< %@ page info="This JSP Page Written By K Himaanshu Shuklaa"  % >

isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0

The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.

< %@ page isELIgnored="false" % >

How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
JSPs can be thread-safe by having them implement the SingleThreadModel interface. This is done by adding 'isThreadSafe' in the the page directive, e.g:

< %@ page isThreadSafe="false" % >

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, we will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized.

We can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for our JSP engine.

What is the include directive?
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.

Include directive has only one attribute called file that specifies the name of the file to be included. The syntax of the include directive is: < %@ include file = "FileName" % >

The FileName in the include directive is actually a relative URL. If you just specify a FileName with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.

What is taglib Directive?
The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.

The taglib directive has a syntax: < %@ taglib uri="uri" prefix="prefixOfTag"  >

Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.

What are the JSP standard actions?
The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client. They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
  • jsp:include :- Includes a file at the time the page is requested
  • jsp:useBean :- Finds or instantiates a JavaBean
  • jsp:setProperty :- Sets the property of a JavaBean
  • jsp:getProperty :- Inserts the property of a JavaBean into the output
  • jsp:forward :- Forwards the requester to a new page
  • jsp:plugin :- Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
  • jsp:element :- Defines XML elements dynamically.
  • jsp:attribute :- Defines dynamically defined XML element's attribute.
  • jsp:body :- Defines dynamically defined XML element's body.
  • jsp:text :- Use to write template text in JSP pages and documents.
What is difference between include action and include directive in JSP?
When a request comes for JSP page, that JSP page first translated into Servlet class and then that servlet gets compiled and loaded into heap memory by the web container. Code written using JSP declaration e.g. < %! > goes into body of generated servlet as instance variable and all code from body goes into service() method of generated Servlet. In case of tomcat web-server these generated servlet files goes inside work directory.

In short, we can say JSP pages in three steps JSP page gets executed: Translation->Compilation->Execution. (JSP file will only be re-compiled only if there is a change in JSP file.)

Include directive in JSP
Include directive in JSP is used to import a static file or dynamic file e.g. including header and footer in JSP. Include directive is also called file include because resource to be included is specified using file attribute, e.g:

< %@ include file="header.jsp" % >


The code written in header.jsp will be included as it is in the jsp file which included it during JSP translation time and than merged code is get compiled to generate Servlet which is later used to server request.

Include action in JSP
Include action in JSP is another way of including a jsp file inside another jsp file. Included resource is specified using page attribute, e.g:

< jsp:include page="header.jsp" % >

header.jsp will be included during request time instead of translation time and any change in header.jsp will reflect immediately. Due to this nature include action is also called dynamic include in JSP. It also referred as page includes because of page attribute used to specify included resource.

Difference between include action and include directive:
  • include directive is static import while include action is dynamic import
  • Resource included by including directive is loaded during jsp translation time, while resource included by including action is loaded during request time.
  • Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in the case of include again any change in included resource will be visible in next request.
What is the < jsp:useBean > standard action?
The < jsp:useBean > standard action first searches for an existing object (java bean) utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.

< jsp:useBean id="name" class="package.class" / >

Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.

Attributes of jsp:useBean are
  • class-Designates the full package name of the bean.
  • type-Specifies the type of the variable that will refer to the object.
  • beanName-Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.

What is the < jsp:setProperty > standard action?
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action:

1).
< jsp:useBean id="myName" ... / >
...
< jsp:setProperty name="myName" property="someProperty" .../ >


In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

2).
< jsp:useBean id="myName" ...  >
...
   < jsp:setProperty name="myName" property="someProperty" .../ >
< /jsp:useBean >


Attributes associated with setProperty action:
  • name :- Designates the bean whose property will be set. The Bean must have been previously defined.
  • property :- Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
  • value :- The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored.
  • param :- The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.
What is the < jsp:getProperty > standard action?
getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes 'name' and 'property':

< jsp:useBean id="myName" ... / >
...
< jsp:getProperty name="myName" property="someProperty" .../ >


Where, 'name' is the name of the Bean that has a property to be retrieved. The Bean must have been previously defined. and 'property' is the property attribute is the name of the Bean property to be retrieved.

What are JSP Scripting elements?
The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements, scriptlet, expression and declaration.

What is a scriptlet in JSP?
A scriptlet tag is used to execute java source code in JSP. e.g:

< % java code %>

You can write XML equivalent of the above syntax as follows:

< jsp:scriptlet >
   java code
< /jsp:scriptlet >


What is JSP Declarations?
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it doesn't get memory at each request.
e.g:
< %! int a, b, c; % >
< %! Circle a = new Circle(2.0); % >


Difference between JSP Scriptlet tag and Declaration tag?
  • The jsp scriptlet tag can only declare variables not methods. The jsp declaration tag can declare variables as well as methods.
  • The declaration of scriptlet tag is placed inside the _jspService() method.    The declaration of jsp declaration tag is placed outside the _jspService() method.
What is JSP Expression?
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. e.g:

< %= expression %>

Or you can write XML equivalent of the above syntax as follows:

< jsp:expression >
   expression
< /jsp:expression >

How do you define application wide error page in JSP?
We can define error pages in Java web application in two ways, using tag in web.xml and other is by using error page JSP which uses isErrorpage to declare that this jsp page can be used as error page.

Page Specific Error page in JSP : By setting 'errorpage' attribute on page directive of JSP, we can define an error page for any particular JSP. After that if any unhandled Exception thrown from that JSP, this error page will be invoked. e.g:
//userlogin.jsp
< %@ page errorPage="error.jsp"% >

That means, if any exception occurs in userlogin.jsp then error.jsp is show. In order to make error.jsp as a error page, we need to mark 'isErrorPage' attribute as true. e.g:
//error.jsp
<%@ page isErrorPage="true"%>

Application wide Error page in Java web application: It is called application wide error page or default/general error page because its applicable to whole web application instead of any particular servlet or JSP. This error page is defined in web.xml by using tag < error-page >. This tag allows you to define custom error message based upon HTTP error code or any Java Exception. you can define a default error message for all exception by specifying < exception-type > as java.lang.Throwable and it would be applicable to all exception thrown form any Servlet or JSP from web application. e.g:

< error-page >
        < exception-type >java.lang.Throwable< /exception-type >
        < location >/error.html< /location >
< /error-page >
< error-page >
    < error-code >404< /error-code >
    < location >/page-not-found-error.htm< /location >
< /error-page >


What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

Difference between SendRedirect() and Forward() in JSP Servlet
1). Forward transfer the request to other resource within the same server for further processing. In case of sendRedirect request is transfer to another resource to different domain or different server for futher processing.
2). In case of forward Web container handle all process internally and client or browser is not involved. When you use SendRedirect container transfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.
3). When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request. In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4). Visually we are not able to see the forwarded address, its is transparent. Where as in address bar we are able to see the new redirected address it’s not transparent.
5). Using forward () method is faster then send redirect. SendRedirect is slower because one extra round trip is required beasue completely new request is created and old request object is lost.Two browser request requird.
6). When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available. But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.

Forward() is declared in RequestDispatcher Interface.
Method Signature: forward(ServletRequest request, ServletResponse response)

e.g
RequestDispatcher rd = request.getRequestDispatcher("welcomeToGermany.jsp");
rd.forward(request, response);


Or

RequestDispatcher rd = servletContext.getRequestDispatcher("/welcomeToGermany.jsp");
rd.forward(request, response);


SendRedirect ()
is declared in HttpServletResponse Interface.
Method Signature: void sendRedirect(String url)

e.g:
response.sendRedirect(/welcomeToGermany.jsp);

What is servlet attributes and their scope?
Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.

ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.

Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

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.

Can we get PrintWriter and ServletOutputStream both in a servlet?
We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method, if we invoke both the methods; getWriter() and getOutputStream() on response; we will get java.lang.IllegalStateException at runtime with message as other method has already been called for this response.

What is called Session Tracking? Why it is needed?
Session tracking is used to maintain a state on the series of requests from the same user for a given period of time. Every HTTP request needs to be captured by HTTP protocol and for that, state is captured. Tracking of state is called session tracking.

What are the types of Session Tracking ?

1. URL rewriting: In this method of session tracking, some extra data is appended at the end of the URL, which identifies the session. This method is used for those browsers which do not support cookies or when the cookies are disabled by the user.
2. Hidden Form Fields: This method is similar to URL rewriting. New hidden fields are embedded by the server in every dynamically generated form page for the client. When the form is submitted to the server the hidden fields identify the client.
3. Cookies: Cookie refers to the small amount of information sent by a servlet to a Web browser. Browser saves this information and sends it back to the server when requested next. Its value helps in uniquely identifying a client.
4. Secure Socket Layer (SSL) Sessions

What are the advantages of cookies?
Cookies are used to store long term information that can be maintained without server interaction. Small and Medium size data are kept in a queue.

What is URL rewriting?
URL rewriting is one of the methods of session tracking in which additional data is appended at the end of each URL. This additional data identifies the session.

Difference between URL-rewriting URL-encoding in Servlet JSP
URL-rewriting is a technique to maintain user session if cookies are not enabled on client browser or browser doesn't support cookie, while URL-encoding is a way to pass string to server containing special characters  by converting special characters like space into some other characters like +.

People often confuse between URL encoding and URL rewriting because of there names which sounds quite similar for new guys but functionality wise they are totally different to each other, Also servlet encodeURL() method adds more confusion because its sounds like its used for URL Encoding but indeed used for URL Rewriting.

1). java.servlet.http.HttpServletResponse methods encodeURL(String url) and encodeRedirectURL(String URL) is used to embed SesssionID on URL to support URL-rewriting. The logic to include sessionID is in method itself and it doesn't embed sessionID, if browser supports cookies or session maintenance is not required. In order to implement a robust session tracking all URL from Servlet and JSP should have session id embedded on it.

In order to implement URL-rewriting in JSP you can use use JSTL core tag all URL passed to it will automatically be URL-rewriting if browser doesn't support cookies. While java.net.URLEncoder.encode() and java.net.URLDecoder.decode()is used to perform URL Encoding and decoding which replace special character from String to another character. This method uses default encoding of system and also deprecated instead of this you can use java.net.URLEncoder.encode(String URL, String encoding) which allows you to specify encoding. as per W3C UTF-8 encoding should be used to encode URL in web application.

2) In URL rewriting session id is appended to URL and in case of URL-encoding special character replaced by another character.

What is JSESSIONID in Java? When does JSESSIONID gets created ?
HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from the same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting.

JSESSIONID is a cookie generated by Servlet containers like Tomcat and is used for session management in J2EE web application for HTTP protocol.

When a web server use a cookie for session management. it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests.

In Java J2EE application container is responsible for Session management, when a user first time access your web application, session is created based on whether its accessing HTML, JSP or Servlet.

If user request is served by Servlet than session is created by calling request.getSession(true) method. It accepts a boolean parameter which instruct to create session if its not already existed. If you pass 'false' in getSession() method then it will either return null(if no session is associated with this user) or return the associated HttpSession object.

If HttpRequest is for JSP page than Container automatically creates a new Session with JSESSIONID, if this feature is not disabled explicitly by using page directive <  %@ page session="false" % >.

In case of HTML access, no user session is created. If  client has disabled cookie than Container uses URL rewriting for managing session on which jsessionid is appended into URL.

When HTTP session is invalidated(), mostly when the user logged off, old JSESSIONID destroyed and a new JSESSIONID is created when the user further login.

How can you prevent the output of your JSP or Servlet pages from being cached by the browser?
We will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. We need to add below scriptlet at the beginning of JSP pages to prevent them from being cached at the browser. We need both the statements to take care of some of the older browser versions.

< % response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
% >


How can you set variable in application scope in Servlet, so that it can be shared among sessions?
servletContext is used to store the global data which is going to share through out the application. This is not thread safe.
getServletContext().setAttribute("APPLICATION_VARIABLE", "APPLICATION_VARIABLE_VALUE");
Suppose, you have two Servlet's Servlet1 and Servlet2. In init() method of Servlet1, we set USER_NAME as 'Matthew Langford Perry',
getServletContext().setAttribute("USER_NAME", "Matthew Langford Perry");


In doGet(), we are printing it.
PrintWriter out = response.getWriter();
out.println("USER_NAME in Servlet1="+getServletContext().getAttribute("USER_NAME"));


Now we create Servlet2, and in doGet(), we first print the USER_NAME from context and then update it.
PrintWriter out = response.getWriter();
out.println("Getting the USER_NAME from Context="+getServletContext().getAttribute("USER_NAME"));
getServletContext().setAttribute("USER_NAME", "Matthew Perry");
out.println("After changing USER_NAME in Context="+getServletContext().getAttribute("USER_NAME"));


When you run Servlet1, for the first time it will print:
USER_NAME in Servlet1=Matthew Langford Perry

Now run Servlet2, it will print:
Getting the USER_NAME from Context=Matthew Langford Perry
After changing USER_NAME in Context=Matthew Perry


Since init() is called only once, so if you run Servlet1 again it wil print:
USER_NAME in Servlet1=Matthew Perry

-K Himaanshu Shuklaa..

No comments:

Post a Comment