ServletConfig

  1. ServletConfig is one of the pre-defined interface.
  2. ServletConfig object is used for developing flexible servlets.
  3. ServletConfig objct exist one per servlet program.
  4. An object of ServletConfig created by the container during its initialization phase.
  5. An object of ServletConfig is available to the servlet during its execution, once the servlet execution is completed, automatically ServletConfig interface object will be removed by the container.
  6. An object of ServletConfig interface contains details at web.xml, of a particular servlet.
  7. The moment when we are using an object of ServletConfig, we need to configure the web.xml by writing tag under tag of web.xml.
  8. When ever compiler executes init() mehod then the ServletConfig will be created in general.
  9. An object of ServletConfig contain the data in the form of key,value pairs, here the keys represents init param names and values are its values, which are represented in the web.xml file

How to Get ServletConfig Object into Servelt
Method1

ServletConfig conf = getServletConfig();

Method2
ServletConfig object will be available in init() method of the servlet.

public void init(ServletConfig config)
{
// …………………
}

How to Retrieve Data from ServletConfig Interface Object

public String getInitParameter(“param name”);
public Enumeration getInitParameterNames();

web.xml

<web-app> 
  <servlet>
     <servlet-name>onServletConfig</servlet-name>
     <servlet-class>java4s.OnServletConfig</servlet-class> 
     <init-param>
        <param-name> n1 </param-name>
        <param-value> 100 </param-value>
     </init-param>
    .
    .
</web-app>

Test.java

ServletConfig conf=getServletConfig(); 
String s1=conf.getInitParameter("n1");
 

ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

Methods of ServletContext interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the attribute for the specified name.
  5. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.

web.xml

    <web-app>  
     ......  
          
      <context-param>  
        <param-name>parametername</param-name>  
        <param-value>parametervalue</param-value>  
      </context-param>  
     ......  
    </web-app>  

Test.java

  ServletContext context=getServletContext();    

  //Getting the value of the initialization parameter and printing it  
  String driverName=context.getInitParameter("parametername");  

Which HTTP method is non-idempotent?
An idempotent operation can be repeated an arbitrary number of times and the result will be the same as if it had been done only once. In arithmetic, adding zero to a number is idempotent.

A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

For example, to access an HTML page or image, we should use GET because it will always return the same object but if we have to save customer information to database, we should use POST method. Idempotent methods are also known as safe methods and we don’t care about the repetitive request from the client for safe methods.

What is ServletContext object?

  1. javax.servlet.ServletContext interface provides access to web application parameters to the servlet.
  2. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using element.
  3. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.
    @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException 
       {
                HttpSession session = request.getSession(true);
                ServletContext context = session.getServletContext();
       }
    

ServletConfig vs ServletContext

Servlet Config Servlet Context
Servlet config object represent single servlet It represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servlet Its like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope ServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config object getServletContext() method is used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet config To get the MIME type of a file or application session related information is stored using servlet context object.

What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

  1. RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.
  2. forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.
  3. forward() is handled internally by the container whereas sednRedirect() is handled by browser.
  4. We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.
  5. In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.

Difference between web server, web container and application server
Web server: serves content to the web using http protocol.
Web container also known as a Servlet container is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

Application server: hosts and exposes business logic and processes.
An application server is a server that hosts the business logic for a system. It often hosts both long running/batch processes and/or a interop services not meant for human consumption (REST/JSON services, SOAP, RPC, etc).
An application server is typically designed and deployed to facilitate longer running processes that will also be more resource intensive.

Real World Scenarios
Web server
You have an online store with only a web server and no application server. The site will provide a display where you can choose a product from. When you submit a query, the site performs a lookup and returns an HTML result back to its client. The web server sends your query directly to the database server (be patient, I will explain this one in our next nugget) and waits for a response. Once received, the web server formulates the response into an HTML file and sends it to your web browser. This back and forth communication between the server and database server happens every time a query is run.

