Skip to content

Instantly share code, notes, and snippets.

@akjava
Created May 19, 2013 13:43
Show Gist options
  • Save akjava/5607663 to your computer and use it in GitHub Desktop.
Save akjava/5607663 to your computer and use it in GitHub Desktop.
util class for use velocity in Google App Engine/Java
import java.io.StringWriter;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
/**
* create velocity dir in war directory.
*
*
* sample code
* this sample you need create a file which contain text "$title" at velocity/hello.html
*
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer output=new StringBuffer();
Map<String,String> hashMap=new HashMap<String, String>();
hashMap.put("title", "this is test");
String html=VelocityUtils.createVelocityPage(getServletContext(), "hello.html", hashMap);
output.append(html);
//print out
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(output.toString());
}
* @author aki
*
*/
public class VelocityUtils {
public static String baseVelocityDir="velocity";
@SuppressWarnings("rawtypes")
public static String createVelocityPage(ServletContext scontext,String realPath,Map map){
VelocityContext context= new VelocityContext(map);
return createVelocityPage(scontext, realPath, context);
}
public static String createVelocityPage(ServletContext scontext,String realPath,VelocityContext context){
Velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem");
setVelociyLoaderPath(scontext);
try {
Velocity.init();
} catch (Exception e) {
e.printStackTrace();
}
try{
StringWriter writer=new StringWriter();
Template template = Velocity.getTemplate(realPath, "UTF-8");
template.merge(context,writer);
return writer.toString();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static void setVelociyLoaderPath(ServletContext scontext){
String dir=scontext.getRealPath(baseVelocityDir);
Velocity.setProperty("file.resource.loader.path",dir );
}
public static VelocityContext createVelocityContext() {
VelocityContext context= new VelocityContext();
return context;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment