Monday, March 31, 2008

3 ways to invoke a Tag that does not have body

 

1) an empty tag: example <tax:calculate2008  user=”${username}”  />

2) a tag with nothing between opening and closing tags: example <tax:calculate2008  user=”${username}”></ tax:calculate2008>

3) a tag with only <jsp:attribute> between tags. Example

<tax:calculate2008  user=”${username}”>

            <jsp:attribute name=”user”>${username}</ jsp:attribute>

</ tax:calculate2008>

 

Remember jsp:attribute is only tag you can put in body even when body content for that tag is declared as empty.

For other things you will get a big org.apache.jasper.JasperException

 

Sunday, March 30, 2008

VS

<jsp:include>VS <c:import>       

  1. The <c:import> tag imports a resource specified by a URL and exposes it to the page, variable, or reader.
  2. The <jsp:include> standard action is a request-time action that will include the output of another JSP at the location of the tag within the calling JSP.
  3. The body of the import tag can have param tags for adding parameters to the URL.
  4. The first additional function allows you to include content directly from other Web sites. So the following is now legal:
    <c:import url=”http://www.example.com/somecontent.html”/>
  5. You can even use ftp:
    <c:import url=”ftp://ftp.example.com/somecontent.txt”/>
  6. Rather than dump an imported URL straight to the page, you can store it in a variable. This is a common strategy in all the JSTL tags and increases the power of a JSP page:
    <c:import url=”http://www.example.com/example.inc” var=”example”/> Once this included page is stored in the example variable, you can use another taglib, such as the Jakarta String taglib, to replace all references to example.com with done.com.
  7. Since you can store <c:import> in a variable <c:import> might do some type of full read before printing to output, whereas <jsp:include> uses buffering. This could show a performance difference for very large files, with <c:import> requiring longer and taking more memory to get all the data in the import whereas <jsp:include> did things with buffers.

Import Syntax:

<c:import url=”resource URL”
          [var=”variable name”]
          [scope=”page|request|session|application”]
          [varReader=”variable name”]
          [context=”context name”]
          [charEncoding=”character encoding”]>
     JSP body content
</c:import>

Include Syntax:

<jsp:include page=”…url..” flush=”true or false“/>

The tag can optionally contain a body:

<jsp:include page="…url…” flush=”true or false“>
  <jsp:param  …./>
</jsp:include>

 

Summary:

If you want to include a page within webapplication, go for JSP:include

If you want to include a page outside webapplication, go for JSTL import

Thursday, March 27, 2008

Servlet Life-Cycle Events -Quick Reference

Servlet Life-Cycle Events

Object

Event

Listener Interface and Event Class

Web context (see Accessing the Web Context)

Initialization and destruction

javax.servlet.ServletContextListener and

ServletContextEvent

Attribute added, removed, or replaced

javax.servlet.ServletContextAttributeListener and

ServletContextAttributeEvent

Session (See Maintaining Client State)

Creation, invalidation, activation, passivation, and timeout

javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and

HttpSessionEvent

Attribute added, removed, or replaced

javax.servlet.http.HttpSessionAttributeListener and

HttpSessionBindingEvent

Request

A servlet request has started being processed by web components

javax.servlet.ServletRequestListener and

ServletRequestEvent

Attribute added, removed, or replaced

javax.servlet.ServletRequestAttributeListener and

ServletRequestAttributeEvent

 

getRequestDispatcher(String) VS getNamedDispatcher(String)

What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class?

NamedDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

getNamedDispatcher(String) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.

Example: Deployment Descriptor


<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.example.ServletExample</servlet-class>
</servlet>

 RequestDispatcher dispatch = request.getNamedDispatcher(“FirstServlet”);

dispatch.forward(request, response);

Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements the Servlet interface or extends the HttpServlet class.

RequestDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

 RequestDispatcher dispatch = request.getRequestDispatcher("/tes");

Here "/tes" represents the url-pattern element value of the servlet class.


<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/tes</url-pattern>
</servlet-mapping>

It represents the path of the servlet class. Since both the base as well as target servlet are in the same package structure by just specifying the url-pattern element value we will be able to access the target servlet.

We shouldn't specify the entire path like

 String str = "/WEB-INF/classes/com/example/posr/Test"
 RequestDispatcher dispatch = request.getRequestDispatcher(str);

To forward a request to a JSP page we use

 RequestDispatcher dispatch = request.getRequestDispatcher("/TestJspOne.jsp");

Here "/TestJspOne.jsp" the slash denotes the Jsp page is at the root of the application.

Session timeout VS setMaxInactiveInterval

           

Fact

Web.xml

Method in HttpSession

How to specify

The <session-timeout> element defines the default session timeout interval

setMaxInactiveInterval(int)

