📄 sample.java
字号:
import java.util.List;import java.util.ArrayList;import java.util.Map;import java.util.HashMap;import java.util.Properties;import java.io.IOException;import java.io.FileNotFoundException;import java.io.FileInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletConfig;import org.apache.velocity.Template;import org.apache.velocity.context.Context;import org.apache.velocity.servlet.VelocityServlet;import org.apache.velocity.app.Velocity;import org.apache.velocity.exception.ResourceNotFoundException;import org.apache.velocity.exception.ParseErrorException;/** * This is a working example that shows how to use * Velocity from a servlet. Note that there is a little * more code than the JavaWorld article showed - required * for configuration. */public class Sample extends VelocityServlet{ public Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context context ) { /* * organize our data */ ArrayList list = new ArrayList(); Map map = new HashMap(); map.put("name", "horse"); map.put("price", "$100.00"); list.add( map ); map = new HashMap(); map.put("name", "dog"); map.put("price", "$59.99"); list.add( map ); map = new HashMap(); map.put("name", "bear"); map.put("price", "$3.99"); list.add( map ); /* * add that list to the context */ context.put("petList", list); /* * get the template */ Template template = null; try { template = getTemplate("petstoreemail.vm"); } catch( Exception e ) { System.out.println("Error from PetStore example Servlet " + e); } return template; } /** * Override the base class's loadConfiguration(), this will * set the log file to be off of the webapp root, and * will do the same with the file loader paths. This * will fail in containers that don't support getRealPath() * (this will be fixed in 1.3 relase with a new loader) */ protected Properties loadConfiguration(ServletConfig config ) throws IOException, FileNotFoundException { /* * get our properties file and load it */ String propsFile = config.getInitParameter(INIT_PROPS_KEY); Properties p = new Properties(); if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) { propsFile = realPath; } p.load( new FileInputStream(propsFile) ); } /* * first, normalize our velocity log file to be in the * webapp */ String log = p.getProperty( Velocity.RUNTIME_LOG); if (log != null ) { log = getServletContext().getRealPath( log ); if (log != null) { p.setProperty( Velocity.RUNTIME_LOG, log ); } } /* * now, if there is a file loader resource path, treat it the * same way. */ String path = p.getProperty( Velocity.FILE_RESOURCE_LOADER_PATH ); if ( path != null) { path = getServletContext().getRealPath( path ); if ( path != null) { p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, path ); } } return p; } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -