Latest translation masterpiece-advanced sitemesh

Source: Internet
Author: User
Suppose you want to build an enterprise-level web site by combining multiple technologies. For example, you are going to use J2EE technology to add new content to your web site, and other parts of this system are built using CGI or Microsoft's IIS server.

In this case, how can we make your application system look and feel consistent? One case handling method is to use J2EE technology to completely rewrite the case and then use a framework, such as Struts-tiles. However, the development cost of such case handling is too high, which is not realistic. Another option is to use the same look and feel in each part of your application system. However, this solution will make site maintenance a nightmare, because whenever the look and feel in an application system need to change, you need to keep the same changes for other Web applications in the system.

Most of the available frameworks used to address such business needs share a common drawback. They are either platform-related or framework-related. When you decide to use tiles as the struts modifier, you need to create the tiles definition file tiles-defs.xml, then declare forwards in the struts-config.xml, reference these tiles to modify the original JSP.

One of the simplest possible solutions is to generate your web application in pure HTML mode. Every HTML page does not need to know how it will be modified, instead, some external mechanism is used to select the appropriate modifier to modify them. This is the function of sitemesh.

Sitemesh is an open-source framework based on Java, J2EE, and XML. It relies on the new function-filter (filters) introduced from servlet 2.3)

Installation and setting

Based on past experience, the best way to learn any new technology or framework is to use it to create a simple application. Therefore, we will use sitemesh to create a simple struts application. Our application includes three pages:

• One logon page
• A Help page, including the page header and footer
• A home page, including the page header, footer, and page menu

The steps for creating this simple web application are as follows:

1. sitemesh is based on the filter, so we need to notify our web application of the sitemesh filter. Add the following lines to the Web. xml file:


<filter>
<filter-name>sitemesh</filter-name>
<filter-class>
com.opensymphony.module.sitemesh.filter.PageFilter
</filter-class>
<init-param>
<param-name>debug.pagewriter</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

These rows tell the Web container that all requests to web applications are filtered by pagefilter. Pagefilter is a class in the sitemesh-2.1.jar, you can download the jarpackage from http://www.opensymphony.com/sitemesh/download.html.

2. Generate a decorators. xml file under the WEB-INF directory with the following content:


<Decorators defaultdir = "/decorators">
<! -Configure the page-side menu modifier for the page that requires the page-side menu -->
<Decorator name = "sidemenu" page = "sidemenu. jsp">
<Pattern>/home. jsp </pattern>
</Decorator>
<! -Configure the page header and footer modifier for the page that requires the page header and footer -->
<Decorator name = "headerfooter" page = "headerfooter. jsp">
<Pattern>/help. jsp </pattern>
</Decorator>
</Decorators>

The decorators. xml file is used to define the decorators in your application ). In this file, each <decorator> element defines a modifier. Name specifies the modifier name and page specifies the JSP page used by the modifier. <Pattern> the child element specifies how these modifiers are applied to the actual page.

In our example web application, two modifiers are defined: headerfooter. jsp of the append header and footer, and sidemenu. jsp of the append page menu. We want to modify the Help page to append the page header and footer, so We append a child element of the/help. jsp path to the headerfooter. jsp modifier.

3. Create headerfooter. jsp in the webcontent/decorators directory:


<%@ taglib
uri="http://www.opensymphony.com/sitemesh/decorator"
prefix="decorator" %>
<title>
My Site -
<decorator:title default="Welcome!" />
</title>
<decorator:head />
<body>
<table>
<tr>
<td>
<H1>
SiteMesh Corporation
<H1>
</td>
</tr>
<tr>
<td><decorator:body /></td>
</tr>
<tr>
<td> SiteMesh copyright</td>
</tr>
</table>
</body>

A sitemesh modifier is actually a JSP page that uses the sitemesh custom tag. In our web application, when a user requests the Help Page, sitemesh intercepts the request and sends it to the Web application. When the application returns a response, sitemesh combines headerfooter. when you encounter <decorator: Head/>, insert the