Unit

minutes

Seconds

Exact syntax

<session-config>
<session-timeout>10</session-timeout>
</session-config>

 

public void setMaxInactiveInterval(int seconds)

 

How to never expire

 A negative value or zero value causes the session never to expire.

 

If a negative value is passed to this method, the session will never time out.

 

Applicable

for all sessions created in the Web application

Only for Session explicitly created for the particular request

Design Aspect

Declarative way

Programmatic way

 

            What happens when you set setMaxInactiveInterval(0) --------------------? Think.

 

 

Simplify Spring 2.5 MVC configuration with Java annotations.

Simplify Spring 2.5 MVC configuration with Java annotations.

 

Steps:

            Use @Controller to make class to handler web request

            Use @RequestMapping to map with Url

 

Here is the code that maps url pattern with method.

 

 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
    
@Controller
public class SimpleController {
    
    @RequestMapping("/index.html")
    public void indexHandler() {
    }
    
    @RequestMapping("/about.html")
    public void aboutHandler() {
    }
    
    @RequestMapping("/admin.html")
    public void adminHandler() {
    }

 

JSR 250, Common Annotations

JSR 250, Common Annotations for the Java platform,

The Java Community Process (JCP) has put up the review for JSR 250, Common Annotations for the Java Platform. This JSR, suported by Sun Microsystems, BEA and Oracle Corp., is currently targeted for J2SE and J2EE platforms. It aims to develop annotations for common semantic concepts in the J2SE and J2EE platforms that apply across a variety of individual technologies, so that all technologies can use the same version of the annotations, thus ensuring consistency. According to the JSR, "With the addition of JSR 175 (A Metadata Facility for the JavaTM Programming Language) in the Java platform we envision that various JSRs will use annotations to enable a declarative style of programming. It would be unfortunate if these JSRs each independently defined their own annotations for common concepts. It would be especially valuable to have consistency within the J2EE 5.0 component JSRs, but it will also be valuable to allowconsistency between J2EE and J2SE. It is the intention of this JSR to define a small set of common annotations that will be available for use within other JSRs. It is hoped that this will help to avoid unnecessary redundancy or duplication between annotations defined in different JSRs. The exact set of annotations will be developed in consultation with the various specifications leads who are currently planning to use annotations within their JSRs." The comments are due by the 30th of August, 2004.

For the uninitiated, JSR 175 is a metadata facility for the JavaTM Programming Language that would allow classes, interfaces, fields, and methods to be marked as having particular attributes. JSR 175 has released the second proposed final draft.

 

 

simple custom tag to make font red- Just notice steps and basics

 

1)       Create a TLD and put in web-inf

<taglib>

<tlib-version>1.0</tlib-version>

<uri>redtag</uri>

            <tag>

                        <name>redfont</name>

                        <tag-class>com.honeywell.sspglobal.report.dao.RedFont</tag-class>

                        <body-content>JSP</body-content>

            </tag>

</taglib>

 

2)       Create a JSP

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>

<%@ taglib prefix="ganesh" uri="redtag" %>

 

<html:html>

<HEAD>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

            pageEncoding="ISO-8859-1"%>

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<META name="GENERATOR" content="IBM Software Development Platform">

<META http-equiv="Content-Style-Type" content="text/css">

<LINK href="../theme/Master.css" rel="stylesheet"

            type="text/css">

<TITLE></TITLE>

</HEAD>

 

<BODY>

<ganesh:redfont> This is to Test Ganesh</ganesh:redfont><br>

 

</BODY>

</html:html>

 

3)       Create a Tag handler class

 

 

package com.honeywell.sspglobal.report.dao;

import java.io.IOException;

 

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.tagext.TagSupport;

 

public class RedFont extends TagSupport

{

      JspWriter out;

      public int doStartTag() throws JspException

      {

                  out =pageContext.getOut();

                  System.out.println("In doStart Tag");

                  try

                  {

                  out.println("<font color=\"red\">");

                  }catch(IOException ie)

                  {

                              ie.getMessage();

                  }

                  return EVAL_BODY_INCLUDE;  

      }

     

      public int doEndTag() throws JspException

      {

                  try

                  {

                  out.println("<//font>");

                  }catch(IOException ie)

                  {

                              ie.getMessage();

                  }

                  return EVAL_PAGE;     

     

      }

     

}

Using the Math class

Using the Math class

 

The Math class is final and all the methods defined in the Math class are static, which means you cannot inherit from the Math class and override these methods. Also, the Math class has a private constructor, so you cannot instantiate it.

The Math class has the following methods: ceil(), floor(), max(), min(), random(), abs(), round(), sin(), cos(), tan(), and sqrt().

If you pass a negative number to the sqrt() function, it returns NaN ("Not a Number").

 

