An example of Velocity application

Source: Internet
Author: User
Tags object getmessage header sql string variable tostring java web
Example | Application Example

Velocity is a general-purpose, java-based template tool that comes from jakarta.apache.org.

Velocity is a reference to the velocity--Java Web development technology . Here is an example of its application.

This example refers to the structure of the Php-nuke, where all HTTP requests are http://www.some.com/xxx/modules?name=xxx&

arg1=xxx&

Bbb=xxx in the form of a process. All files in the example are. java and. html, and there are no other special file formats. In addition to the Modules.java is the Java Servlet, the rest of the. java files are normal Java Class.

All HTTP requests are processed by Modules.java. Modules.java loads modules.htm by Velocity. Modules.htm has a page header, footer, page left navigation links, the content of several parts of the page. Where the page header ads, the content of the page is part of the change. The page header ad is processed by Modules.java, and the content in the page is processed by Modules.java Dispatch to the child page 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 Modulesextends Velocityservlet

{

Public Template handlerequest (httpservletrequest request,httpservletresponse response,context context)

{

Initresponse.setcontenttype ("text/html;

Charset=utf-8 ");

Response.setcharacterencoding ("Utf-8");

Prepare function Pageprocesssubpage 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 Mainpagepage = mainPage;

if (requestfunctionname = = null| | Requestfunctionname.equalsignorecase ("Home"))

{

page = MainPage;

}

No login, can use Pageelse 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 the other page, need login Firstelse 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 is Administratorelse 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 (""))

{

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 are for administrators only. "

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 would be used to Initiali Z The Velocity runtime. */protected java.util.Properties loadconfiguration (servletconfig config) throwsjava.io.IOException, Java.io.FileNotFoundException

{

Return utilities.initservletenvironment (this);

}

}

2) Processsubpage.java, relatively simple, only defines a 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 is in sub class of Processsubpage:" + this.getclass (). GetName ());

Return ' Sorry, this module is not finish yet. '

}

}

His. java file is essentially a processsubpage subclass and some tool classes. Processsubpage's subclasses are basically the same process, with similar

Context.put ("Page_footer", getpagefooterhtml ());

To replace the variable part of the HTML. If there is no variable part, completely static web pages, such as Aboutsubpage, it 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 basically similar to the above, except for a few more context.put ("xxx", "xxxx") statements.

From the above example, we can see that using the Velocity + Servlet, all the code is: 1 java serverlet + M Java class + n Html files.

Here is the mechanism for centralized processing and then distributing (dispatch). Don't worry about users accessing certain pages without landing. User authentication, header and footer contains only once, easy to write, modify, and maintain. The code is simple, and it's easy to add your own page buffering function. You can easily save a page's HTML in memory, cache a few minutes, to achieve page buffering function. A successful, error-prone page can also be encapsulated into functions using the same code, passing the Message/title through the parameters.

Because the Java code and the Html code completely in different files, art and Java code personnel can be a good division of labor, each person to modify their familiar documents, basically do not need to spend time to do coordination work. And with JSP, art and Java code personnel to work together to modify the maintenance. JSP file, a lot of trouble, a lot of nightmares. And there is no use of XML, to tell the truth, people who know xml/xls are only a fraction of the Java programmer, and the staff is difficult to find.

Because all Java code people write standard Java programs, you can use any Java editor, debugger, so the development speed will also be greatly improved. The art is written in standard Html files, no XML, and very familiar to them, and fast. And, when the need for Web site revision, as long as the art of the HTML file to modify the layout can be completely without changing a Java code.

It's so cool!!

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 Onceif (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 the Ru Ntime */properties p = new Properties ();

ServletConfig config = V.getservletconfig ();

Set the Velocity.file_resource_loaded_path property//to the root directory. 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 is the file//velocity.log relative to the root directory//of the CONTEXT.P.S Etproperty (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)

{

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 ();

}

}

}

keywords : (Java, JSP, Servlet, template, templates, Apache, Jakarta, Velocity)



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.