Freemark page Static

Source: Internet
Author: User

1. What is the page static?
Page static has a lot of meaning, in web development, static Web pages generally understand that most of the hyperlinks in the site refer to the page is a separate HTML static page file (such as . htm,. html and other paging files, the HTML language itself is static, does not support data transfer, can prevent SQL injection
)。

2. Why do you have to make the page static?
For today's Internet applications (WEB application), dynamic pages occupy an absolute high position, because of the dynamic, it is now the rich and colorful Internet, but like all other facts, the benefits are often a price. To produce dynamic results, each request to a page requires the server to compile or execute the page, which consumes system resources. If there is a communication with the database during this period, the cost will be greater.

   如果一个页面在一定的时间内,其内容没有发生改变,那么就不必为每一次对它的访问进行一次“新”的编译或执行。我们可以把它在这段没有发生改变的时间内的 结果保存到一个静态的页面里面,然后每次访问这个页面时,就用刚才保存的静态页面进行回复。这样便能大大地减少系统资源的消耗,并且提高对客户的响应速度。而这个过程就称之为页面静态化。

3. Page static scheme?
At present, there are two main types of static: one is through the program to crawl the dynamic page and save as a static page, so that the actual existence of the page in the server's hard disk, and the other is through the Web server URL rewrite way, His principle is through the Web server internal module according to certain rules to the external URL request into the internal file address, in a word, the static address of the external request to the actual dynamic page address, and static page actually does not exist. Both of these methods achieve the effect of static URL, but also each has its own characteristics (also called pseudo-static).
3.1. What is the difference between them?
Convert dynamic pages to actual static pages this method, due to the existence of static pages, less dynamic parsing process, so improve the page access speed and stability, making the optimization effect is very obvious. So this method is widely used. But its limitations are also there. For large Web sites, this approach will bring an issue that cannot be overlooked.

First, due to the number of files generated, storage needs to take into account the number of files, folders and disk space capacity issues;
Second, the page maintenance of the complexity and large workload, and the resulting page maintenance issues, the need for a complete set of site update system.
and the URL rewrite way characteristic is also distinct, because is the server inside resolves the address, therefore the content is real-time updates, also does not have the file management and the hardware question, the maintenance is more convenient. The rewrite rewrite technique at the server-level URL does not affect the speed of the page execution. But the threshold of the URL Rewrite is relatively high, most of the domestic virtual host is not supported, and the virtual host is a directory-level URL Rewrite, by traversing the directory reader URL forwarding rules will greatly reduce the speed of the page execution.

4. How do I make the page static?
First described above the first page of static, this static implementation of the real static, to do this static can be used Freemarker and httpclient.
Freemarker is a template-based generic tool for generating output text, so we have to customize the template that fits our business and generate the HTML page
Freemarker is loading the template by freemarker.template.Configuration this object (it also handles the work of creating and caching pre-resolved templates), and then we get the template you want through the GetTemplate method, one thing to remember Freemarke R.template.configuration must guarantee a unique instance throughout your entire application.

Freemarker main steps to implement page static:

1. Import the relevant jar package, I do with the servlet, only need to import a Freemarker.jar

2. Import 2 tool classes Directoryfilter and Freemarkertutil, Directoryfilter (It implements the file filter that interface FilenameFilter) This tool class is mainly to determine whether a particular HTML file has been generated Java class (not very useful), The Freemarkertutil package Freemarker is used to create templates and load templates. It also contains a method for initializing the template.

Directoryfilter.java

 PackageCom.lyl.util;ImportJava.io.File;ImportJava.io.FilenameFilter;/** * Determine if a specific HTML file has been generated for the Java class * @author Administrator * */ Public  class directoryfilter implements filenamefilter {String myString; Public Directoryfilter(String myString) { This. myString = myString; } Public Boolean Accept(File dir,string name) {//filenamefilter.accept (File dir, String name)           //test whether the specified file should be included in a list of files. String f=NewFile (name). GetName ();if(F.contains (myString) | | f.equals (myString)) {return true; }return false; }      }

Freemarkertutil.java

 PackageCom.lyl.util;ImportJava.io.IOException;ImportJava.io.Writer;ImportJava.util.Locale;ImportJava.util.Map;ImportJavax.servlet.ServletContext;ImportFreemarker.template.Configuration;ImportFreemarker.template.DefaultObjectWrapper;ImportFreemarker.template.Template;ImportFreemarker.template.TemplateException;/** * Encapsulates freemarker for creating templates and loading templates. It also contains a way to initialize the template * @author Administrator * */ Public  class freemarkertutil {    Private StaticConfiguration config =NewConfiguration ();/** * @param templatename * Template name * @param root * template root used to output a knot within a template Fruit set * @param out * Where the output object is output to */     Public Static void ProcessTemplate(String templatename, map<?,? > root, Writer out) {Try{//Get TemplatesTemplate template = Config.gettemplate (templatename,"Utf-8");//Generate files (here we are generating HTML)Template.process (root, out);        Out.flush (); }Catch(IOException e)        {E.printstacktrace (); }Catch(Templateexception e)        {E.printstacktrace (); }finally{Try{Out.close (); out =NULL; }Catch(IOException e)            {E.printstacktrace (); }        }    }/** * Initialize Template configuration * * @param servletcontext * javax.servlet.ServletContext *  @param Templatedir * Template location * *     Public Static void initconfig(ServletContext ServletContext, String templatedir)        {Config.setlocale (Locale.china); Config.setdefaultencoding ("Utf-8"); Config.setencoding (Locale.china,"Utf-8");        Config.setservletcontextfortemplateloading (ServletContext, Templatedir); Config.setobjectwrapper (NewDefaultobjectwrapper ()); }}

3. Configure Web. xml

<?xml version= "1.0" encoding= "UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation="Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_ 5.xsd "id=" webapp_id " version=" 2.5 ">                <display-name>Freemarker_stat</display-name>    <welcome-file-list>        <welcome-file>Index.html</welcome-file>        <welcome-file>Index.htm</welcome-file>        <welcome-file>index.jsp</welcome-file>        <welcome-file>Default.html</welcome-file>        <welcome-file>Default.htm</welcome-file>        <welcome-file>default.jsp</welcome-file>    </welcome-file-list><servlet>     <servlet-name>Index</servlet-name>     <servlet-class>Com.lyl.servlet.Index</servlet-class>     <init-param>      <param-name>Templatedir</param-name><!--template storage location, is based on the app's root directory- -    <param-value>/templates</param-value>     </init-param>     <load-on-startup>3</load-on-startup><!--Initialize the template configuration to start </servlet>  <servlet-mapping>     <servlet-name>Index</servlet-name>     <url-pattern>/index.do</url-pattern>   </servlet-mapping> </Web-app>

4. New JSP page

<%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html><head><title>My JSP ' index.jsp ' starting page</title><meta http-equiv="Pragma" content="No-cache"><meta http-equiv="Cache-control" content="No-cache"> <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 " />  <meta http-equiv="Expires" content="0"></head><body>    <form Action="Index.do" method="POST">        <input type="Submit" value="Login">    </form></body></html>

5. Create a new servlet note the same as the jump name configured in Web. xml

 PackageCom.lyl.servlet;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.Writer;ImportJavax.servlet.ServletConfig;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportCom.lyl.client.ProcessClient;ImportCom.lyl.util.DirectoryFilter;ImportCom.lyl.util.FreeMarkertUtil; Public  class Index extends httpservlet {          Private Static Final LongSerialversionuid =7474850489594438527L Public Index() {Super(); } Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException { This. DoPost (Request, response); } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {//html The path that is stored after the buildString Dirpath = Request.getsession (). Getservletcontext (). Getrealpath ("/templates/html"); File Path =NewFile (Dirpath); SYSTEM.OUT.PRINTLN (path);//The name of the generated fileString Indexfilename ="Index.html";/** * Determine if the HTML file already exists, there is a direct access to HTML, there is no HTML file generated * /string[] Indexfilelist = Path.list (NewDirectoryfilter (Indexfilename));if(indexfilelist==NULL|| indexfilelist.length<=0) {Writer out =NULL; System.out.println ("HTML file does not exist, create an HTML");//byte stream into a character stream to generate an HTML fileout =NewOutputStreamWriter (NewFileOutputStream (dirpath+"/"+indexfilename),"UTF-8");//Go in here and write the dynamic JSP to this HTMLProcessclient.processbody (out); Request.getrequestdispatcher ("/templates/html/index.html"). Forward (request, response); }Else{System.out.println ("HTML already exists, direct access"); Request.getrequestdispatcher ("/templates/html/"+indexfilelist[0]). Forward (request, response); }          }/** * Initialize the template configuration for later access to the template, in the init add is also mainly to ensure that the configuration instance unique * /           Public void Init(ServletConfig config)throwsservletexception {String Templatedir = Config.getinitparameter ("Templatedir");          Freemarkertutil.initconfig (Config.getservletcontext (), templatedir); }      }

Here Freemark Static has been implemented in this demo download

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Freemark page Static

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.