32. What is the difference between ServletContext and ServletConfig

public interface ServletContext

  • Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
  • There is one context per “web application” per Java Virtual Machine.
  • The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

public interface ServletConfig

  • A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.
  • This object defines how a servlet is to be configured is passed to a servlet in its init method.
  • Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters.
  • The container, in turn, passes these parameters to the servlet via the ServetConfig.

31. Explain Servlet Life Cycle.

  1. Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours.
  2. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance.
  3. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

  

Servlet Initialization (init())
So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application.

Now when will Servlet Container create an instance of your Servlet? there are two situations :

  • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
    <web-app>
    
      <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>com.wordpress.sharat.servlets.TestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    </web-app>

    So when the Servlet Container starts it will preload your Servlet in the memory.

  • If your Servlet is not already loaded, it’s instance will be created as soon as a request is received for it by the Servlet Container.
  • During the loading of the Servlet into the memory, Servlet Container will call your Servlet’s init() method.
  • Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

Responding to Requests(service())

  1. Once your Servlet is initialized and it’s init() method called, any request that the Servlet Container receives will be forwarded to your Servlet’s service() method.
  2. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives.
  3. So in order to generate respose you should override the doGet() or doPost() method as required.
  4. At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

Servlet Destruction(destory())

When your application is stopped or Servlet Container shuts down, your Servlet’s destroy() method will be called. This allows you to free any resources you may have got hold of in your Servlet’s init() method.

Always Remember

  • init() and destroy() methods will be called only once during the life time of your Servlet
  •  while service() and it’s broken down methods ( doGet(), doPost() etc ) will be called as many times as requests are received for them by the Servlet Container.

30. Explain the advantages of JSTL

  1. The Java Standard Tag Library (JSTL) is a standardized collection of custom tags.
  2. It has a number of tags for common tasks such as iterating through lists, interacting with databases, handling XML data, formatting data, and much more.
  3. The latest version of JSTL is 1.1. An implementation of JSTL can be downloaded from the Apache Jakarta Web site (http://jakarta.apache.org/).
  4. JSTL consist of four sets of tags and a library of functions, grouped according to their functionality:
  • The JSTL core tag library contains tags that deal with flow control in JSP pages, iterating over collections, evaluating expressions, and importing resources.
  • Before using the core tag library, the following directive needs to be added to the JSP page:
  • <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>
  • The equivalent XML syntax for this directive is as follows:
  • <jsp:directive.taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; />

The following table summarizes the JSTL core tags.

Tag Name

Description

catch

Catches any Throwable exception that occurs in the body of the tag

choose

Provides conditional operation and allows for choosing between mutually exclusive options

if

Provides conditional operation

import

Imports a resource specified by a URL and exposes it to the page, variable, or reader

forEach

Iterates over collections

forTokens

Iterates over tokens

out

Outputs expressions to the Web page

otherwise

A conditional operation tag for choosing between mutually exclusive options. This tag is a subtag of the choose tag.

param

Used along with the import, redirect, or url tags to add a parameter to a URL

redirect

Redirects to a new URL

remove

Removes a variable from a scope

set

Sets the value of an attribute

url

Creates a URL

when

A conditional operation tag that includes its body when an expression evaluates to true. This tag is a subtag of the choose tag.

29. What are the advantages of JSP

  • Separation of static from dynamic content.
  • Write Once Run Anywhere.
  • Dynamic content can be served in a variety of formats.

            example: browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML

  • Recommended Web access layer for n-tier architecture.
  • Completely leverages the Servlet API.

28. Explain JSP Basic Structure Items.

JSP Expression

  • <%= expression %>
  • Expression is evaluated and placed in output.
  • XML equivalent is
    <jsp:expression>
    expression
    </jsp:expression>
    .
  • Predefined variables are request,response,out,session,application,config, andpageContext (available in scriptlets also).

JSP Scriptlet

  • <% code %>
  • Code is inserted in service method.
  • XML equivalent is
    <jsp:scriptlet>
    code
    </jsp:scriptlet>
    .

JSP Declaration

  • <%! code %>
  • Code is inserted in body of servlet class, outside of service method.
  • XML equivalent is
    <jsp:declaration>
    code
    </jsp:declaration>
    .

JSP page Directive

  • <%@ page att=”val” %>
  • Directions to the servlet engine about general setup.
  • XML equivalent is
    <jsp:directive.page att="val"\>.
  • Legal attributes, with default values in bold, are:
    • import=”package.class
    • contentType=”MIME-Type
    • isThreadSafe=”true|false”
    • session=”true|false”
    • buffer=”sizekb|none”
    • autoflush=”true|false”
    • extends=”package.class
    • info=”message
    • errorPage=”url
    • isErrorPage=”true|false
    • language=”java”

JSP include Directive

  • <%@ include file=”url” %>
  • A file on the local system to be included when the JSP page is translated into a servlet.
  • XML equivalent is
    <jsp:directive.include
      file="url"\>
    .
  • The URL must be a relative one. Use the jsp:include action to include a file at request time instead of translation time.

JSP Comment

  • <%– comment –%>
  • Comment; ignored when JSP page is translated into servlet.
  • If you want a comment in the resultant HTML, use regular HTML comment syntax of <-- comment -->.

The jsp:include Action

  • <jsp:include page=”relative URL” flush=”true”/>
  • Includes a file at the time the page is requested.
  • If you want to include the file at the time the page is translated, use the page directive with theinclude attribute instead. Warning: on some servers, the included file must be an HTML file or JSP file, as determined by the server (usually based on the file extension).

The jsp:forward Action

  • <jsp:forward page=”relative URL“/>
  • Forwards request to another page.

The jsp:plugin Action

  • <jsp:plugin attribute=”value“*> … </jsp:plugin>
  • Generates OBJECT orEMBED tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.

27. How to handle cookies in JSP

  • The getCookies() method of the request object returns an array of Cookie objects.
  • Cookies are used to allow web browsers to hold small amounts of information or state data associated with a user’s web browsing.
  • Cookies are named and have a single value. They may have optional attributes, including a comment presented to the user, path and domain qualifiers for which hosts see the cookie, a maximum age, and a version.
 
Cookie(java.lang.String name, java.lang.String value)

Cookie objects have the following methods.

getComment()
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

getMaxAge()
Returns the maximum specified age of the cookie.

getName()
Returns the name of the cookie.

getPath()
Returns the prefix of all URLs for which this cookie is targetted.

getValue()
Returns the value of the cookie.

setComment(String)
If a web browser presents this cookie to a user, the cookie’s purpose will be described using this comment.

setMaxAge(int)
Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behaviour: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted

setPath(String)
This cookie should be presented only with requests beginning with this URL.

setValue(String)
Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the “at” sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.

26. Explain JSP Session implicit Object.

  1. The session implicit object is used to provide an association between the client and the server. This association, or session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests.
  2. A session can be maintained either by using cookies or by URL rewriting. To expose whether the client supports cookies, session defines an isCookieSupportDetermined() method and an isUsingCookies() method.

Servlet Class

HttpSession

The following table summarises the most useful methods available to the session object.

isNew()
A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.

invalidate()
Discards the session, releasing any objects stored as attributes.

getAttribute(String)
Retrives the object associated with the named attribute.

getAttributeNames()
Retrives the names of all attributes currently associated with the session.

setAttribute(String, object)
Sets the object to the named attribute. attribute created if it doesn’t exist.

removeAttribute(String)
Removes the object bound with the specified name from this session.

25. What is Session Tracking.

There are a number of problems that arise from the fact that HTTP is a “stateless” protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can’t easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what’s already in your cart? Even if servers did retain contextual information, you’d still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

There are three typical solutions to this problem.

  1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled:
    • Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all),
    • Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and
    • Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).
  2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don’t support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.
  3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

24. How can JSP inheritance be achieved

The JSP super class and sub-class need to satisfy certain requirements as defined in the sections below. First let us assume we are using the HTTP protocol. Then mapping of other protocols is an easy task.

Requirements for the Super Class

  • It must implement the HttpJspPage interface.
  • It will obviously extend the HttpServlet class. It needs to implement the three main lifecycle methods of the servlet:
    • init
    • destroy
    • service

These implementations are ‘final’. In addition, the method getServletConfig must be implemented to return the ServletConfig object, passed onto the servlet during initialization.

This super class now necessitates the base class to actually implement the JSP version of these three function calls: jspInit, jspDestroy, and _jspService, by providing abstract declarations for the same

    • public abstract void jspInit()
    • public abstract void jspDestroy()
    • The signature for the _jspService method depends on the kind of JSP Engine that has been deployed. For eg: if Weblogic is the JSP Engine, the signature is:
public abstract void _jspService(HttpServletRequest request, HttpServletResponse response);

The init method is called jspInit, the destroy method – jspDestroy, and the service method as _jspService.

Requirements for the sub class

The sub class may or may not provide the jspInit and jspDestroy method, based on whether the parent class provides it.

Code snippet for the JSP sub class

<%@ page extends=”JSPPageSuper”%>

<%

//Any server processing

%>

<HTML>

</HTML>

Note the first line where the page extends the JSPPageSuper servlet.

23. Explain about JSP Standard Action

* The use of JavaBeans within JSP pages is a system for accessing Java components through the standard interface of methods with set and get prefixes.
* The general syntax for the useBean tag is as follows.
<jsp:useBean id=”myBean” type=”classtype” class=”com.domain.ClassName” scope=”session” />

   #  The it attribute id mandatory and can be an arbitrary string, but each can only appear once within a page (i.e. You cannot have two beans with the same id within a page).
   #  The actual class must be stored under the WEB-INF\classes directory
   #  The scope attribute can be page,request,session, or application.
   #  The scope attribute is optional and if it is omitted the default is page scope.

Example:

# Java Bean Code

package com.wordpress.sharat;
public class TestJSPUseBean {
   private String firstName=”sharat”;
   private String lastName=”abcd”;
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getFirstName() {
      return firstName;
   }
   
   public String getLastName() {
      return lastName;
   }
}

# Usage:

That JavaBean can be used within a JSP as follows
<jsp:useBean id=”testbean” type=”com.wordpress.sharat.TestJSPUseBean” class=”com.wordpress.sharat.TestJSPUseBean” scope=”session” />
<html>
<%
   out.print(testbean.getFirstName());
%>
</html>
# getProperty

<jsp:getProperty name=”testbean” property=”firstName”/>

name and property attributes are mandatory.
# setProperty

<jsp:setProperty name=”testbean” property=”firstName” value=”Donkey”/>

# This allows values of a JavaBean to be set at runtime.
# Param Attribute:
  It is a very common requirement to want to set a property according to a runtime query parameter.
  for example with the URL query string
           ?firstname=marcus&lastname=green

  <jsp:setProperty name=”testbean” property=”firstName” param=”firstname” />
  <jsp:setProperty name=”testbean” property=”lastName”  param=”lastname” />

# Default Params:
  <jsp:setProperty name=”person” property=”*”   />
  then It will correctly map the firstName and lastName parameters to the “testbean” bean.

# type attribute in bean defication is optional. We can have a bean defication with type attribute and with out a “class” attribute.