Using velocity to make page static can improve the performance of the site, but how does the generated static page be updated in real time?
1, the most stupid way, manual refresh. For example: Home page, when the Administrator update a feature, manually click a button in the background to update the corresponding HTML file 2, timed refresh. Update all existing HTML files at a specified time, if you want to verify which HTML files have already been generated. As to how to verify. You can write to a list or file of memory every time a file is generated, or to a table that writes the currently generated file name
3. Smart Refresh
The administrator in the background of each operation additions and deletions, all monitoring, and after the operation to verify that the corresponding file exists, there is an update, does not exist do not operate
using the third smart refresh it's a bit more scientific, using a third approach we need to use the observer pattern in the design pattern
to initialize the velocity configuration:
Package com.wwxl.filter;
Import java.io.IOException;
Import java.util.Properties;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import org.apache.velocity.app.Velocity;
Import Com.wwxl.servletcontext.FConfig;
/** * Servlet Filter Implementation Class Setcodefilter */public class Setcodefilter implements Filter {/**
* Default constructor.
*/Public Setcodefilter () {//TODO auto-generated constructor stub}/** * @see Filter#destroy () */ public void Destroy () {//TODO auto-generated Method stub}/** * @see filter#dofilter (ServletRequest, Servletre Sponse, Filterchain) */public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throw S IOException, servletexception {//TODO auto-generated Method Stub//place your code here//Pass the request along the filter chain Chain.dofilter (request, response); }/** * @see filter#init (filterconfig) */@SuppressWarnings ("static-access") public void init (Filterconfig fconfig
) throws Servletexception {//Initialize velocity Configuration Properties Properties=new properties (); Specify the velocity log storage location properties.put ("Runtime.log", Fconfig.getservletcontext (). Getrealpath ("/web-inf/log/velo
City_example.log ")); Specifies the location where the template is stored Properties.put ("File.resource.loader.path", Fconfig.getservletcontext (). Getrealpath ("/web-inf/v
elocity/"));
Properties.put ("input.encoding", "UTF-8");
Properties.put ("Default.contenttype", "text/html;charset\\=utf-8");
Properties.put ("output.encoding", "UTF-8");
Velocity.init (properties);
When initializing, get ServletContext, in Java code will use this servletcontext to get the relative path of the server Fconfig fc=new fconfig ();
Fc.setservletcontext (Fconfig.getservletcontext ());
}
}
Package com.wwxl.servletcontext;
Import Javax.servlet.ServletContext;
/**
* Get ServletContext, life cycle is created from ServletContext to server off
* @author Administrator * */Public
class Fconfig {
public static ServletContext ServletContext;
public static ServletContext Getservletcontext () {
return servletcontext;
}
public static void Setservletcontext (ServletContext servletcontext) {
fconfig.servletcontext = ServletContext;
}
}
Observed by:
Package Com.wwxl.service.impl;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import java.util.Observable;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import Org.springframework.stereotype.Service;
Import org.springframework.transaction.annotation.Transactional;
Import Com.wwxl.dao.UserDao;
Import Com.wwxl.entity.User;
Import Com.wwxl.observer.UserServiceimplObserver;
Import Com.wwxl.service.UserService; The observed object inherits Observable @Service @Transactional public class Userserviceimpl extends Observable implements userservice{@Aut
Owired @Qualifier ("Userdao") private Userdao Userdao;
/** * Add User */public boolean SVA (user user) {Boolean falg=this.userdao.sva (user);
if (falg) {map<string,object> maps=new hashmap<string, object> ();
Maps.put ("Falg", "save");
Maps.put ("user", user);
Mark this Observable object as a changed object; Now the HasChanged method returns True. This.setchangeD ();
If the HasChanged method indicates that the object has changed, notify all its observers and call the Clearchanged method to indicate that the object is no longer changing, and that maps is the content of the change this.notifyobservers (maps);
} return falg;
}/** * Query user */public list<user> FindAll () {return this.userDao.findAll ();
/** * Query user by ID */public user Finduserbyid (String ID) {return this.userDao.getById (ID); }//Registered observer, a observable object can have one or more observers.
The observer can be any object that implements the Observer interface public Userserviceimpl () {///Registered observer This.addobserver (new Userserviceimplobserver ());
}
}
Observers, observe what the user has done, and then update or delete, generate HTML pages
Package com.wwxl.observer;
Import Java.util.Map;
Import java.util.Observable;
Import Java.util.Observer;
Import Com.wwxl.entity.User;
Import Com.wwxl.servletcontext.FConfig;
Import Com.wwxl.util.JHtmlVelocityGenerator;
The observer, observing that the user has changed, generates a static page public
class Userserviceimplobserver extends Fconfig implements observer{
// Observe if the user modified the data
@SuppressWarnings ("unchecked") public
void update (Observable o, Object Arg) {
map< String,object> maps= (map<string, object>) arg;
String falg= (String) maps.get ("Falg");
System.out.println ("What to do with the user:" +falg);
User user= (user) Maps.get ("user");
Boolean falgs=jhtmlvelocitygenerator.jhtmlvelocitygenerators (Getservletcontext (), User, "mytemplates.html", "res/ Template ");
if (Falgs)
{
System.out.println ("Generate static page Success");
}
else
{
System.out.println ("Failed to generate static page");}
}}
To generate a static page:
package com.wwxl.util;
Import Java.io.File;
Import Javax.servlet.ServletContext;
Import Org.apache.velocity.VelocityContext;
Import com.wwxl.constant.ClassConstant;
Import Com.wwxl.entity.User;
public class Jhtmlvelocitygenerator extends Htmlvelocitygenerator {/** * generate static page * @param servletcontext servlert Context * @param object MODIFIED by entity * @param templatename template name * @param savepath Storage Path */public static Boolean Jhtmlvelocitygen
Erators (ServletContext servletcontext,user user,string templatename,string savepath) {Boolean falg=false;
Gets the relative path of String Realpath =servletcontext.getrealpath (Savepath);
File SaveFiles = new file (Realpath);
if (!savefiles.exists ()) savefiles.mkdirs ();
String Htmlname=classconstant.html_prefix+user.getid ();
Velocitycontext context = new Velocitycontext ();
Context.put ("user", user);
Falg=htmlvelocitygenerator.htmlcreate (SaveFiles, templatename, HTMLName, context);
return falg; }
}
Common methods for generating static pages:
Package com.wwxl.util;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.OutputStreamWriter;
Import Org.apache.velocity.Template;
Import Org.apache.velocity.VelocityContext;
Import org.apache.velocity.app.Velocity; /** * Velocity static page Generation generic class * @author Deng Wenwei * */public class htmlvelocitygenerator{/** * Static page builder * @param savefiles
HTML page Saved path * @param templatename template name * @param htmlname generated HTML name * @param context Velocity Context * @return */
public static Boolean htmlcreate (File savefiles,string templatename,string htmlname,velocitycontext context) {try {
Template template = Velocity.gettemplate (templatename);
File SaveFile = new file (savefiles,htmlname+ ". html");
FileOutputStream OutStream = new FileOutputStream (savefile);
OutputStreamWriter writer = new OutputStreamWriter (OutStream, "UTF-8");
BufferedWriter bufferwriter = new BufferedWriter (writer); Template.merge (context, BUfferwriter);
Bufferwriter.flush ();
Outstream.close ();
Bufferwriter.close ();
return true;
}catch (Exception e) {e.printstacktrace ();
return false;
}} public static void Main (string[] args) {//htmlvelocitygenerator.htmlcreate ("c:/");
}
}
Static page generation succeeds after accessing static resources:
/**
* Query static resources
* @param request
* @param response
* @param ID
* @return
*
/@RequestMapping ({ "/userids.htm"}) public
Modelandview Userbyids (httpservletrequest request,
httpservletresponse response, String ID) {
modelandview mv = new Jmodelandview (null, request, response);
Get the name of the static HTML file to generate
String HTMLName =html_prefix + ID + ". HTML";
Mv.setviewname (context_res_template+htmlname);
return MV;
}
Many details are still to be optimized, so record it, it took me half a day to get this!