Velocity application example

xiaoxiao2021-03-06  98

Velocity application example

Keywords: Java, JSP, Servlet, Template, Template, Apache, Jakarta, Velocity Reader Requirements: Learn about Java Servlet Basic Concept

Velocity is a Java-based general template tool that comes from Jakarta.apache.org.

For the introduction of Velocity, please refer to Velocity - Java Web Development Technologies. Here is an application example.

This example refers to the structure of PHP-NUKE, that is, all HTTP requests are processed in the form of http://www.some.com/xxx/modules?name =xxxx/modules?name =xxxxx. All files in the example are .java and .html, no other special file formats. In addition to modules.java is Java servlet, the rest .java files are ordinary Java Class.

All HTTP requests are processed through modules.java. Modules.java loads modules.htm via Velocity. Modules.htm has a page head, footer, page left navigation link, and a few parts in the page. The page advertisement, the content is the change section. The page advertisement is processed by modules.java, and the content part in the page is processed by Modules.java Dispatch to sub-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 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 homeubpage ();

String RequestFunctionName = (String) Request.getParameter ("name");

Boolean Logined = False;

String loginaccount = (string) Request.getSession (TRUE) .GetaTribute

"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

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

ViewProgramItemitem ")) {

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";

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, relatively simple, only defined 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 Method in Sub Class of ProcessSubpage:"

this.getClass (). getname ());

Return "Sorry, this Module NOT FINISH YET.";

}

}

His .java file is basically a subclass of ProcessSubpage and some tool classes. The subclasses of ProcessSubpage are basically the same procedure, with similar context.put ("Page_footer", getPageFooterhtml ()); the variable portion in the HTML can be used. If there is no variable part, it is completely static web page, 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 aboutsis.com 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.mege (context, sw);

Return sw.toString ();

}

Catch (Exception EX) {

Return "ERROR GET TEMPLATE" FileName "" ex.getMessage ();

}

}

}

The subclasses of other processsubpages are basically similar above, but there will be some statements that have some context.put ("xxx", "xxxxx").

Through 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 a mechanism for centralized processing and then distribute (Dispatch). Don't worry that users access certain pages without landing. User verification, the header footer contains only one time, easy to write, modify, and maintain. The code is relatively simple, and it is easy to add your own page buffering function. You can save the HTML of a page in memory, cache a few minutes to implement page buffering function. Successful, the error page can also be encapsulated into functions with the same code, passing the message / title through the parameters. Because Java code is completely in different files, the artist and Java code staff can be divided into work. Everyone modifies their familiar files, basically does not need to take time to coordinate work. Use JSP, the art and Java code staff to change the maintenance .jsp file, more trouble, a lot of nightmares. And there is no use of XML, telling the truth, people who understand the XML / XLS only account for one in the Java programmers, people are not looking for.

Because all Java codes written by standard Java programs, you can use any Java editor, debugger, so development speed will also be greatly improved. US work is written by standard HTML files, no XML, is also familiar with them, and the speed is also very fast. And, when the website is required, as long as the art worker re-modifies the typography of the HTML file, the Java code is not changed at all.

Sleep! !

4) Tools 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 property 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 online

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 printy 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 INITX = New InitialContext ();

Javax.naming.context context = (javax.naming.context) initX.

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 ("in" 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

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

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 {

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 {

C. 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.mege (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.mege (context, sw);

Return sw.toString ();

}

Catch (Exception EX) {

Return "ERROR GET TEMPLATE" FileName "" ex.getMessage ();

}

}

}

Note: Chinese full-width spaces are used in the code based on the typographic needs. If you want to copy the code, make a text replace after replication.

Author Blog:

http://blog.9cbs.net/jacklondon/

related articles

I am using Joshua Bloch Email Discussion (Emails Between Joshua Bloch and ME) C Singleton Realization Velocity Application Example Velocity - Java Web Develop New Technology Java JDBC Database Connection Pool Implementation Method

转载请注明原文地址:https://www.9cbs.com/read-123622.html

New Post(0)