4. Create help. jsp in the webcontent directory:


<HTML>
<HEAD>
<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>
<TITLE>Help Page</TITLE>
</HEAD>
<BODY>
Help Page
</BODY>
</HTML>

This is a common help page in Web applications.

5. Request the help. jsp page in the browser to test whether the sitemesh installation is normal. The browser returns a Help page containing the page header and footer.

Sitemesh Architecture

The sitemesh architecture is based on pagefilter-a servlet filter. When the container receives a page request, it will pass the request to pagefilter. pagefilter collects the Response Details of the application, generates a custom response object, and then passes it together with the request to the Web application. The Web application writes the response resource to the custom response object and then returns it to pagefilter.

1. parsing phase
When the control returns a response to pagefilter, it checks the content type of the response generated by the web application, and generates different Resolvers based on the response type to parse the response. For example, if the application returns text/HTML content, sitemesh will generate a fastpageparser instance and pass the page generated by the web application to it. Fastpageparser parses the page and extracts the header, footer, title, and other content of the page.

2. Modification phase

After the resolution, sitemesh begins to modify the page. This stage is divided into two parts:

A. decide how to modify

Sitemesh has a concept called modifier ing. The interface for implementing this concept is the decoratormapper (with Init () and getdecorator () methods ). The er is declared in sitemesh. xml. In the sitemesh. xml file, each er is the parent ing of the previous er. When sitemesh needs a modifier to modify the page. search for the er in XML, generate the instance of the first er found, and call the getdecorator () method. In this method, try to find the modifier for that page. If the modifier is found, return. Otherwise, call the getdecorator () method of the parent er to repeat the process until the correct modifier is found.

B. application modification

After the modifier is found, sitemesh will distribute the request to it. The modifier JSP page will access the page information parsed in the previous phase. Use various sitemesh custom tags to extract different parts of the page information (such as header, footer, and title) and insert them to the appropriate position of the output file.

You can customize the page parser used in the sitemesh. xml file to parse the specified content type or the modifier ing scheme, for example:


<?xml version="1.0" encoding="UTF-8"?>
<sitemesh>
<property name="decorators-file" value="/WEB-INF/decorators.xml"/>
<excludes file="${decorators-file}"/>
<page-parsers>
<parser content-type="text/html"
class="com.opensymphony.module.sitemesh.parser.FastPageParser" />
</page-parsers>
<decorator-mappers>
<mapper
class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper">
<param name="property.1" value="meta.decorator" />
<param name="property.2" value="decorator" />
</mapper>
<!-- Mapper for localization -->
<mapper
class="com.opensymphony.module.sitemesh.mapper.LanguageDecoratorMapper">
<param name="match.en" value="en" />
<param name="match.zh" value="zh" />
</mapper>
<!-- Mapper for browser compatibility -->
<mapper
class="com.opensymphony.module.sitemesh.mapper.AgentDecoratorMapper">
<param name="match.MSIE" value="ie" />
<param name="match.Mozilla/" value="ns" />
</mapper>
<mapper
class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">
<param name="decorator" value="printable" />
<param name="parameter.name" value="printable" />
<param name="parameter.value" value="true" />
</mapper>
<mapper
class="com.opensymphony.module.sitemesh.mapper.ParameterDecoratorMapper">
<param name="decorator.parameter" value="decorator" />
<param name="parameter.name" value="confirm" />
<param name="parameter.value" value="true" />
</mapper>
<mapper
class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
<param name="config" value="${decorators-file}" />
</mapper>
</decorator-mappers>
</sitemesh>

In this list, <property name = "decorators-file"> specifies the file used to define the modifier. <Page-parsers> defines the content types that sitemesh can process. Each <parser> sub-element specifies which parser parses which specific content type. In our example sitemesh. xml file, we tell sitemesh to use fastpageparser to parse text/HTML content. By default, sitemesh can only process HTML, but we can create our own parser to process other content types.

