Enterprise Java Technology Development Skills 2

Source: Internet
Author: User
Tags foreach define empty expression naming convention new features time and date valid
Tips for reading this issue of Enterprise Java Technologies Tech tips. Below you will get tips for using the Enterprise Java technology and APIs, such as Java 2 Platform and Enterprise Edition.

This article discusses:

Custom tag file
Use Enterprise Beans with JSP Pages
These techniques are developed using the Java 2, Enterprise Edition, v 1.4 SDK. You can download the SDK, the URL is http://java.sun.com/j2ee/1.4/download-dr.html.

The problem with Tech Tips is written by Mark Johnson, president of ELUCIFY Technical Communications and designing Enterprise applications with the J2E E Platform, one of the authors of 2nd Edition. Mark Johnson is in charge of an open forum to discuss these techniques.

You can download a sample archive of these tips. The context root of the application is the ttfeb2004,index.html welcome file that indicates how to use the sample code. Use of the following code and/or information should be subject to the license terms.

Custom tag file
Custom tags in JSP pages look like HTML tags. Custom tags are replaced with text at run time, which is output by a handler class that is associated with the tag. The previous Enterprise Tech Tip Using Custom Tag Describes how to create a class like this. This month's first tip will introduce a new and easier way to implement custom tags.

Before JSP 2.0, the only way to create a custom tag is to implement it as a Java tag handler class. The handler class developer also needs to create a TLD file that is responsible for describing the markup for the Web container. Although the custom tag is powerful, it also requires programming skills and an in-depth understanding of how JSP pages are translated into HTML.

The new features of the JSP 2.0 tag file enable non-programmers to write reusable markup. It also makes programming life easier for programmers. The JSP 2.0 syntax is used with the JavaServer Pages Standard tag Library (JSTL) and its expression language (EL) to create custom tags without writing any Java code.

A tag file is a reusable component of a JSP page. It has many advantages:

Can be used to hide or remove scriptlet.
Increase the reusability of your code by referencing rather than by cutting and pasting.
Makes JSP pages easier to write, more visually consistent, and easier to maintain.
Can be written by non-programmers.
Its syntax is closer to HTML than Java, so JSP pages look more like written in one language.
You can compose advanced components to increase productivity and development speed.
The TLD files used by custom tags are usually automatically generated.
Can be used to refactor an existing page. The common part of the code can be merged into a tag file that can be shared between application views.
The tag file does not completely override the custom tag handle class. Tag files are preferable when encapsulation of reusable content with relevant layouts and representations. When you reuse application logic (application logic) in JSP pages, custom tags are better. For example, headers and footers are the forte of tag files. In contrast, custom tags in JSTL are implemented as Java language handler classes.

Mark File Details

In fact, tag files are translated and compiled into tag handle classes. The only difference between a tag handler and a tag handler class is that the tag handler is written in JSP syntax and the tag handler class is written in the Java language.

The JSP 2.0 compliant container looks for tag files in the Web archive path web-inf/tags. Tag files can also be packaged into JAR files under Web-inf/lib. When a Web container serves a JSP page, the output of the JSP content in that tag file is parsed and included in the response stream whenever the container encounters a tag associated with the tag file. Tag files define properties and have full access to the expression language (EL) of JSP 2.0. The tag file can also create an EL variable that can continue to exist after its execution has completed.

The tag file declares its properties with a property directive. Here is an example of the sample code that comes with this tip. The tag file starts with a property directive:

<%@ attribute name= "format" required= "false"%>


This tag, used for formatting dates, tells the container that a possible "format" attribute is expected to appear in this line of code. The "required" attribute in the directive is set to "true" for the mandatory property. These directives allow the Web container to generate its own TLD file at deployment time.

tags accept input through their properties. In addition to the output text generated by the markup file, the tag can also "output" data by creating an EL variable. The tag file can return a value to the page that called it, as follows:

<%@ variable name-given= "filesincluded" scope= "At_end"%>


Name-given provides a name for the variable that will be set on the page after the tag is completed. "At_end" specifies that the variable is set at the end of the tag file.

Tag file Example

The sample code in this tip includes a tag file that implements the custom tags developed for the September 2002 Tech Tip "Using custom tags." The original tag can format the date of the server in three ways:

If the format is not set or empty, the tag displays the date in the default format.
If the format parameter starts with a dollar sign, the tag uses the remainder of the string as the name of an environment item. It then marks the lookup of the named environment item and takes its value as a format.
If the format parameter contains a format string (compatible with Java.text.SimpleDateFormat), the string is used to format the date.
The tag file specifies a slightly different markup feature. If the format parameter starts with a dollar sign, the tag looks for a servlet context initialization parameter instead of finding an environment item. (Expression Language JSTL 1.0 does not provide intrinsic support for accessing environment items.) )

This example marks the beginning of file Date.tag with instructions to define the expected properties in the file. It also specifies namespaces for other tag libraries that the tag uses.

<%@ attribute name= "format" required= "false"%>

<%@ taglib uri=

"Http://java.sun.com/jsp/jstl/core" prefix= "C"%>

<%@ taglib uri=

"Http://java.sun.com/jsp/jstl/fmt" prefix= "FMT"%>

<%@ taglib uri=

"Http://java.sun.com/jsp/jstl/functions"

prefix= "FN"%>


The next-generation code block for a date tag file uses the <c:choose> tag to determine the format string. <c:choose> is the tag used to implement the If/then/else function in the JSP page. If the format is not set or empty, the first "when" statement sets the EL variable "format" to the default value. The code is as follows:

<c:choose>

<%--If format is blank, set default--%>

<c:when test= "${format = = NULL or format = = '}" >

<c:set var= "Format"

Value= "eeee, D MMMM yyyy ' at ' kk:mm:ss z"/>

</c:when>

...


If "format" is not empty, it will begin with a "$" or not a "$". In the first case, the <otherwise> statement of the,<choose> tag removes the heading "$" and replaces the "format" variable with the contents of the context parameter with the given name.

<c:otherwise>

<%--Else If format starts with "$",

Look up in the context Param,

and set "format" to its value. --%>

<c:if test= "${fn:substring (format,0,1) = = ' $ '}" >

<c:set var= "Format_name"

Value= "${fn:substringafter (format, ' $ ')}"/>

<c:set var= "Format"

Value= "${initparam[format_name]}"/>

</c:if>



<%--otherwise leave it as it is--%>

</c:otherwise>

</c:choose>


Note that if "format" does not start with a "$", its value remains unchanged.

At this point, the value of the EL variable "format" is assigned to a string that will be used to format the date. The Usebean code line creates a Date object that indicates the current time. The Fmt:formatdate method formats the date with the given "format":

<%--now actually create and format the date--%>

<jsp:usebean id= "Now" class= "Java.util.Date"/>

<fmt:formatdate value= "${now}" pattern= "${format}"/>


The tag file is now complete.

It is easier to use a tag file. Example page datepage.jsp (links to index.jsp in this month's sample archive) a directive stating that all tags under the archive directory (/web-inf/tags) can be accessed using the "mytags" prefix. The directive reads as follows:

<%@ taglib tagdir= "/web-inf/tags" prefix= "Mytags"%>


Now, it's easy to use JSP tag files as if you were using any custom tags. The following code excerpt is from the sample page datepage.jsp:

Server time and date in default format

are <b><mytags:date/></b>.<br>

The server's time zone is

<b><mytags:date format= "zzzz"/></b>.<br>

The server date is

<b><mytags:date format= "m/d/yyyy"/></b>.<br>

Server Time is

<b><mytags:date format= "Hh:mm:ss a"/></b>.<br>


The tag file is invoked every time that the <mytags:date> appears, and the tag is replaced by the server's corresponding time and date in the output.

This example is just a trigger. JSP tag files also have many options that are not mentioned here. To learn more about JSP tag files, read the "Custom Tag in JSP Pages" section of the Java 1.4 Tutorial.

Back to Top

Use Enterprise beans with Jsp Pages
The JSP 2.0 Expression Language (EL) is described in the January 26, 2004 version of Tech Tips. One of the examples in this tip describes how to use an EL variable to access JavaBean by name. JavaBean properties can also be accessed using a simple EL expression. This feature makes EJB components very easy to use in JSP pages. Simply place the Enterprise JavaBeans component (Enterprise beans) required by the application view into the named property and have the JSP page access the property through the name in the EL expression. The best way to illustrate this technique is to give examples.

Sample code

The sample code in this tip is a credit card verification application. Credit card companies have a range of rules that can be used to verify the validity of a credit card number. A credit card number may be valid and overdrawn, expired, or canceled. The purpose of the validity check is to catch data entry errors before the data authorization transfer.

Credit card numbers are valid in the following situations:

There is a correct prefix for the credit card type.
The credit card number has the correct number of digits.
The credit card number passed the checksum test.
The credit card does not expire.
This sample program uses three components:

A stateful session bean creditcardlocal that represents credit card data and performs validation.
A servlet feb2004servlet that creates an instance of the Bean in the session scope so that each user has an instance.
A JSP page validatecard.jsp that collects data and displays the validation results.
The code works like this: A link on the index.jsp form points to the servlet, which creates the session bean handle and places it in the session context. The servlet then sends the request to the URL jsp/validatecard.jsp, which handles card number input and validation. When the user completes the data entry, the form is handed back to itself. In a real-world application, the form is automatically forwarded to the next step in the procurement process when the credit card is properly validated.

The code in the servlet is simple and straightforward. It simply creates a stateful session bean of the creditcardlocal type and places it in a HttpSession attribute in the name of "CreditCard." When the servlet is invoked, if such a variable already exists, the servlet deletes the previous instance.



Creditcardlocal CreditCard = (creditcardlocal)

Req.getsession (). getattribute ("CreditCard");



Remove it if it exists--we ' re starting over.

if (CreditCard!= null) {

try {

Creditcard.remove ();

catch (Exception e) {

System.err.println (

"Exception Removing Card:" + E);

}

System.err.println ("info:removed previous card.");

}



Create New Enterprise Bean Reference in Session scope

try {

InitialContext CTX = new InitialContext ();

Creditcardlocalhome CCLH =

(Creditcardlocalhome) Ctx.lookup (

"Java:comp/env/ejb/creditcard");



String cardname = Req.getparameter ("Cardname");

String Cardtype = Req.getparameter ("Cardtype");

String Cardnumber = Req.getparameter ("Cardnumber");

String carddate = Req.getparameter ("Carddate");



CreditCard = Cclh.create (

Cardname, Cardnumber, Cardtype, carddate);



Req.getsession (). setattribute (

"CreditCard", CreditCard);



catch (Exception e) {

throw new Servletexception (e);

}



RequestDispatcher rd = Req.getrequestdispatcher (

"/jsp/validatecard.jsp");

Rd.forward (req, res);


Notice the last two lines of the code above. After the enterprise bean Reference is created, the servlet sends the request to the VALIDATECARD.JSP page, which processes input and validation.

The first chapter of the page copies any parameters that may have been posted to the page to the corresponding properties of the enterprise bean. Note the <c:set> tag is how to use "Target" and "property" to access the properties of the enterprise bean for the given name.

<!--Copy parameters to CreditCard properties-->

<c:set target= "${creditcard}" property= "name"

Value= "${param[' Cardname ']}"/>

<c:set target= "${creditcard}" property= "type"

Value= "${param[' Cardtype ']}"/>

<c:if test= "${param.cardnumber!= null and

Param.cardnumber!= '} ' >

<c:set target= "${creditcard}" property= "number"

Value= "${param.cardnumber}"/>

</c:if>

<c:set target= "${creditcard}"

Property= "Expirationdatestr"

Value= "${param[' Carddate ']}"/>


If the request parameter is not set (when the page is first displayed without setting the request parameter), the expression such as ${param[' Cardname '] has a null value, the corresponding Bean property is also set to null.

The next section of the Validatecard.jsp page collects data from the user. When the user clicks the Submit button, the data is handed back to the same page. This part of the code has some interesting features. A form always passes back to itself, so each input defined below includes a property that sets the input value to the current value of the credit card.

The first part of the form uses a table to control the layout and the local background color, and defines an INPUT element for the form property "Cardname".

<input type= "text" name= "Cardname" size= "32"

Value= "${creditcard.name}" ><br>


The Cardname value is assigned to the EL expression ${creditcard.name}, which is equivalent to the following code:

<%= ((creditcardlocal) request.getsession ().

GetAttribute ("CreditCard")). GetName ()%>


If the form has been submitted before, any names entered by the field will be displayed in the Cardname input box.

The next input is a set of radio buttons, one for a credit card type. The credit card object has an "info" attribute of type Ccinfo. The object is a java.util.HashMap that contains information about all valid credit card types. The core of the map is the symbolic name of each credit card, for example, "MC" represents MasterCard's credit card (MasterCard). The value is the Ccdesc type, which is the object used to describe the card. (For more information, see the format source code in the code example). The <c:forEach> loop loops back and forth in the received credit card type and creates a radio button for each type.

<p>

<b>type of Card:</b><br>

<c:foreach var= "Item" items= "${creditcard.info}" >

<input type= "Radio" name= "Cardtype"

Value= "${item.key}"

${(Item.key eq creditcard.type)? ' Checked ': '}>

${item.value.description}<br>

</c:forEach>


If the radio button being created in the CreditCard object is the currently selected button, then the expression ${(item.key eq creditcard.type)? ' Checked ': ' The string ' checked ' is obtained. The loop provides a hidden benefit in an extensible way. To add a new credit card type, simply add a ccdesc description of the type to the CreditCard ccinfo. The next time validatepage.jsp executes, the loop will receive the new credit card type and add it to the list.

The following two entries include credit card numbers and expiration dates:

<b>card number:</b>

<input type= "text" name= "Cardnumber" size= "24"

Value= "${creditcard.number}" ><p>

<b>expiration Date (mm/yyyy):</b>

<input type= "text" name= "Carddate" size= "10"

Value= "${creditcard.expirationdatestr}" >


Note again: This value is assigned to the corresponding Enterprise bean property value.

If appropriate, the third section of the form displays an error message, or a message stating that the card is valid. This section contains two <c:when> tags and one <c:otherwise> mark. When the credit card number is empty, the first token is used to prevent error messages from being displayed.

<c:choose>



<c:when

test=

"${creditcard.number = = NULL | | Creditcard.number = = ' '} ' >

<!--no number, so no need to complain

That is it ' s not valid-->

</c:when>


When the credit card number is valid, the second <c:when> mark displays a success message.

<c:when test= "${creditcard.valid}" >

The following card is valid:<br>

<table border= "0" >

<tr><th align= "left" >Name:</th>

<td>${creditCard.name}</td>

</tr>

<!--and so on ...-->

</c:when>


At this point, a real application might be able to transmit the user's browser to a form that collects billing address information (billing addressing infomation). Note here: The test for <c:if> is a Boolean value. So the expression ${creditcard.valid} must be Boolean. The accessor (accessor) of this property is Creditcardlocal.isvalid () because the naming convention for a get property accessor for a Boolean value is to use "is" instead of "get".

The last Mark <c:otherwise> is for cases where the credit card number is invalid.

<c:otherwise>


<font color= "Red" >this number is not valid.</font>

<br>

<i>problem</i>: ${creditcard.validitymessage}<br>

Please correct the problem and try again.

</c:otherwise>

</c:choose>


Creditcardlocal.getvaliditymessage returns a user-friendly error message explaining why the credit card is not valid.

What is interesting and useful in this example is that the enterprise bean interface can be stored in the application's session (or other) context and can be referenced through a name in the JSP EL expression. Because application logic is not implemented in scriptlet, this technique can be used to improve encapsulation. It also makes JSP pages easier to create, understand, and maintain.

Run the sample code
Download examples of these tips for archiving. The application's upper and lower root (context root) is ttfeb2004. The downloaded ear file also contains the full source code for the sample.

You can use the Deployment utility (Deploytool program) or the Administrative console (Admin console) to deploy this application archive (ttfeb2004.ear) on the Java EE 1.4 application Server. You can also deploy by running the asadmin command:

Asadmin Deploy Install_dir/ttfeb2004.ear


Replaces Install_dir with the path of the installation war file.

To access this application, please link: http://localhost:8000/ttfeb2004.

For a 1.4 compliant implementation of Java EE 1.4 application Server, you can deploy the application on your own platform using the deployment tools of your own Java EE product.

When you start the application, you will see a page (showing only part of the page) as follows:





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.