Archive for the 'Java' Category

JavaSercer Pages The JSP 1.1 specification defines that (Servlets hosting)

Thursday, January 18th, 2007

JavaSercer Pages The JSP 1.1 specification defines that an attribute named id typically is used to name a variable created by an action.7 The value of the id attribute must be unique within the page. Because it’s used as a scripting variable name, it must also follow the variable name rules for the scripting language. For Java, this means it must start with a letter followed by a combination of letters and digits, and must not contain special characters, such as a dot or a plus sign. The attribute used in another action to refer to the variable can be named anything, but the convention established by the standard actions is to call it name. When a custom action creates a variable, it must cooperate with the JSP container to make it happen. To understand how this works, recall that the JSP page is turned into a servlet by the JSP container. The JSP container needs to generate code that declares the scripting variable in the generated servlet and assigns the variable a value. Before getting into how the tag handler and the container cooperate, let’s look at the kind of code that is generated for the custom action introduced in Chapter 8. Here’s a JSP page fragment: <% prod.getName( ); %> The action creates an instance of the CatalogBean (or locates an existing instance) and saves it in the page scope with the name catalog. It also declares a scripting variable named catalog and sets it to the same CatalogBean instance. The custom action retrieves the product property from the CatalogBean and introduces it as a page scope object named prod and a scripting variable with the same name, in the same manner as the action. Finally, the value of prod is added to the response twice: first using the action, and then again using a JSP expression. This JSP page fragment results in code similar to Example 16.5 in the generated servlet. Example 16.5. Code Generated for JSP Actions // Code for com.ora.jsp.beans.shopping.CatalogBean catalog = null; catalog= (com.ora.jsp.beans.shopping.CatalogBean) pageContext.getAttribute(”catalog”,PageContext.PAGE_SCOPE); if ( catalog == null ) { try { catalog = (com.ora.jsp.beans.shopping.CatalogBean) Beans.instantiate(getClassLoader( ), “com.ora.jsp.beans.shopping.CatalogBean”); } catch (Exception exc) { throw new ServletException (”Cannot create bean of class “+ “com.ora.jsp.beans.shopping.CatalogBean”); } pageContext.setAttribute(”catalog”, catalog, PageContext.PAGE_SCOPE); } … // Code for com.ora.jsp.tags.generic.UsePropertyTag _jspx_th_ora_useProperty_1 = new com.ora.jsp.tags.generic.UsePropertyTag( ); _jspx_th_ora_useProperty_1.setPageContext(pageContext); _jspx_th_ora_useProperty_1.setParent(null); _jspx_th_ora_useProperty_1.setId(”prod”); _jspx_th_ora_useProperty_1.setName(”catalog”); _jspx_th_ora_useProperty_1.setProperty(”product”); _jspx_th_ora_useProperty_1.setArg(”1″); _jspx_th_ora_useProperty_1.setClassName( “com.ora.jsp.beans.shopping.ProductBean”); try { _jspx_th_ora_useProperty_1.doStartTag( ); if (_jspx_th_ora_useProperty_1.doEndTag( ) == Tag.SKIP_PAGE) return; } finally { _jspx_th_ora_useProperty_1.release( ); } com.ora.jsp.beans.shopping.ProductBean prod = null; prod = (com.ora.jsp.beans.shopping.ProductBean) pageContext.findAttribute(”prod”); … // Code for out.print(pageContext.findAttribute(”prod”), “name”))); … // Code for <%= prod.getName( ) %> out.print( prod.getName( ) ); 7 If an action creates more than one variable, the id attribute is typically used to name one of them. page 224
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services

JavaSercer Pages The class has two instance variables, (Mambo hosting)

Thursday, January 18th, 2007