Difference between String ,StringBuffer and StringBuilder

String is immutable whereas StringBuffer and StringBuilder can change their values.

The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among String, StringBuffer and StringBuilder

  1. If your text is not going to change use a string Class because a String object is immutable.
  2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
  3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous

 

 

 

 

How to create Immutable Objects

A Strategy for Defining Immutable Objects

 

 

·  Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

·  Make all fields final and private.

·  Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

 

Eg Code here:

 
final public class ImmutableRGB {
 
    //Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;
 
    public ImmutableRGB(int red, int green, int blue, String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }
    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }
    public String getName() {
        return name;
    }
}

 

Static Import - Java 5

Static imports are another convenience feature added to version 1.5 that extends the way imports work in Java. For example, consider the code fragment shown below that calls the static ceil() method on the java.lang.Math class





 
// x is a number of type double such as 98.765



 
double y = Math.ceil(x);



With static imports in 1.5, you can ask the Java compiler to import only a class's static portions, as shown, for example, in the rewritten code fragment below:





 
// Import declaration at the top of the class along with the other imports



 
import static java.lang.Math.ceil;


// And then somewhere in the code...





 
// x is a number of type double such as 5.345



 
double y = ceil(x);


In the above fragment, I used the new static import feature to import the static method ceil() from the Math class. Now when I call the method, I don't have to qualify it with Math. If I wanted to use multiple static methods from the Math class, I could import them individually or all at once as shown below:

 

 

Tips in LifeCycle Method of Servlet

 

Ø       Please note that init(ServletConfig config) is defined in Servlet Interface and it is the actual life cycle method.

 

Ø      Abstract Classes Genericservlet has only init()
          A convenience method which can be overridden so that there's no need to call super.init(config)

 

Ø       HttpServlet service method implementation is nothing but to find http method type of request like get , post and call appropriate doGet,doPost,do*….. methods

Ø       Never override HttpServlet service method

 

 

JDK 5 enum

Enumerated Types

Let's kick this one off with a quick look at the way we used to simulate enumerated types:

class FizzyDrink {
 static final int PEPSI = 1;
 static final int COKE = 2;
 static final int SCHWEPPES = 3
}

What's the problem here? We now have 3 FizzyDrink types: FizzyDrink.PEPSI, FizzyDrink.COKE, and FizzyDrink.SCHWEPPES, right? Well, not really. We actually just have 3 int values. Take a look at the following code:

int todaysFizzyDrink = 237; // ouch, this shouldn't happen!

This approach is type-unsafe, which means the compiler isn't able to force users of our class to use one of the acceptable values we've defined. Furthermore, because constants are compiled into each class that uses them, this approach can sometimes lead to subtle bugs in code -- you have to remember to track down and recompile every other dependant class each time you need change the class that contains your constants!

Here's the new way:

enum FizzyDrink { pepsi, coke, schweppes }

Notice the use of the enum keyword in place of the class keyword? An enum is really just a special kind of class. Here's an example of this enum in use:

FizzyDrink todaysFizzyDrink = FizzyDrink.pepsi;

Now, we really do have a FizzyDrink type. In fact, if we printed the value of todaysFizzyDrink, we'd get the string pepsi and not some meaningless integer value. Here's the really cool part: no dependant class recompilation is required, and Java will even warn you when you change an enumerated type but still have code elsewhere that uses the old enumerated values!

 

 

 

OpenSource for rapidly developing form-based web applications

J2EE Spider is a new open source tool for rapidly developing form-based web applications. The objectives of J2EE Spider are simple:

Generating codes whenever you want, with whatever you want and however you want.

When allow us to generate codes not only in the beginning of the project, but also to perform an incremental build. This concept of successive builds uses merge whenever necessary so that it won't lose customizations that may have been done in the code.

With what is the flexibility in the choice of frameworks? This allows the developer to decide which technologies will be part of the generated code, taking advantage of his/her team's know-how. In the future, it is intended to allow the generation with the greatest possible number of frameworks.

How allows us to alter the generation code template so that the generated code will be as similar as possible to the development methodology of each team. It is also possible to add new resources to the standard code generation in an easy and simple way.

Key features of J2EE Spider include:

  • Visual interface for generating code
  • Integration with Eclipse
  • Incremental builds
  • Round-trip engineering
  • Generated code is Internationalized
  • Code generation using templates
  • Supports multiple frameworks

As well as being able to provide custom page templates for your applications, new technologies can be integrated as necessary. However, for "out of the box" functionality the following technologies are provided:

  • Web frameworks: Struts, JSF and Mentawai ( Brazilian web application framework)
  • Dependency Injection Containers: Spring
  • O/R Mapping: Hibernate
  • Page Templates: SiteMesh and Facelets