Java EE application User interface Development (ii)
Author KURT A. Gabrick
DAVID B. WEISS.
SOURCE EE and XML Development Fifth chapter
Address <Http://www.manning.com/gabrick>
This article is the second part of Java EE and XML Development user interface, if you are unfamiliar with the examples in this article, see the first part of the--J2EE and XML Development user interface (i)
Four Java-EE Federated XML Solution
The first thing we want to contact with XML Schemas is the federated use of XSLT and the Java EE Presentation layer component. XSLT provides a common way to convert XML documents into various output formats. This makes thin-client user interface development easy. The output format of the XSLT processor is determined by the transformation rules defined by the XSL style. Our example requires output in HTML and WML format. If your team XSLT use is not very clear, you can refer to the XSLT online tutorials provided by the
4. 1 adding XSLT to the Web development process
In the first section, we created a servlet controller, a custom tag (also a javabean) and four JSP pages. Adding XSLT processing can have the following four effects on our design:
• No longer need to use the JSP we designed
• No longer need to use the custom tags we designed (also JavaBean)
• We need a new out filter component to process the XSLT
• We need to modify our Watchlistjspservlet to remove the forwarding statements from the JSP
The filter filter is a new member of the Java EE Presentation Layer framework. They are useful for connecting web workflows. A filter can be applied to a specific request or to your entire application. The filter can preprocess the request (before the request reaches the servlet) or after processing. In the example of this article, we are only interested in any post processing of requests processed by our servlet controller.
The XSLT request processing process begins with our servlet controller accepting a request for a stock price. The servlet exchanges information through the Listbuilder class with the application logic layer, while the Listbuilder class returns a Jdom document. The selection logic for the view will now be processed by our new filter component, which will select one from the XSL stylesheet instead of the original JSP.
The example applies the new architecture as described in the following figure.
4. 1. 1 XSLT Filter process
We have developed a filter to start our XSLT example, which will manage the selection of stylesheets and the process of XSLT conversion. Here's a summary of how this filter works:
• Each Web request from the Watch list page is intercepted by the filter and handed over to the controller after processing is complete.
· The Jdom document is returned to the filter via the HttpRequest object.
• Filters determine the type of device and the area in which the user is located.
• The filter selects the most appropriate XSL style and invokes the XSLT processor to convert the Jdom result to the destination format.
• Filters send the results of XSLT transformations to the customer's device. To submit and display there.
4. 1. 2 Modifying the servlet
Because our filters will choose the right style and do not use JSP, we modify the watchlistservlet to make it quite simple. Its source code is shown in Listing 8. The servlet is now connected to Listbuilder and stores the Jdom document in the HttpRequest object.
List 8
Import org.jdom.*;
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
/**
* The stock watchlist servlet with XSLT
*/
public class Watchlistservlet extends HttpServlet {
Private Listbuilder builderinterface = new Listbuilder ();
Private ServletConfig config;
Private ServletContext context;
Public Watchlistservlet () {super ();}
public void init (servletconfig config)
Throws Servletexception {
this.config = config;
This.context = Config.getservletcontext ();
}
public void doget (httpservletrequest request,httpservletresponse response)
Throws Servletexception, IOException {
HttpSession session = Request.getsession (false);
if (session = null) {
Context.getrequestdispatcher ("/login.jsp"). Forward (request, response);
Return
}
String userId = (string) session.getattribute ("UserId");
Document quotelist = builderinterface.getwatchlist (userId);
Request.setattribute ("Quotelist", quotelist);/no need to use JavaBean wrapper document
}
public void DoPost (httpservletrequest request,httpservletresponse response)
Throws Servletexception, IOException {
Doget (request, response);
}
}
4. 1. 2 Build Filters
Our filter is a class that implements the Javax.servlet.Filter interface. The Java EE Web container invokes filters and servlet using pattern matching based on URLs. When a filter matches a specific URL pattern, the container invokes the Dofilter method, which is signed as follows:
public void Dofilter (ServletRequest request,
Servletresponse Response,filterchain chain)
throws IOException, servletexception;
The Filterchain parameter is a collection of all the processes that need to be processed at the time of the request, including the servlet, JSP, and other filters that may be invoked. Since our filter does the post processing, all operations of the method Dofilter must be performed before Filterchian: chain.dofilter (Request,response);
This actually invokes watchlistservlet through the Web container, which stores the Jdom document we need in the request object. Then, we get this document in the Dofilter method.
HttpServletRequest HttpRequest = (httpservletrequest) request;
Document Outputdoc = (document) Httprequest.getattribute ("Quotelist");
Next, we call some helper methods to decide which style to choose for conversion
String OutputFormat = GetOutputFormat (HttpRequest);
String locale = getlocalestring (HttpRequest);
String Stylesheetpath = Getstylesheet (OutputFormat, locale);
The body of these methods is in Listing 9. They are very similar to those of the first part of the method. Now that we have the XML document and which style to use, we can use the JAXP API for conversion.
Transformerfactory myfactory = Transformerfactory.newinstance ();
Transformer Mytransformer =
Myfactory.newtransformer (New Streamsource (Stylesheetpath));
Jdomresult result = new Jdomresult ();
Mytransformer.transform (New Jdomsource (outputdoc), result);
Now it is only the logic of using the HttpResponse object to write the output of the XSLT to the client.
Document Resultdoc = Result.getdocument ();
Xmloutputter xout = new Xmloutputter ();
if (Outputformat.equals ("WML"))
Response.setcontenttype ("TEXT/VND.WAP.WML");
PrintWriter out = Response.getwriter ();
Xout.output (Resultdoc, out);
Listing 9 provides an implementation code for the complete Xsltfilter class
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
Import org.jdom.*;
Import org.jdom.output.*;
Import org.jdom.transform.*;
Import javax. xml.transform.*;
Import javax. xml.transform.stream.*;
public class Xsltfilter implements Filter {
Private Filterconfig Filterconfig;
public void init (Filterconfig filterconfig) throws Servletexception {
This.filterconfig = Filterconfig;
}
Public Filterconfig Getfilterconfig () {
return this.filterconfig;
}
public void Setfilterconfig (Filterconfig filterconfig) {
This.filterconfig = Filterconfig;
}
public void Dofilter (ServletRequest request,servletresponse response,
Filterchain chain) throws Ioexception,servletexception {
try {
Chain.dofilter (Request,response);
HttpServletRequest httprequest= (httpservletrequest) request;
Document Outputdoc= (document) Httprequest.getattribute ("Quotelist");
if (Outputdoc = null) return;
String OutputFormat = GetOutputFormat (HttpRequest);
String locale = getlocalestring (HttpRequest);
String Stylesheetpath=getstylesheet (OutputFormat, locale);
Transformerfactory myfactory=transformerfactory.newinstance ();
Transformer mytransformer=
Myfactory.newtransformer (New Streamsource (Stylesheetpath));
Jdomresult result = new Jdomresult ();
Mytransformer.transform (New Jdomsource (outputdoc), result);
Document Resultdoc = Result.getdocument ();
Xmloutputter xout = new Xmloutputter ();
if (Outputformat.equals ("WML"))
Response.setcontenttype ("TEXT/VND.WAP.WML");
PrintWriter out = Response.getwriter ();
Xout.output (Resultdoc, out);
catch (Exception e) {
System.out.println ("Error was:" + e.getmessage ());
}
}
Private String GetOutputFormat (HttpServletRequest request) {
String useragent = Request.getheader ("user-agent");
This is where your robust user-agent lookup should happen
if (Useragent.indexof ("Up"). Browser ") >= 0)
return "WML";
return "HTML";
}
Private String getlocalestring (HttpServletRequest request) {
Enumeration locales = Request.getheaders ("Accept-language");
while (Locales.hasmoreelements ()) {
String locale = (string) locales.nextelement ();
if (Locale.equalsignorecase ("EN_GB"))
return "EN_GB";
}
return "en_US";
}
private string Getstylesheet (string OutputFormat, string locale) {
if (Locale.equals ("en_US")) {
if (outputformat.equals ("html"))
return "watchlist.html.en_US.xsl";
Else
return "watchlist.wml.en_US.xsl";
} else {
if (outputformat.equals ("html"))
return "watchlist.html.en_GB.xsl";
Else
return "watchlist.wml.en_GB.xsl";
}
}
public void Destroy () {}
}
4. 1. 3 Development Styles
Finally, we need four new XSL styles to use for XSLT, which provides the conversion functionality of XML to output. We need to convert the JSP, JavaBean, and custom tags developed in the previous section to four XSLT transformation rules. Although there are many different ways to develop XSL styles, the most straightforward way is to base the template approach. This way of XSL style is very similar to the way our JSP templates are.
Listing 10 contains the XSL style, which converts the stock reference list XML document into HTML format, which is the United States. Notice the difference between this file and the HTML file, and most of all, it wraps the entire document with <xsl:sytleshEEt> elements and global <xsl:template> elements. The <xsl:styleshEEt> element indicates that the file is a set of conversion rules, while the <xsl:template> element is the global conversion rule that applies to the root node of the XML document. The analysis of XSLT development is beyond the scope of this article, but it is a powerful tool for transforming XML in different ways.
List 10 styles of HTML generated in the U.S. region
? XML version= "1.0" encoding= "UTF-8"?>
<xsl:stylesheet xmlns:xsl=<xsl:output method= "html" doctype-public= "-//W3C//DTD XHTML 1.0 strict//en"/>
<xsl:template match= "/" > <!-the start of global conversion rules à
<body>
<xsl:value-of select= "/customer[@first-name]"/>! <!-use XPath to select a user name à
Here are the "latest price quotes" for
Your watch list stocks.
<p><i>
Price quotes were obtained at
<xsl:value-of select= "/quote-list[@time]"/> <!-get time to generate from quote-list documents à
On
<xsl:value-of select= "/quote-list[@date]"/> <!-get the date of production from the quote-list document à
</i></p>
<table cellpadding= "5" cellspacing= "0" border= "1" >
<tr>
<th>stock symbol</th>
<th>company name</th>
<th>last price</th>
<th>easy actions</th>
</tr>
<xsl:for-each select= All quote elements in the "//quote" > <!-Iteration document à
<tr>
<td><xsl:value-of select= "@symbol"/></td>
<td><xsl:value-of select= "@name"/></td>
<td>$$
<xsl:value-of select= "./price[@currency =USD]"/>
</td>
<td>
<a href= "http://www.exampleco.com/buyStock?symbol=
<xsl:value-of select= "@symbol"/> ">
Buy
</a>
<a href= "http://www.exampleco.com/sellStock?symbol=
<xsl:value-of select= "@symbol"/> ">
Sell
</a>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</xsl:template>
</xsl:styleshEEt>
4. 2 Analysis Results
The XSLT architecture makes our example better modular and scalable. It allows us to create a single, holistic presentation layer that provides the right services for a variety of customer types and regions. When it comes to adding new customer types and regions, we just need to add additional styles to the framework and select them appropriately. By making the selection of styles configurable, we can reduce the extension process that is added to create a single document and update our Web application profile so that filters can be used.
Another major advantage of this architecture is that it can divide development roles more effectively. The Display page author can implement XSL and the developer can focus on the process of generating XML. These tasks can be accomplished independently of each other.
However, the advantages of role separation are faced with their own challenges. For example, using XSL to develop user interfaces is much more difficult than using standard HTML and requires more programming skills that web designers are unfamiliar with. It is expected that graphics tools will be able to deal with this problem in the near future. Another challenge in actually using this architecture is that there is still a lack of sufficient XSLT support in the IT industry. While this will change over time, it has become an obstacle to consolidating XML into the presentation layer.
Guide
The third part of this article describes how to use XSLT to generate PDF documents for XML and Web publishing framework cocoon.
More information
1. 2.
This article is reserved by starchu1981, if necessary, please specify the author and source.
-->
-->