JavaSercer Pages The class has two instance variables, name and value, and the corresponding setter methods. The most interesting method is the doEndTag( ) method. This method first uses the findAncestorWithClass( ) method to try to locate the enclosing EncodeURLTag instance. Note that this is not the class name used as the argument value. Instead, the ParamParent interface is used. The reason is that the action is supported in the body of other actions besides , such as the action. The ParamParent interface is implemented by all tag handlers for actions that can contain nested actions: package com.ora.jsp.tags.generic; public interface ParamParent { void setParam(String name, String value); } The interface defines one method: the setParam( ) method. This is the method the nested ParamTag tag handler uses to communicate with its parent. For each nested action, the setParam( ) method gets called when the parent’s action body is processed. The name and value for each action are accumulated in the parent tag handler, ready to be used when the parent’s doEndTag( ) method is called. Example 16.4 shows the setParam( ) and doEndTag( ) methods implemented by the EncodeURLTag class. Example 16.4. EncodeURLTag … private Vector params; … public void setParam(String name, String value) { if (params == null) { params = new Vector( ); } Param param = new Param(name, value); params.addElement(param); } public int doEndTag( ) throws JspException { StringBuffer encodedURL = new StringBuffer(url); if (params != null && params.size( ) > 0) { encodedURL.append(’?'); boolean isFirst = true; Enumeration e = params.elements( ); while (e.hasMoreElements( )) { Param p = (Param) e.nextElement( ); if (!isFirst) { encodedURL.append(’&'); } encodedURL.append(p.getName( )).append(’='). append(p.getValue( )); isFirst = false; } } try { HttpServletResponse res = (HttpServletResponse) pageContext.getResponse( ); JspWriter out = pageContext.getOut( ); out.print(res.encodeURL(encodedURL.toString( ))); } catch (IOException e) {} return SKIP_BODY; } In setParam( ), the parameter name and value are saved as instances of a simple value holder class named Param, held in a Vector. In the doEndTag( ) method, each parameter’s name/value pair is added to the URL before the complete URL is encoded to support session tracking through URL rewriting. If you don’t remember what all of this means, you can refresh your memory by looking at Chapter 8 again. 16.5 Creating New Variables Through Actions Actions can also cooperate through objects available in the standard JSP scopes (page, request, session, and application). One example of this type of cooperation is illustrated by the three standard JSP actions: , , and . The action creates a new object and makes it available in one of the JSP scopes. The other two actions can then access the properties of the object by searching for it in the scopes. Besides making the object available in one of the scopes, the action also makes it available as a scripting variable, so it can be accessed by scripting elements in the page. page 223
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

JavaSercer Pages This is part of (Servlet hosting) the puzzle.

Thursday, January 18th, 2007

JavaSercer Pages This is part of the puzzle. However, a tag handler is usually interested only in finding a parent it’s been designed to work with. It would be nice to have a method that works its way up the hierarchy until it finds the parent of interest. That’s exactly what the findAncestorWithClass( ) method implemented by the TagSupport class does: public static final Tag findAncestorWithClass(Tag from, Class klass) { boolean isInterface = false; if (from == null || klass == null || (!Tag.class.isAssignableFrom(klass) && !(isInterface = klass.isInterface( )))) { return null; } for (;;) { Tag tag = from.getParent( ); if (tag == null) { return null; } if ((isInterface && klass.isInstance(tag)) || klass.isAssignableFrom(tag.getClass( ))) return tag; else from = tag; } } First of all, note that this is a static method. Consequently, it can be used even by tag handlers that implement the Tag interface directly, instead of extending the TagSupport class. The method takes two arguments: the tag handler instance to start searching from, and the class or interface of the parent. After making sure that all parameters are valid, it starts working its way up the nested tag handlers. It stops when it finds a tag handler of the specified class or interface and returns it. If the specified parent type is not found, the method returns null. This is all that’s needed to let a nested action communicate with its parent: the parent accessor methods, and the method that walks the action hierarchy to find the parent of interest. Example 16.3 shows how the ParamTag class uses this mechanism to find the enclosing EncodeURLTag instance. Example 16.3. The ParamTag Class package com.ora.jsp.tags.generic; import java.net.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ParamTag extends TagSupport { private String name; private String value; public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public int doEndTag( ) throws JspException { Tag parent = findAncestorWithClass(this, ParamParent.class); if (parent == null) { throw new JspException(”The param action is not ” + “enclosed by a supported action type”); } ParamParent paramParent = (ParamParent) parent; paramParent.setParam(name, URLEncoder.encode(value)); return EVAL_PAGE; } } page 222
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services

Comcast webspace - JavaSercer Pages You may be wondering why the

Thursday, January 18th, 2007

JavaSercer Pages You may be wondering why the method is called getPreviousOut( ) as opposed to getOut( ). The name is intended to emphasize the fact that you want to use the object assigned as the output to the enclosing element in a hierarchy of nested action elements. Say you have the following action elements in a page: Some template text The JSP container first creates a JspWriter and assigns it to the out variable for the page. When it encounters the action, it creates a BodyContent object and temporarily assigns it to the out variable. It creates another BodyContent for the action and, again, assigns it to out. The container keeps track of this hierarchy of output objects. Template text and output produced by the standard JSP elements end up in the current output object. Each element can get access to its own BodyContent object by calling the getBodyContent( ) method and reading the content. For the element, the content is the template text. After processing the content, it can write it to the body by getting the BodyContent for this element through the getPreviousOut( ) method. Finally, the element can process the content provided by the element and add it to the top-level output object: the JspWriter object it gets by calling the getPreviousOut( ) method. The tag handler in Example 16.2 converts all the special characters it finds in its BodyContent object using the toHTMLString( ) method in the com.ora.jsp.utils.StringFormat class, introduced in Chapter 6. It gets the content of the BodyContent by using the getString( ) method, and uses it as the argument to the toHTMLString( ) method. The result is written to the JspWriter obtained by calling getPreviousOut( ). The doAfterBody( ) method then returns SKIP_BODY, since no iteration is needed. 16.4 Letting Actions Cooperate Now that you’ve seen how to develop basic tag handlers, let’s discuss some more advanced features. In this section, we look at tag handlers that let a page author use custom actions that cooperate with each other. You have seen examples of this throughout this java blog. For instance, in Chapter 9, various types of value actions are nested within the body of an action to set the values of place holders in the SQL statement. Another example is the action with nested actions, which are used in Chapter 8: servlet hosting services

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