📄 sampleservlet.java
字号:
package com.meijia.db;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
public class SampleServlet extends VelocityServlet {
protected Properties loadConfiguration(ServletConfig config)throws IOException, FileNotFoundException{
/*
* 得到属性配置文件并load它
*/
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));
}
/*
* 设置velocity日志文件在web应用中的位置
*/
String log = p.getProperty(Velocity.RUNTIME_LOG);
if (log != null){
log = getServletContext().getRealPath(log);
if (log != null) {
p.setProperty(Velocity.RUNTIME_LOG, log);
}
}
/*
* 设置模板文件在web应用中的位置
*/
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;
}
public Template handleRequest(HttpServletRequest request,HttpServletResponse response,Context ctx){
String p1 = "tyl";
String p2 = "admin";
Vector personList = new Vector();
personList.addElement(p1);
personList.addElement(p2);
/*
* 将模板数据 list 放置到上下文环境 context 中去
*/
ctx.put("theList", personList);
/*
* 获取模板对象,有三种可能产生的异常
*/
Template outty = null;
try{
outty = getTemplate("sample.vm");
String path = getServletContext().getRealPath("/html/");//本WEB程序根目录服务器绝对路径
String name = ((new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))+".html");//最终保存路径
File index = new File(path+"\\"+name);
// File index = new File("f://test.html");
FileOutputStream output = new FileOutputStream(index);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
output, "utf-8"));
PrintWriter dw = new PrintWriter(path+"\\"+name);
outty.merge(ctx, dw);
dw.close();
} catch (ParseErrorException pee){
System.out.println(
"SampleServlet : parse error for template " + pee);
}catch (ResourceNotFoundException rnfe){
System.out.println("SampleServlet : template not found " + rnfe);
}catch (Exception e){
System.out.println("Error " + e);
}
return outty;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -