Wednesday, July 24, 2013

What are the life-cycle methods of JSP?

JSP:

If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author.

Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program.

Note: 

A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page.
The resulting servlet is executed on the server. 

It is never visible to the user agent. If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.


Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.


c) jspDestroy(): The container calls this when its instance is about to destroyed.

How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. 

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

You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the <%! DECLARE %>tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above.

Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe.

How do I include static files within a JSP page?

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.


The following example shows the syntax:

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

Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine.


In doing so, you may lose out on any advanced optimization that may be provided by the JSPengine.

In any case, your new super class has to fulfill the contract with the JSP engine by: 

Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final. Additionally, your servlet super class also needs to do the following:

The service() method has to invoke the _jspService() method The init() method has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. 

Once the super class has been developed, you can have your JSP extend it as follows:

How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. 

The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.


public void doPost (HttpServletRequest request, HttpServletResponse response)
{
  try
   {
     govi.FormBean f = new govi.FormBean();
     String id = request.getParameter("id");
     f.setName(request.getParameter("name"));
     f.setAddr(request.getParameter("addr"));
     f.setAge(request.getParameter("age"));
     //use the id to compute
     //additional bean properties like info
     //maybe perform a db query, etc.
     // . . .

     f.setPersonalizationInfo(info);
     request.setAttribute("fBean",f);   
     getServletConfig().getServletContext().getRequestDispatcher
     ("/js/Bean1.jsp").forward(request, response);
   }
    catch (Exception ex)
    { . . .
     }
}


The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action. 

jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty name="fBean" property="name" / jsp:getProperty name="fBean" property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean" property="personalizationInfo" /

How can I enable session tracking for JSP pages if the browser has disabled cookies?

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. 

URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response.

Adding the session ID to a link is greatly simplified by means  of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.

Basically, we create a new session within hello1.jsp and place an object within this session.

The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. 

Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. 

Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.

hello1.jsp hello2.jsp hello2.jsp <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is "+i.intValue());

What is difference between custom JSP tags and beans?

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:

1. The tag handler class that defines the tag\'s behavior.

2. The tag library descriptor file that maps the XML element names to the tag implementations.

3. The JSP file that uses the tag library When the first two components are done, you can use the tag by using taglib directive:

<%@ taglib uri="xxx.tld" prefix="..." %>

Then you are ready to use the tags you defined.

Let's say the tag prefix is test: MyJSPTag or JavaBeans are Java utility classes you defined.

Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms.

There are several differences:

Custom tags can manipulate JSP content;beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans.

Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

Sunday, July 21, 2013

What is jsp:setProperty, jsp:getProperty, standard and jsp:plugin action?

jsp:setProperty action

You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="myProperty" ... />

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

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:

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

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

jsp:getProperty action

The <jsp:getProperty> action is used to access the properties of a bean that was set using the <jsp:getProperty> action. The container converts the property to a String as follows:

  • If it is an object, it uses the toString() method to convert it to a String.
  • If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
  • The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name" property="Property" />
Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the <jsp:useBean> action before using the <jsp:getProperty> action.

<jsp:param> standard action

The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names and values to the target resource. The syntax of the <jsp:param> standard action is as follows: <jsp:param name="paramName" value="paramValue"/>

jsp:plugin action

This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.