<Decorator-mappers> the child element defines the ing scheme. sitemesh uses this ing scheme to find the modifier that modifies the specified page. You can use the <param> sub-element to configure each mapper. Sitemesh will wrap the configuration information into a java. util. properties object and pass it to the init () method of the er.

Region Modifier

In our example sitemesh. xml file, there are the following lines of labels:


<mapper class="com.opensymphony.module.sitemesh.mapper.LanguageDecoratorMapper">
<param name="match.en" value="en" />
<param name="match.zh" value="zh" />
</mapper>

When you look for a modifier applied to a page, sitemesh first reads the accept-language information in the request header. If the en region is matched, sitemesh appends-en to the end of the modifier's JSP file name. In our example, if the request defines the modifier headerfooter. JSP help. JSP page, and the use of the region is the UK, sitemesh will first find and apply the headerfooter-en.jsp modifier, if not found then apply headerfooter. JSP.

Browser Modifier

You can use agentdecoratormapper to ensure browser compatibility:


<mapper
class="com.opensymphony.module.sitemesh.mapper.AgentDecoratorMapper">
<param name="match.MSIE" value="ie" />
<param name="match.Mozilla/" value="ns" />
</mapper>

This means that when sitemesh finds a modifier to modify the page, it first extracts the User-Agent information in the request header. If it is IE, add-ie to the end of the modifier's file name, and search for and apply this modifier. If the modifier cannot be found, apply headerfooter. jsp.

Advanced sitemesh

Sitemesh provides a er that allows every page to participate in the process of finding its own modifier.

Printabledecoratormapper

Most Web sites provide a function to obtain printable pages. The so-called printable version generally refers to a page with a set of style sheets except the page header, footer, and page menu. In sitemesh, we can use printabledecoratormapper to provide this function. To use this er, you need to append the following lines in sitemesh. xml:


<mapper
class= "com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">
<param name="decorator" value="printable" />
<param name="parameter.name" value="printable" />
<param name="parameter.value" value="true" />
</mapper>

The three configuration parameters passed to printabledecoratormapper will be packaged into a java. util. properties object and passed to the init () method.

• Decorator
The modifier name used to generate the printable version page.

• Parameter. Name
To notify sitemesh, we need a printable version of the request parameter name. For example, in our example, you can append the printable = true parameter to the query string to pass

• Parameter. Value
When setting the value of the printable parameter, sitemesh provides a printable page.

Pagedecoratormapper

You can reload the meta attribute to specify the modifier name.

To use this er, add the following lines to the sitemesh. xml file:


<mapper
class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper">
<param name="property.1" value="meta.decorator" />
</mapper>

Pagedecoratormapper can obtain a list of parameters. In our example, a parameter name is provided, specifying that the modifier name is obtained through the meta attribute. Therefore, if we want to use the test modifier to modify the page, add the following content to the header of the page:

<Meta name = "decorator" content = "test">

Pagedecoratormapper provides a static method for the page to select the modifier you want to use. In addition, you can use parameterdecoratormapper to specify the modifier to be used during running.

Parameterdecoratormapper

To use parameterdecoratormapper, add the following lines to sitemesh. xml:


<mapper
class= "com.opensymphony.module.sitemesh.mapper.ParameterDecoratorMapper">
<param name="decorator.parameter" value="decorator" />
<param name="parameter.name" value="confirm" />
<param name="parameter.value" value="true" />
</mapper>

The meanings of the three parameters are as follows:

• Decorator. Parameter
Specifies the request parameter name used by the modifier.

• Parameter. Name
Confirm the validation parameter name using the request modifier.

• Parameter. Value
Confirm the validation parameter value using the request modifier.

For example, if you want to use the test modifier to modify help. jsp, you can access help. jsp as follows:

Help. jsp? Decorator = Test & confirm = true

In addition to the above mappers, sitemesh also provides more useful mappers, such:

