Archive for January, 2007

JavaSercer Pages Figure 16.4. A JSP page with (Drupa hosting)

Wednesday, January 17th, 2007

JavaSercer Pages Figure 16.4. A JSP page with HTML source processed by the action Note how the body of the action in Example 16.1 contains HTML elements. Unless the special characters were converted to HTML character entities, the browser would interpret the HTML and show the result instead of the elements themselves. Besides static text, the action body can contain any JSP element. A more realistic example of the use of this action is to insert text from a database into a JSP page, without having to worry about how special characters in the text are interpreted by the browser. The tag handler class is very trivial, as shown in Example 16.2. Example 16.2. The EncodeHTMLTag Class package com.ora.jsp.tags.generic; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.ora.jsp.util.*; public class EncodeHTMLTag extends BodyTagSupport { public int doAfterBody( ) throws JspException { BodyContent bc = getBodyContent( ); JspWriter out = getPreviousOut( ); try { out.write(StringFormat.toHTMLString(bc.getString( ))); } catch (IOException e) {} // Ignore return SKIP_BODY; } } The action doesn’t have any attributes, so the tag handler doesn’t need any instance variables and property access methods. The tag handler can reuse all BodyTag methods implemented by the BodyTagSupport class except for the doAfterBody( ) method. In the doAfterBody( ) method, two utility methods provided by the BodyTagSupport class are used. The getBodyContent( ) method returns a reference to the BodyContent object that contains the result of processing the action’s body. The getPreviousOut( ) method returns the BodyContent of the enclosing action (if any) or the main JspWriter for the page if the action is at the top level. page 220
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

Subdomain web hosting - JavaSercer Pages The tag handler gets a reference

Wednesday, January 17th, 2007

JavaSercer Pages The tag handler gets a reference to the BodyContent object through the setBodyContent( ) method: … protected BodyContent bodyContent; … public void setBodyContent(BodyContent b) { this.bodyContent = b; } The BodyTagSupport class simply saves the reference to the BodyContent object in an instance variable. Next, the container gives the tag handler a chance to initialize itself before the body is processed by calling doInitBody( ): public void doInitBody( ) throws JspException { } The implementation in BodyTagSupport does nothing. A tag handler can, however, use this method to prepare for the first pass through the action body, perhaps initializing scripting variables that it makes available to the body. We look at this in more detail later. A tag handler that doesn’t introduce variables rarely overrides this method. When the body has been processed, the doAfterBody( ) method is invoked: public int doAfterBody( ) throws JspException { return SKIP_BODY; } A tag handler can use this method to read the buffered body content and process it in some way. This method also gives the tag handler a chance to decide whether the body should be processed again. If so, it returns the EVAL_BODY_TAG value. We’ll look at an example of an iteration action that takes advantage of this later. The BodyTagSupport implementation returns SKIP_BODY to let the processing continue to the doEndTag( ) method. As with a tag handler implementing the Tag interface, this method returns either EVAL_PAGE or SKIP_PAGE. Let’s look at a tag handler class that extends the BodyTagSupport class. The EncodeHTMLTag class is the tag handler class for a custom action called . This action reads its body, replaces all characters with special meanings in HTML (single quotes, double quotes, less-than and greater-than symbols, and ampersands) with their corresponding HTML character entities (', ", <, >, and &) and inserts the result in the response body. Example 16.1 shows how the action can be used in a JSP page, and Figure 16.4 what the processed result looks like in a browser. Example 16.1. A JSP Page Using the Action <%@ page language="java" %> <%@ taglib uri="/orataglib" prefix="ora" %>

Encoded HTML Example

The following text is encoded by the <ora:encodeHTML> custom action:

      HTML 3.2 Documents start with a   declaration followed by an HTML element containing  a HEAD and then a BODY element:          A study of population dynamics  … other head elements      … document body          

page 219
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

JavaSercer Pages 16.3 Processing the Action Body As (Hosting j2ee)

Wednesday, January 17th, 2007

JavaSercer Pages 16.3 Processing the Action Body As you can see, it’s easy to develop a tag handler that doesn’t need to do anything with the action element’s body. For a tag handler that does need to process the body, however, just a few more methods are needed. They are defined by the BodyTag interface, which extends the Tag interface. The action element’s body has many possible uses. It can be used for input values spanning multiple lines; the SQL custom actions introduced in Chapter 9, use the body this way. The SQL statement is often large, so it’s better to let the page author write it in the action body instead of forcing it to fit on one line, which is a requirement for an attribute value. The body can also contain nested actions that rely on the enclosing action in some way. The action, also from Chapter 9, provides the nested SQL actions with the DataSource object they use to communicate with the database, and ensures that the SQL statements in all actions are treated as one transaction that either fails or succeeds. A third example is an action that processes the body content in one way or another before it’s added to the response. Chapter 12, contains an example of an action that processes its XML body using the XSL stylesheet specified as an attribute. Later in this section we look at an action that replaces characters that have special meanings in HTML with the corresponding HTML character entities. As with the Tag interface, there’s a BodyTagSupport class that implements all the methods of the BodyTag interface, plus a few utility methods: public class BodyTagSupport extends TagSupport implements BodyTag { A tag handler that implements the BodyTag interface is at first handled the same way as a tag handler implementing the Tag interface: the container calls all property setter methods and the doStartTag( ) method. But then things divert, as illustrated in Figure 16.3. Figure 16.3. BodyTag interface methods First of all, the BodyTagSupport class overrides the doStartTag( ) method inherited from the TagSupport class: public int doStartTag( ) throws JspException { return EVAL_BODY_TAG; } Instead of returning SKIP_BODY, like the TagSupport class does, it returns EVAL_BODY_TAG . The EVAL_BODY_TAG value is valid only for a tag handler that implements the BodyTag interface. It means that not only should the action’s body be processed, but the container must also make the result available to the tag handler. To satisfy this requirement, the container uses a BodyContent object. This is a subclass of the JspWriter, the class used to write text to the response body. In addition to the inherited methods for writing to the object, the BodyContent class has methods that the tag handler can use to read the content. This is how it works. The JSP container assigns a reference to a JspWriter to the implicit out variable at the top of the page. Everything that’s added to the response body - either explicitly by JSP elements or implicitly by the JSP container (template text) - is written to out, so it ends up in the JspWriter before it’s sent to the browser. When the JSP container encounters a custom action with a tag handler that implements the BodyTag interface, it temporarily reassigns out to a BodyContent object until the action’s end tag is encountered. The content produced when the element body is processed is therefore buffered in the BodyContent object where the tag handler can read it. page 218
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

JavaSercer Pages The maxAge attribute is optional, so (Hosting paypal)

Wednesday, January 17th, 2007

JavaSercer Pages The maxAge attribute is optional, so before the corresponding String value is converted into an int, a test is performed to see if it is set or not. You may wonder why similar tests are not done for the name and value variables. The reason is that the JSP container verifies that all mandatory attributes are set in the custom action. If a mandatory attribute is not set, the JSP container refuses to process the page, so you can always be sure that a variable corresponding to a mandatory attribute has a value. I describe how to specify a mandatory attribute at the end of this chapter. The code that actually creates the Cookie object and adds it to the response object is executed by the sendCookie( ) method in the com.ora.jsp.util.CookieUtils class. This is a pretty common practice; the tag handler is just a simple adapter for logic that’s implemented in another class, providing a JSP-specific interface to the reusable class. One last thing to note in this example is that the property setter method for the maxAge attribute, and the corresponding instance variable, is of type String, even though it’s later converted to an int before it’s used. In a regular bean, you would likely make it a property of type int to begin with instead. Using a String property and converting it to an int in the tag handler is not necessarily the best implementation strategy, but it’s the safest. A JSP 1.1-compliant container should automatically convert a literal string attribute value to the appropriate type, as shown in Table 16.1. Table 16.1, Conversion of String Value to Property Type Property Type Conversion Method boolean or Boolean Boolean.valueOf(String) byte or Byte Byte.valueOf(String) char or Character String.charAt(int) double or Double Double.valueOf(String) int or Integer Integer.valueOf(String) float or Float Float.valueOf(String) long or Long Long.valueOf(String) This is a very recent clarification of the specification, documented in the specification errata document available at http://java.sun.com/products/jsp/. Even though Tomcat 3.2 works according to the updated specification, other early implementations may not. If the conversion from a String to the appropriate type is not done by the container, a page author has to use a request-time attribute expression to set a non-String attribute value: tomcat hosting services

Mambo hosting - JavaSercer Pages This method gives the tag handler

Tuesday, January 16th, 2007

JavaSercer Pages This method gives the tag handler a chance to initialize itself, perhaps verifying that all attributes have valid values. Another use for this method is to decide what to do with the element’s body content, if a body exists. The method returns an int, which must be one of two values defined by the Tag interface: SKIP_BODY or EVAL_BODY_INCLUDE. The default implementation returns SKIP_BODY. As the name implies, this tells the JSP container to ignore the body completely. If EVAL_BODY_INCLUDE is returned instead, the JSP container processes the body (for instance, executes scripting elements and other actions in the body) and includes the result in the response. A simple conditional tag - a replacement for a scriptlet with an if statement - can be created by testing some condition (set by action attributes) in the doStartTag( ) and returning either SKIP_BODY or EVAL_BODY_INCLUDE, depending on if the condition is true or false. No matter which value the doStartTag( ) method returns, the JSP container calls doEndTag( ) when it encounters the end tag: public int doEndTag( ) throws JspException { return EVAL_PAGE; } This is the method that most tag handlers override to do the real work. It can also return one of two int values defined by the Tag interface. The TagSupport class returns EVAL_PAGE, telling the JSP container to continue to process the rest of the page. But a tag handler can also return SKIP_PAGE, which aborts the processing of the rest of the page. This is appropriate for a tag handler that forwards processing to another page or that sends a redirect response to the browser, like the custom action introduced in Chapter 8. An example of a custom action that can be implemented as a simple tag handler is the action, introduced in Chapter 10. The tag handler class is called com.ora.jsp.tags.generic.AddCookieTag and extends the TagSupport class to inherit most of the Tag interface method implementations: package com.ora.jsp.tags.generic; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.ora.jsp.util.*; public class AddCookieTag extends TagSupport { The action has two mandatory attributes, name and value, and one optional attribute, maxAge. Each attribute is represented by an instance variable and a standard property setter method: private String name; private String value; private String maxAgeString; public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public void setMaxAge(String maxAgeString) { this.maxAgeString = maxAgeString; } The purpose of the custom action is to create a new javax.servlet.Cookie object, with the name, value, and max age values specified by the attributes, and to add the cookie to the response. The tag handler class overrides the doEndTag( ) method to carry out this work: public int doEndTag( ) throws JspException { int maxAge = -1; if (maxAgeString != null) { try { maxAge = Integer.valueOf(maxAgeString).intValue( ); } catch (NumberFormatException e) { throw new JspException(”Invalid maxAge: ” + e.getMessage( )); } } CookieUtils.sendCookie(name, value, maxAge, (HttpServletResponse) pageContext.getResponse( )); return EVAL_PAGE; } page 216
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

JavaSercer Pages 16.2 (Ez web hosting) Developing a Simple Action As

Tuesday, January 16th, 2007

JavaSercer Pages 16.2 Developing a Simple Action As you have seen in the previous chapters, a custom action element in a JSP page consists of a start tag (possibly with attributes), a body, and an end tag:
The body If the action element doesn’t have a body, the following shorthand notation can be used instead of the start tag and the end tag:
A tag handler is the object invoked by the JSP container when a custom action is found in a JSP page. In order for the tag handler to do anything interesting, it needs access to all information about the request and the page, as well as the action element's attribute values (if any). At a minimum, the tag handler must implement the Tag interface, which contains methods for giving it access to the request and page information, as well as methods called when the start tag and end tag are encountered. Note that an action element supported by a tag handler that implements the Tag interface may have a body, but the tag handler has more limited control over the body content than a tag handler that implements the BodyTag interface. For the attribute values, the JSP container treats the tag handler as a bean and calls a property setter method corresponding to each attribute, as shown in Figure 16.2. Figure 16.2. Tag interface methods and property setter methods Here are the most important methods of the Tag interface: public void setPageContext(PageContext pageContext); public int doStartTag( ) throws JspException; public int doEndTag( ) throws JspException; To be complete, let's first look at the implementation of these methods provided by the TagSupport class. This is the class that most simple tag handlers extend, so it's important to know how TagSupport implements the methods a tag handler inherits. The first method of interest is the setPageContext( ) method: public class TagSupport implements Tag, Serializable { ... protected PageContext pageContext; ... public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } This method is called by the JSP container before the tag handler is used. The TagSupport implementation simply sets an instance variable to the current PageContext object. The PageContext provides access to the request and response objects and all the JSP scope variables, and it implements a number of utility methods that the tag handler may use. Appendix B, includes a complete list of all PageContext methods. When the start tag is encountered, the JSP container calls the doStartTag( ) method, implemented like this in the TagSupport class: public int doStartTag( ) throws JspException { return SKIP_BODY; } page 215
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services

Cpanel hosting - JavaSercer Pages A tag library is a collection

Tuesday, January 16th, 2007

JavaSercer Pages Chapter 16. Developing JSP Custom Actions (Oscommerce hosting)

Tuesday, January 16th, 2007

JavaSercer Pages Chapter 16. Developing JSP Custom Actions Custom actions let you encapsulate logic and make it available to page authors in a familiar format. Throughout this java blog, a number of generic custom actions are used for such tasks as accessing a database, including localized content, encoding URLs, and much more. Using these actions, the amount of Java code in the JSP pages can be kept to a minimum, making the application easier to debug and maintain. However, for a complex application, the generic actions presented in this java blog are not enough. Perhaps you want to develop application-specific actions to access the database instead of putting SQL statements in the JSP pages. Or you may want to present complex data as a set of nested HTML tables with cells formatted differently depending on their values. Instead of using conditional scripting code in the JSP page to generate this table, an application-specific custom action can be used. Custom actions know about their environment. They automatically get access to all information about the request, the response, and all the variables in the JSP scopes. Another common use for a custom action is as an HTTP-specific adapter to a bean. JavaBeans components are frequently used in a JSP application, and a bean is easier to reuse if it doesn’t know about the environment where it’s used. To develop a custom action, you use a set of classes and interfaces referred to in the JSP 1.1 specification as the tag extension mechanism. The simplest custom action implementation is just a class with bean-like accessor methods plus a couple of other well-defined methods. But it’s a very powerful mechanism, letting you develop custom actions to do pretty much anything. As always, with increased power comes some amount of complexity. For more advanced actions you need to implement additional methods, and in some cases an extra class. But it’s still not rocket science. We’ll take it step by step, starting with the most common and simple cases, and then work through some examples of the advanced features in the later sections of this chapter. 16.1 Tag Extension Basics A custom action - actually a tag handler class for a custom action - is basically a bean with property setter methods corresponding to the custom action element’s attributes. In addition, the tag handler class must implement one of two Java interfaces defined by the JSP specification. All the interfaces and classes you need to implement a tag handler are defined in the javax.servlet.jsp.tagext package. The two primary interfaces are named Tag and BodyTag. The Tag interface defines the methods you need to implement for any action. The BodyTag interface extends the Tag interface and adds methods used to access the body of an action element. To make it easier to develop a tag handler, two support classes are defined by the API: TagSupport and BodyTagSupport, as shown in Figure 16.1. These classes provide default implementations for the methods in the corresponding interface. Figure 16.1. The primary tag extension interfaces and support classes The reason the specification defines both interfaces and the support classes that implement those interfaces is simply to cover all the bases. If you already have a class with functionality that you want to access as a custom action, you can specify that it implements the appropriate interface and add the few methods defined by that interface. In practice, though, I recommend that you implement your tag handlers as extensions to the support classes. This way, you get most of the methods implemented for free, and you can still reuse the existing classes by calling them from the tag handler. page 213

Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services

Iowa web hosting - JavaSercer Pages Both the getNewsItems( ) and the

Monday, January 15th, 2007

JavaSercer Pages Both the getNewsItems( ) and the removeNewsItem( ) methods synchronize on the newsItems object, and the addElement( ) method used in setNewsItem( ) is a synchronized method. The effect is that while one thread is manipulating the list of news items through one of these methods, all other threads wait until the current thread leaves the synchronized block. The setNewsItem( ) method also synchronizes on idSequence, a variable used to generate a unique ID for each item. idSequence is an int array with one component. It’s a neat trick to be able to use synchronization for an integer value: Java doesn’t allow synchronization on primitive types, only on objects, but an array is an object. You could use an Integer object instead, but you can’t change the value of an Integer. To increment the value, a new Integer must be created. Using an array avoids these repeated object creations (and creating an object is a fairly expensive operation in Java). Another approach that avoids multithreading problems is used in the utility beans in this java blog, such as the CounterBean used in Chapter 8 and the EmployeeRegistryBean described in the previous section. These beans only define setter methods for customization that takes place when the bean is created, and define all data needed to perform a function as method arguments instead of properties. Each thread has its own copies of argument values and local variables, so with this approach there’s no risk of one thread stepping on another. 15.3 Unexpected Behavior The action can be used to automatically set all properties in a bean with names matching the names of the parameters received with the request. This is a great feature that’s used in many of the examples in this java blog. But unless you know how this works behind the scenes, you could be in for a surprise. When the code is invoked, it gets a list of all request parameter names and uses bean introspection to find the corresponding property setter methods. It then calls all setter methods to set the properties to the values of the parameters. This means that if you have a property in your bean that doesn’t match a parameter, the setter method for this property is not called. In most cases, this is not surprising. However, if the parameter is present in some requests but not in others, things may get a bit confusing. This is the case with parameters corresponding to checkbox, radio button, and selection list elements in an HTML form. If this type of element is selected, the browser sends a parameter with the element’s name and the value of the selected item. But if the element is not selected, it doesn’t send a parameter at all. For example, let’s say you have a bean with an indexed property, such as the projects property in the com.ora.jsp.beans.emp.EmployeeBean used in Chapter 10. This bean is kept in the session scope. The user can change the value of the property through a group of checkboxes in a form. To unregister all projects, a user deselects all checkboxes and submits the form. You may think the following code would then clear the property (setting it to null): Yet it doesn’t. Without any checkbox selections, the projects parameter is not sent and the corresponding property setter method is not called. The workaround used in Chapter 10 is to use a request-time attribute expression to explicitly set the property to either the array of selected checkboxes or null if none is selected: February 2007

  • January 2007
  • December 2006
  • November 2006
  • October 2006
  • Categories