Include mechanism in JSP

Source: Internet
Author: User
Tags image hosting apache tomcat
This article is the first part of a new series of articles on JSP best practices. It introduces the assumerver pages include mechanism. Follow Java programming expert Brett McLaughlin to learn how to use include to add static header files and footer files to your website or web application pages.
Read the latest Best Practices series in the Java area. If you have read the previous series of articles, you will know that the best practices are designed to help you quickly understand the useful aspects of various Java technologies. This series of best practices specifically discusses the assumerver pages (JSP) technology, which is one of the core J2EE technologies.

In short, JSP technology is a tool for building web pages or web application interfaces on the Java platform. JSP technology allows us to do the following: dynamically respond to request data, display complex XML and HTML, and create interesting, dynamic-driven websites. In this series, you will learn some basic knowledge about Using JSP technology to build websites. I will introduce you to the most common JSP mechanisms, through which you will understand basic web development technologies, such as creating templates, operating dynamic content, image hosting, and creating a utility code library.

This is the first article in this series. In this article, we will focus on the JSP include mechanism, which allows us to "pull" the content of the local HTML page. We will first introduce some background knowledge about the development of Web Page include, especially the use of the framework and server-side include. Then, I will show you how to use the JSP include mechanism to add uniform header files and footer files to web pages or web application screens.

· JSP Best Practices Series

This series of articles does not intend to fully introduce JSP technology, nor are they intended to serve as a guide to how to build special types of applications. On the contrary, each part of the series focuses on one aspect of JSP-based programming and divides it into small fragments. For more information about JSP technology or more in-depth research on how to use it for special results, see references.
What do you need
All the best practices in this series are based on the assumerver Pages technology. To run any practice, you need to set JSP-compliant Web containers on the local machine or test server, such as Apache Tomcat. You also need to use a text editor or ide To write JSP page code. See references to obtain links to the list of Tomcat and JSP-compatible web containers and ides.

· Better appearance

Creating consistent design and layout for Web pages is one of the easiest ways to ensure a professional look. You may have seen enough websites to know that most of the pages in a single site share a uniform page header, end of the page, and a certain type of navigation bar. On well-designed sites, these elements present the same layout, content, and functionality on each page, while the main panel (usually called the content pane) changes with each view.

Previously, this layout was almost entirely implemented by the framework and framework set. Each segment of static content is placed in a frame, and the main content of the page is placed in the intermediate frame. The trouble with frameworks is that different browsers often display them in different ways to make them look different. Using a framework to link external sites from an internal page is more difficult than you think. Originally, users were allowed to view external content without leaving the site, but the results were often inconsistent. What the user sees is that the entire site is congested into a much smaller frame. Worse, your site will eventually be nested in another site frame. This chaos drives web designers to find a better solution. Server-side include (SSI) is one type.

· Server include

Not long ago, SSI was one of the most popular options for creating shared content. The simple SSI directive allows you to create a page that contains the content of another page (such as the header and footer file), as shown in Listing 1.

· List 1. ssi being used

<! [CDATA [
<HTML>
<Head>
<Title> simple SSI test </title>
</Head>
<Body>
This content is statically in the main HTML file. <br/>
<! -- # Include virtual = "included.html" -->
</Body>
</Html>
]>

We will soon use this file for an exercise. Currently, you should save it as a test-ssi.shtml. In most settings, the SSI File must.

The end of shtml, which allows the Web server to parse them into SSI pseudo commands. Listing 2 shows the contents of a file named included.html.

· List 2. Contents

<! [CDATA [
This content is in another file, included.html
]>

When you request a test-ssi.shtml, you will see the contents of this file and the contents of included.html. You can view these files on any Web container that supports SSI (for example, Apache Tomcat, see references.

From the user's perspective, SSI has a major improvement over the framework, because there is no obvious difference between a single file and the files imported from other included files. The disadvantage is that SSI requires a specific server setting, which Java developers often cannot use. In addition, SSI usually requires static content to be included, although dynamic content inclusion is added to later versions.

SSI is a viable solution for websites or Web applications that contain different types of content, but they are not the best choice for Java developers. This is not only because the assumerver Pages technology replaces the full Java Technology of SSI, but also because these two technologies are not easily combined. JSP page with extension. JSP end. This indicates that to enable the SSI pseudo command to take effect, you must change the SSI configuration to parse the JSP file (add overhead for parsing each JSP page), or change the JSP configuration. the shtml extension is used as JSP page processing (this is a bad idea ). For Java developers, JSP technology is the best content management solution. Fortunately, its include mechanism is easy to master.

· JSP include

JSP include pseudo commands are extremely similar to SSI-like pseudo commands. Listing 3 shows the JSP peer-to-peer pseudo commands of SSI pseudo commands shown in Listing 1. Any Web container that supports JSP will process the display of this JSP page (likewise, refer to the references section for links ). You should save the file as a test-include.jsp.

· Listing 3. jsp include pseudoinstructions

<! [CDATA [
<% @ Page Language = "Java" contenttype = "text/html" %>
<HTML>
<Head>
<Title> JSP include element test </title>
</Head>
<Body>
This content is statically in the main JSP file. <br/>
<% @ Include file = "included.html" %>
</Body>
</Html>
]>

The include directive makes it easy to merge the unified header file and footer file into your site. Listing 4 shows the primary index pages with several contained files.

· List 4. jsp include Directive on the primary index page

<! [CDATA [
<% @ Page Language = "Java" contenttype = "text/html" %>
<HTML>
<Head>
<Title> newinstance.com </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1"/>
<Link href = "/styles/default.css" rel = "stylesheet" type = "text/CSS"/>
</Head>

<Body>
<% @ Include file = "header. jsp" %>
<% @ Include file = "navigation. jsp" %>
<% @ Include file = "bookshelf. jsp" %>
<% @ Include file = "/MT-blogs/index. jsp" %>
<% @ Include file = "footer. jsp" %>

</Body>
</Html>
]>

By viewing the code, you will learn how to use JSP include. You should also test the code to learn how it works.

· Add dynamic content

In addition to static content such as header, footer, and navigation file, listing 4 also includes calling weblog (/MT-blogs/index. jsp), which involves the topic of dynamic content. As with the SSI include Directive, JSP include mechanism may cause problems when applied to dynamic content. You can use the JSP include directive to introduce dynamic content, but you cannot obtain changes to the content. This is because the Web container will be read as part of the original (contained) page. The container caches the results as a single file, instead of multiple JSP components. Because the Web container does not poll the contained files for changes, it does not know that any changes have occurred. It automatically displays the cached pages instead of the refreshed pages. To understand how it works, we will do a simple exercise. First, update the saved included.html page as shown in listing 5.

· List 5. Modify included content

<! [CDATA [
This content is in another file, included.html.
<Br/>
Some new content...
]>

Next, save the changes, navigate to the test-include.jsp file, and refresh the browser. You will notice that no new content in included.html is displayed in the browser. The content of the contained file is cached before the change occurs, so it is not displayed. If your site contains dynamic content or content that may be frequently modified, this is a problem. Fortunately, there is a work und. In the next section, I will show you how to add dynamic content to the web page using the <JSP: Include> tag. Before that, please refer to the references section and test the Code provided here. I will meet you online.

Automatically jump to the servlet/jsp framework of the error page

JSP has a directive that defines the error page of JSP and jumps to this page to output error logs when an error occurs on this JSP page. Example:

<% @ Page errorpage = "errorpage. JSP "%> errorpage. the JSP code is as follows :..... <% @ page iserrorpage = "ue" %> .... // Output Error Log <% = Exception. getmessage () %>

However, this can only be controlled at the JSP page layer. In the implementation of J2EE, JSP is often displayed only as a page, and the database operations related to the business are performed in the backend servlet. After the processing is completed, the JSP display page is redirected. This setting framework implements the MVC structure, greatly reducing the maintenance difficulty of the entire system.

In actual work, although the system uses the above setup framework, the level of J2EE developers and programming habits may not work, developers often encounter improper handling of possible errors in servlet. One of the most common cases is to catch an exception E and then only call E. printstacktrace (). The consequences are very serious. Once an exception occurs, a white screen will appear on the web page. We can look at the following two aspects:

(1) if it is a user. He is often at a loss, and may not know that there are errors, continue to use the system, but at this time the system has gone wrong, on the basis of the error to continue the business process, more system-level errors are often caused.

(2) developers. The user reflects the error, but does not know the cause of the error. Only white screen is required. If a developer needs to debug and catch an error, check the error log at the input end of the application server, locate the cause of the error, and then troubleshoot the error.

Here, I will introduce an effective servlet error handling mechanism, which throws all the error content of the exception to the web page so that the user can have an error immediately, you can also promptly submit the error content to the developer to locate the cause of the error.

In fact, this mechanism is very simple. The idea is to define an abstract baseservlet base class that inherits httpservlet.

And add an abstract
Absact public void doworkflow (httpservletrequest request, httpservletresponse response) method. This method is a required and only required method for all baseservlet subclasses. Of course, the baseservlet base class must implement the service method --

Public final void Service (httpservletrequest request, httpservletresponse response ). Its code snippets are as follows:

Public final void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {y {// before executing doworkflow, you can handle issues such as whether you have the permission to handle them ....... doworkflow ();} catch (exception e) {singwriter out = new singwriter (); E. printstacktrace (New printwriter (out); Request. setatibute ("err_msg", out. tosing (); requestdispatcher RD = This. getservletcontext (). getrequestdispatcher ("errorservlet. JSP "); Rd. forward (request, response );}}
Errorservlet. jsp is very simple. The code snippet is as follows:

... // Output Error Log <% = request. getatibute ("err_msg") %>

Related Article

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.