Application Example of Velocity

Source: Internet
Author: User

Application Example of Velocity

 Keywords: Java, JSP, Servlet, template, template, Apache, Jakarta, Velocity
Reader requirements: Understand the basic concepts of Java Servlet

Velocity is a Java-based general template tool from jakarta.apache.org.

For more information about velocity, seeVelocity -- New Java Web Development Technology. Here is an example of its application.

This example references the structure of PHP-Nuke, that is, all HTTP requests are in the http://www.some.com/xxx/Modules? Name = xxx & arg1 = xxx & BBB = xxx. In this example, all files are. Java and. html, and there are no other special file formats. Except that modules. Java is a Java Servlet, other. java files are common Java classes.

All HTTP requests are processed through modules. java. Modules. Java loads modules.htm through velocity. Modules.htm consists of the page header, footer, left navigation link, and content. Among them, the content of the page header advertisement and page is the change part. The page header advertisement is processed by modules. Java, and the Content Part of the page is processed by modules. Java dispatch to the subpage class.

1) modules. Java

 
     
 
import javax.servlet.*;import javax.servlet.http.*;import org.apache.velocity.*;import org.apache.velocity.context.*;import org.apache.velocity.exception.*;import org.apache.velocity.servlet.*;import commontools.*;public class Modules  extends VelocityServlet {  public Template handleRequest(HttpServletRequest request,                 HttpServletResponse response,                 Context context) {    //init    response.setContentType("text/html; charset=UTF-8");    response.setCharacterEncoding("utf-8");    //prepare function page    ProcessSubPage page = null;    ProcessSubPage mainPage = new HomeSubPage();    String requestFunctionName = (String) request.getParameter("name");    boolean logined = false;    String loginaccount = (String) request.getSession(true).getAttribute(      "loginaccount");    if (loginaccount != null) {      logined = true;    }    //default page is mainpage    page = mainPage;    if (requestFunctionName == null||requestFunctionName.equalsIgnoreCase("home")) {      page = mainPage;    }    //no login , can use these page    else if (requestFunctionName.equalsIgnoreCase("login")) {      page = new LoginProcessSubPage();    }    else if (requestFunctionName.equalsIgnoreCase("ChangePassword")) {      page = new ChangePasswordSubPage();    }    else if (requestFunctionName.equalsIgnoreCase("ForgetPassword")) {      page = new ForgetPassword();    }    else if (requestFunctionName.equalsIgnoreCase("about")) {      page = new AboutSubPage();    }    else if (requestFunctionName.equalsIgnoreCase("contact")) {      page = new ContactSubPage();    }    //for other page, need login first    else if (logined == false) {      page = new LoginProcessSubPage();    }    else if (requestFunctionName.equalsIgnoreCase("listProgram")) {      page = new ListTransactionProgramSubPage();    }    else if (requestFunctionName.equalsIgnoreCase(      "ViewProgramItem")) {      page = new ViewTransactionProgramItemSubPage();    }    else if (requestFunctionName.equalsIgnoreCase(      "UpdateProgramObjStatus")) {      page = new UpdateTransactionProgramObjStatusSubPage();    }    else if (requestFunctionName.equalsIgnoreCase(      "Search")) {      page = new SearchSubPage();    }    //check if this is administrator    else if (Utilities.isAdministratorLogined(request)) {      //Utilities.debugPrintln("isAdministratorLogined : true");      if (requestFunctionName.equalsIgnoreCase("usermanagement")) {        page = new UserManagementSubPage();      }      else if (requestFunctionName.equalsIgnoreCase(        "UploadFiles")) {        page = new UploadFilesSubPage();      }      else if (requestFunctionName.equalsIgnoreCase(        "DownloadFile")) {        page = new DownloadFileSubPage();      }      else if (requestFunctionName.equalsIgnoreCase(        "Report")) {        page = new ReportSubPage();      }    }    else {      //no right to access.      //Utilities.debugPrintln("isAdministratorLogined : false");      page = null;    }    //Utilities.debugPrintln("page : " + page.getClass().getName());    if(page != null){      context.put("function_page",            page.getHtml(this, request, response, context));    }else{      String msg = "Sorry, this module is for administrator only.
You are not administrator.
";      context.put("function_page",msg);    }        context.put("page_header",getPageHeaderHTML());    context.put("page_footer",getPageFooterHTML());    Template template = null;    try {      template = getTemplate("/templates/Modules.htm"); //good    }    catch (ResourceNotFoundException rnfe) {      Utilities.debugPrintln("ResourceNotFoundException 2");      rnfe.printStackTrace();    }    catch (ParseErrorException pee) {      Utilities.debugPrintln("ParseErrorException2 " + pee.getMessage());    }    catch (Exception e) {      Utilities.debugPrintln("Exception2 " + e.getMessage());    }    return template;  }  /**   * Loads the configuration information and returns that information as a Properties, e   * which will be used to initializ the Velocity runtime.   */  protected java.util.Properties loadConfiguration(ServletConfig config) throws    java.io.IOException, java.io.FileNotFoundException {    return Utilities.initServletEnvironment(this);  }}
 
     

2) processsubpage. Java, which is relatively simple and only defines one function interface gethtml

     
 
import javax.servlet.http.*;import org.apache.velocity.context.*;import org.apache.velocity.servlet.*;import commontools.*;public abstract class ProcessSubPage implements java.io.Serializable {  public ProcessSubPage() {  }  public String getHtml(VelocityServlet servlet, HttpServletRequest request,             HttpServletResponse response,             Context context) {    Utilities.debugPrintln(      "you need to override this method in sub class of ProcessSubPage:"      + this.getClass().getName());    return "Sorry, this module not finish yet.";  }}
 
     

The. Java file is basically a subclass of processsubpage and some tool classes. The child classes of processsubpage are basically the same process.
Context. Put ("page_footer", getpagefooterhtml ());
Replace the variable part in. html. If there is no variable part, it is completely a static webpage, such as aboutsubpage, Which is simpler.

3) aboutsubpage. Java

     
 
import org.apache.velocity.servlet.VelocityServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.velocity.context.Context;public class AboutSubPage extends ProcessSubPage {  public AboutSubPage() {  }  public String getHtml(VelocityServlet servlet, HttpServletRequest request,             HttpServletResponse response, Context context) {    //prepare data    //context.put("xxx","xxxx");                          Template template = null;    String fileName = "About.htm";    try {      template = servlet.getTemplate(fileName);      StringWriter sw = new StringWriter();      template.merge(context, sw);      return sw.toString();    }    catch (Exception ex) {      return "error get template " + fileName + " " + ex.getMessage();    }  }}
 
     

The other processsubpage subclasses are similar, but some context. Put ("XXX", "XXXX") statements are added.

Through the above example, we can see that using velocity + servlet, all the code is: 1 Java serverlet + M Java class + n html files.

Here we use the centralized processing and then dispatch (dispatch) mechanism. You don't have to worry about accessing some pages without logging in. User verification: the header and footer are only written once, which is easy to write, modify, and maintain. The code is concise, and it is easy to add its own page buffering function. You can save the HTML of a page in the memory for several minutes to buffer the page. The success and error pages can also be encapsulated into functions using the same code, and the message/title can be passed in through parameters.

Because Java code and HTML code are completely different from each other, the artist and Java code staff can work well in different ways. when each person modifies a file that he or she is familiar with, there is basically no need to spend time on coordination. Using JSP, the artist and Java code staff modify and maintain the. jsp file together, causing a lot of trouble and a lot of nightmares. XML is not used here. To be honest, people who know XML/XLS are only a fraction of Java programmers.

Because all Java code workers write standard Java programs and can use any Java editor or debugger, the development speed will be greatly improved. The artist wrote standard HTML files without XML. They are also familiar with them and the speed is fast. In addition, when you need a website revision, you only need to modify the HTML file again and do not need to modify a Java code.

It's amazing !!

4) tool class utilities. Java

     
 
import java.io.*;import java.sql.*;import java.text.*;import java.util.*;import java.util.Date;import javax.naming.*;import javax.servlet.*;import javax.servlet.http.*;import org.apache.velocity.*;import org.apache.velocity.app.*;import org.apache.velocity.context.Context;import org.apache.velocity.servlet.*;public class Utilities {  private static Properties m_servletConfig = null;  private Utilities() {  }  static {    initJavaMail();  }  public static void debugPrintln(Object o) {    String msg = "proj debug message at " + getNowTimeString() +      " ------------- ";    System.err.println(msg + o);  }  public static Properties initServletEnvironment(VelocityServlet v) {    // init only once    if (m_servletConfig != null) {      return m_servletConfig;    }    //debugPrintln("initServletEnvironment....");    try {      /*       * call the overridable method to allow the       * derived classes a shot at altering the configuration       * before initializing Runtime       */      Properties p = new Properties();      ServletConfig config = v.getServletConfig();      // Set the Velocity.FILE_RESOURCE_LOADED_PATH property      // to the root directory of the context.      String path = config.getServletContext().getRealPath("/");      //debugPrintln("real path of / is : " + path);      p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);      // Set the Velocity.RUNTIME_LOG property to be the file      // velocity.log relative to the root directory      // of the context.      p.setProperty(Velocity.RUNTIME_LOG, path +             "velocity.log");// Return the Properties object.//return p;      Velocity.init(p);      m_servletConfig = p;      return p;    }    catch (Exception e) {      debugPrintln(e.getMessage());      //throw new ServletException("Error initializing Velocity: " + e);    }    return null;    //this.getServletContext().getRealPath("/");  }  private static void initJavaMail() {  }  public static Connection getDatabaseConnection() {    Connection con = null;    try {      InitialContext initCtx = new InitialContext();      javax.naming.Context context = (javax.naming.Context) initCtx.        lookup("java:comp/env");      javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup(        "jdbc/TestDB");      //Utilities.debugPrintln("ds = " + ds);      con = ds.getConnection();    }    catch (Exception e) {      Utilities.debugPrintln("Exception = " + e.getMessage());      return null;    }    //Utilities.debugPrintln("con = " + con);    return con;  }  public static java.sql.ResultSet excuteDbQuery(Connection con, String sql,    Object[] parameters) {    //Exception err = null;    //Utilities.debugPrintln("excuteDbQuery" + parameters[0] + " ,sql=" + sql);    try {      java.sql.PreparedStatement ps = con.prepareStatement(sql);      for (int i = 0; i < parameters.length; i++) {        processParameter(ps, i + 1, parameters[i]);      }      return ps.executeQuery();    }    catch (Exception e) {      //Utilities.debugPrintln(e.getMessage());      e.printStackTrace();    }    return null;  }  public static void excuteDbUpdate(String sql, Object[] parameters) {    Connection con = Utilities.getDatabaseConnection();    excuteDbUpdate(con, sql, parameters);    closeDbConnection(con);  }  public static void excuteDbUpdate(Connection con, String sql,                   Object[] parameters) {    Exception err = null;    try {      java.sql.PreparedStatement ps = con.prepareStatement(sql);      for (int i = 0; i < parameters.length; i++) {        processParameter(ps, i + 1, parameters[i]);      }      ps.execute();    }    catch (Exception e) {      err = e;      //Utilities.debugPrintln(err.getMessage());      e.printStackTrace();    }  }  private static void processParameter(java.sql.PreparedStatement ps,                     int index, Object parameter) {    try {      if (parameter instanceof String) {        ps.setString(index, (String) parameter);      }      else {        ps.setObject(index, parameter);      }    }    catch (Exception e) {      //Utilities.debugPrintln(e.getMessage());      e.printStackTrace();    }  }  public static void closeDbConnection(java.sql.Connection con) {    try {      con.close();    }    catch (Exception e) {      Utilities.debugPrintln(e.getMessage());    }  }  public static String getResultPage(    String title, String message, String jumpLink,    VelocityServlet servlet, HttpServletRequest request,    HttpServletResponse response, Context context) {    Template template = null;    context.put("MessageTitle", title);    context.put("ResultMessage", message);    context.put("JumpLink", jumpLink);    try {      template = servlet.getTemplate(        "/templates/Message.htm");      StringWriter sw = new StringWriter();      template.merge(context, sw);      return sw.toString();    }    catch (Exception ex) {      return "error get template Message.htm " + ex.getMessage();    }  }  public static String mergeTemplate(String fileName, VelocityServlet servlet,                    Context context) {    Template template = null;    try {      template = servlet.getTemplate(fileName);      StringWriter sw = new StringWriter();      template.merge(context, sw);      return sw.toString();    }    catch (Exception ex) {      return "error get template " + fileName + " " + ex.getMessage();    }  }}
 
     

 

Note: Based on the typographical requirements, the Code uses Chinese fullwidth spaces. If you want to copy the code, replace the text after the copy.

 

Author's blog:Http://blog.csdn.net/jacklondon/Related Articles

My email discussion with Joshua BLOCH (emails between Joshua Bloch and me)
Singleton implementation in C ++
Application Example of Velocity
Velocity -- New Java Web Development Technology
Java JDBC database connection pool Implementation Method

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.