• Framesetdecoratormapper
It is used when the page is frame.

• Cookiedecoratormapper
You can use cookies to specify the modifier you want to use.

• Robotdecoratormapper
Use the specified modifier when the requester is indeed a robot. You can manually append the robot keyword to the Request Header, or use the modifier.

Velocity and freemarker Modifier

Sitemesh does not limit that you can only modify JSP pages. You can freely select the object you want to modify, such as velocity or freemarker. Velocity and freemarker Are Template languages that can be used to generate Web pages. These languages are easier to use than JSP, but less flexible in terms of programming.

Sitemesh supports these two template languages through two Servlets, which are also defined in the sitemesh. jar file. We can declare these two servlets in Web. XML as follows:


<servlet>
<servlet-name>sitemesh-velocity</servlet-name>
<servlet-class>
com.opensymphony.module.sitemesh.velocity.VelocityDecoratorServlet
</servlet-class>
</servlet>
<!--Declare servlet for handling freemarker requests -->
<servlet>
<servlet-name>sitemesh-freemarker</servlet-name>
<servlet-class>
com.opensymphony.module.sitemesh.freemarker.FreemarkerDecoratorServlet
</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>ISO-8859-1</param-value>
</init-param>
</servlet>
<!-- Velocity servlet should serve all requests with .vm extension-->
<servlet-mapping>
<servlet-name>sitemesh-velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
<!-- FreeMarker servlet should serve all requests with .dec extension-->
<servlet-mapping>
<servlet-name>sitemesh-freemarker</servlet-name>
<url-pattern>*.dec</url-pattern>
</servlet-mapping>

Of course, we also need to introduce freemarker. jar, velocity-dep.jar and velocity-tools-view.jar In the Lib folder. These jar files are included in the release package of sitemesh. Next, let's modify the first example application and use the velocity and freemarker modifier to replace JSP. In our first example, two modifiers are defined: headerfooter and sidemenu. Next we will create a headerfooter. DEC:


<title>My Site - $Advanced SiteMesh</title>
${head}
<body>
<table border="1">
<tr>
<td>SiteMesh Corporation</td>
</tr>
<tr>
<td>${body}</td>
</tr>
<tr>
<td>SiteMesh copyright</td>
</tr>
</table>
</body>

On this page, we use the freemarker template to request header, footer, and title, instead of using JSP custom tags, but the page layout is the same. When the container receives a page request with the. Dec extension, it will pass the request to freemarkerdecoratorservlet, which will call freemarkerdecorator to modify the generated HTML page. We use the $ advanced sitemesh template to access the title of the web page generated by the application, $ {head} to access head, $ {body} to access body. Freemarker provides a wide range of templates. For more information, see http://www.javaworld.com/~-01-2001/109-0119-freemarker.html.

Similarly, create the sidemenu. VM file under the decorators Directory, which is the velocity modifier file:


<title>My Site - $title</title>
$head
<body>
<table border="1">
<tr>
<td> SiteMesh Header </td>
</tr>
<tr>
<td> Sidemenu </td>
<td> $body </td>
</tr>
<tr>
<td> SiteMesh Footer </td>
</tr>
</table>
</body>

Replace <decorator: Title/> with the $ title template, and replace the corresponding JSP custom tag with the $ head and $ body velocity templates.

Conclusion

Filter-based sitemesh is a flexible and easy-to-use modifier framework. But it still has some problems. First, Servlet 2.3 supports filters. Therefore, some application servers in earlier versions cannot support sitemesh. Before using sitemesh, check whether the app server you want to use supports filters.

In addition, the filter takes effect only when a browser is used to request a page. Therefore, if you access home in a browser. JSP, it will be modified, but if you use the Servlet's requestdispatcher. include () or forward () to control home. JSP, modifier does not work. But don't worry. Starting from servlet 2.4, you can configure the applicable environment of the filter, including forward and include.

 

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.