Application server
if the query you want to run has already been done previously and no data has changed since then, the server will generate the results without having to send the request to the database server. This allows a real-time query where a second client can access the same info and receive real time, reliable information without sending another duplicate query to the database server. The server basically acts as an intermediate between the database server and the web server. This allows the information pulled to be reusable while in the first scenario, since this info is embedded in a particular and “customized” HTML page, this is not a reusable process. A second client will have to request the info again and receive another HTML embedded page with the info requested -highly inefficient.

How to make sure a servlet is loaded at the application startup?
Usually servlet container loads a servlet on the first client request but sometimes when the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use load-on-startup element with servlet configuration in web.xml file or use WebServlet annotation loadOnStartup variable to tell container to load the servlet on system startup.

<servlet>
	<servlet-name>foo</servlet-name>
	<servlet-class>com.foo.servlets.Foo</servlet-class>
	<load-on-startup>5</load-on-startup>
</servlet> 

If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.

How to get the actual path of servlet in server?

getServletContext().getRealPath(request.getServletPath())

Why is _jspService() method starting with an ‘_’ while other life cycle methods do not?

_jspService() cannot be overridden where as other methods jspInit(), jspDestroy() can be overridden.

Difference between Filter and Listener in Servlet
Servlet Filter is used for monitoring request and response from client to the servlet, or to modify the request and response, or to audit and log.

Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example HttpSessionListener.

JSP lifecycle phases

  1. Translation of JSP to Servlet code.
  2. Compilation of Servlet to bytecode.
  3. Loading Servlet class.
  4. Creating servlet instance.
  5. Initialization by calling jspInit() method
  6. Request Processing by calling _jspService() method
  7. Destroying by calling jspDestroy() method

JSP lifecycle methods

  1. jspInit() method-What is jspInit() method
    Once a JSP file is successfully compiled into a class file, jsp engine calls jspInit() method to initialize class file. This method is called by the container only once during the lifecycle. jspInit() method can be overridden by the author to initialize resources such as database and network related connections.

    public void jspInit() {
      // initialization code or something needs to be called before JSP page
      // starts serving the requests.
     }
    

    Now the question arises why we shouldn’t use constructor instead of init method of jsp or servlet ?. Of course ! we can use constructor instead of init() method, there is nothing to stop us. In previous versions of java it was not possible to dynamically call constructor with arguments. This does no longer applied, but servlet containers still looks for an no-argument constructor. So we won’t have access to a ServletConfig or ServletContext if we use constructor instead of init() method.

  2. _jspService() method – _jspService() method is called every time a request comes to jsp during its lifecycle. The (_) underscore sign indicates that this method is generated by Container and hence cannot be overriden. The jsp code written by us goes in _jspService() because this is implicitly implemented. In case we tries to override it explicitly, JSP compliler will give an error saying “the method is already implemented and cannot override’.
  3. jspDestroy() method
    jspDestroy() method is called when servlet(jsp) is no longer in use, with the call of this method jsp lifecycle is ended and jsp submits itself to garbage collection.

    public void jspDestroy() {
      // code related to release resources like database ot network
      // connections.
     }
    

    We can always call jspDestroy() at any stage of its lifecycle but it does not make sense because even if you called jspDestroy() in the beginning, it doesn’t stops the JSP to execute the _jspService() method and sending the response back to the client. This is one of the lifecycle method which is invoked by the JSP Container when the jsp instance is removed.

Implicit objects in JSP – Objects created by web container and contain information regarding a particular request, application or page are called Implicit Objects.

Implicit object is the object that is created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

  1. response
  2. request
  3. exception
  4. application
  5. session
  6. pageContext
  7. page
  8. config
  9. out

Is JSP technology extensible?
Yes, JSP is easily extensible by use and modification of tags, or custom actions, encapsulated in tag libraries.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
requestDispatcher – forward() method

  1. When we use forward method, request is transfer to other resource within the same server for further processing.
  2. In case of forward, web container handle all process internally and client or browser is not involved.
  3. When forward is called on requestdispatcher object we pass request and response objects so our old request object is present on new resource which is going to process our request.
  4. Visually we are not able to see the forwarded address, it is transparent.
  5. Using forward () method is faster then send redirect.
  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.

HttpServletResponse.sendRedirect() method

  1. In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.
  2. 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. In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.
  4. In address bar, we are able to see the new redirected address. It’s not transparent.
  5. sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.
  6. But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.

Which one is good?
If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect. Generally, forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

How HttpServletResponse.sendRedirect() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with Location: other.jsp header
  3. Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  4. Server sends a HTTP response back with content of other.jsp.

How RequestDispatcher.forward() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with content of other.jsp.

How can a thread safe JSP page be implemented?
It can be done by having them implemented by the SingleThreadModel Interface. Add <%@page isThreadSafe=”false” %> directive in the JSP page.

How do I prevent the output of my JSP or Servlet pages from being cached?

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

How do we configure init params for JSP?
We can configure init params for JSP similar to servlet in web.xml file, we need to configure JSP init params with servlet and servlet-mapping element.

What is Scriptlet, Expression and Declaration in JSP?

A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the _jspService() method. For example;

<%
Date d = new Date();
System.out.println("Current Date="+d);
%>

Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.

<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as

<%! public static int count=0; %>

Use of pageContext Object

  1. pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.This object is intended as a means to access information about the page while avoiding most of the implementation details.
  2. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
  3. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
  4. important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute (“attrName”) removes the attribute from all scopes, while the following code only removes it from the page scope
pageContext.removeAttribute("attrName", PAGE_SCOPE);

Other Example

ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

JSP Action Elements or Action Tags
JSP action elements or action tags are HTML like tags that provide useful functionalities such as working with Java Bean, including a resource, forwarding the request and to generate dynamic XML elements. JSP action elements always starts with jsp: and we can use them in JSP page directly without the need to import any tag libraries or any other configuration changes. Some of the important action elements are jsp:useBean, jsp:getProperty, jsp:setProperty, jsp:include and jsp:forward.

Syntax Purpose
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.

difference between include directive and jsp:include action?
The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.

Another difference is that in JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.

When included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.

What are JSP EL implicit objects and how it’s different from JSP implicit Objects?
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. Note that these are different from JSP implicit objects and contains only the attributes in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.

JSP EL Implicit Objects Type Description
pageScope Map A map that contains the attributes set with page scope.
requestScope Map Used to get the attribute value with request scope.
sessionScope Map Used to get the attribute value with session scope.
applicationScope Map Used to get the attributes value from application scope.
param Map Used to get the request parameter value, returns a single value
paramValues Map Used to get the request param values in an array, useful when request parameter contain multiple values.
header Map Used to get request header information.
headerValues Map Used to get header values in an array.
cookie Map Used to get the cookie value in the JSP
initParam Map Used to get the context init params, we can’t use it for servlet init params

What is JSP Standard Tag Library, provide some example usage?
JSP Standard Tag Library or JSTL is more versatile than JSP EL or Action elements because we can loop through a collection or escape HTML tags to show them like text in response.JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container.

What is difference between JspWriter and Servlet PrintWriter?
PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.

<%@ include is a static include, The include directive:

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

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

standard action:

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

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like , but it’s more powerful and flexible: unlike the other two includes, the url can be from outside the web Container!

Preludes and codas:
Static preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding and elements respectively within a element in the Web application web.xml deployment descriptor.

How can one Jsp Communicate with Java file.

<%@ page import="market.stock.*” %>

What is web.xml
The /WEB-INF/web.xml file is the Web Application Deployment Descriptor of your application. This file is an XML document that defines everything about your application that a server needs to know except the context path.

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 1 is also known as pre-initialization of servlet means now the servlet for which we have defined this tag has been initialized in starting when context is loaded before getting any request.