JSP页面:
<img src="<%=request.getContextPath()%>/DisplayFile?filename=${contentVO.firstImage}"
alt="" width="164" height="124" border="0" class="thumb_img"
rel="${ctx}/view.do?method=view&id=${contentVO.id}"
link="${ctx}/view.do?method=view&id=${contentVO.id}"/>
servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author 461245 sgh
*
*/
public class DisplayFile extends HttpServlet {
protected static final Log log = LogFactory.getLog(ContentAction.class);
/**
* Default constructor.
*/
public DisplayFile() {
super();
}
public void init() throws ServletException {
return;
}
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ServletUtilities servletUtilities=new ServletUtilities();
HttpSession session = request.getSession();
String filename = request.getParameter("filename");
String type = request.getParameter("type");
String model = request.getParameter("model");
if("URL".equals(model)){
filename=dealFileName(request,filename);
servletUtilities.sendHTML(filename, response);
return ;
}
if (filename == null) {
log.error(new ServletException("Parameter 'filename' must be supplied"));
}
if (filename.equals("")) {
log.error(new ServletException("Parameter 'filename' must be supplied"));
}
String path="";
if(null!=type&&"xml".equals(type)){
path=Config.getConfigFilesPath();
}else{
path=Config.getFilepath();
}
servletUtilities.sendTempFile(new java.io.File(path+"/"+filename), response);
return;
}
private String dealFileName(HttpServletRequest request, String filename) {
String reString = "";
reString = filename;
int pos=filename.indexOf(".");
String type=Util.getFileSuffixName(filename);
if(type==null) return reString;
if(pos+type.length()==filename.length()){
String path = request.getContextPath();
reString = path + "/DisplayFile?filename=" + filename;
}
return reString;
}
}
工具类:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
public class ServletUtilities {
protected static final Log log = LogFactory.getLog(ContentAction.class);
public void sendTempFile(File file, HttpServletResponse response)
throws IOException {
String mimeType = null;
String filename = file.getName();
String suffixName=Util.getFileSuffixName(filename);
if (".xml".equalsIgnoreCase(suffixName)){
sendXML(file,response);
return ;
}
if(".jpeg".equalsIgnoreCase(suffixName)||
".jpg".equalsIgnoreCase(suffixName)||
".jpe".equalsIgnoreCase(suffixName)) mimeType = "image/jpeg";
if(".png".equalsIgnoreCase(suffixName)) mimeType = "image/png";
if(".gif".equalsIgnoreCase(suffixName)) mimeType = "image/gif";
if(".qt".equalsIgnoreCase(suffixName)||
".mov".equalsIgnoreCase(suffixName)) mimeType = "video/quicktime";
if(".mpeg".equalsIgnoreCase(suffixName)||
".mpg".equalsIgnoreCase(suffixName)||
".mpe".equalsIgnoreCase(suffixName)) mimeType = "video/mpeg";
if(".mpv2".equalsIgnoreCase(suffixName)||
".mp2v".equalsIgnoreCase(suffixName)) mimeType = "video/mpeg-2";
if(".avi".equalsIgnoreCase(suffixName)) mimeType = "video/x-msvideo";
if(".rm".equalsIgnoreCase(suffixName)) mimeType = "audio/x-pn-realaudio";
if(".rmvb".equalsIgnoreCase(suffixName)) mimeType = "application/vnd.rn-realmedia-vbr";
if(".swf".equalsIgnoreCase(suffixName)) mimeType = "application/x-shockwave-flash";
if(".3gp".equalsIgnoreCase(suffixName)) mimeType = "video/3gpp";
if(".amr".equalsIgnoreCase(suffixName)) mimeType = "audio/amr";
if(".mp3".equalsIgnoreCase(suffixName)) mimeType = "audio/mpeg";
if(".mp4".equalsIgnoreCase(suffixName)) mimeType = "video/mp4";
if (null == mimeType)
mimeType = "text/html";
sendTempFile(file, response, mimeType);
}
public void sendXML(File file,HttpServletResponse response) throws IOException {
Document doc=Util.loadXML(file);
String repStr =doc.asXML();// new String(doc.asXML().getBytes(), "GBK");
if (repStr != null) {
response.setContentType("text/xml;charset=GBK");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(repStr);
}
}
/**
* Binary streams the specified file to the HTTP response in 1KB chunks.
*
* @param file
* the file to be streamed.
* @param response
* the HTTP response object.
* @param mimeType
* the mime type of the file, null allowed.
*
* @throws IOException
* if there is an I/O problem.
*/
public void sendTempFile(File file, HttpServletResponse response,
String mimeType) throws IOException {
if(!file.isFile()){
log.error(new Exception(file.getName()+"is not a file"));
return ;
}
if (file.exists()) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// Set HTTP headers
if (mimeType != null) {
response.setHeader("Content-Type", mimeType);
}
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setCharacterEncoding("GBK");
BufferedOutputStream bos = new BufferedOutputStream(
response.getOutputStream());
byte[] input = new byte[1024];
boolean eof = false;
while (!eof) {
int length = bis.read(input);
if (length == -1) {
eof = true;
} else {
bos.write(input, 0, length);
}
}
bos.flush();
bis.close();
bos.close();
} else {
throw new FileNotFoundException(file.getAbsolutePath());
}
return;
}
public void sendHTML(String src, HttpServletResponse response) throws IOException {
StringBuffer html=new StringBuffer();
Displayer displayer=new Displayer();
try {
html=displayer.excute(src);
} catch (Exception e) {
log.error(e);
}
response.setHeader("Content-Type", "text/html");
response.setHeader("Content-Length",Integer.toString(html.length()) );
response.setCharacterEncoding("GBK");
ByteArrayInputStream bais=new ByteArrayInputStream(html.toString().getBytes());
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] input = new byte[1024];
boolean eof = false;
while (!eof) {
int length = bais.read(input);
if (length == -1) {
eof = true;
} else {
bos.write(input, 0, length);
}
}
bos.flush();
bais.close();
bos.close();
return;
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Config {
public static Properties props = new Properties();
public static void load() throws Exception {
props = Util.parse("config.xml", new ConfigHandler());
try{
String[] imgs=getImage().split(",");
for (String str : imgs) {
img.put(str, str);
}
String[] musics=getMusic().split(",");
for (String str : musics) {
music.put(str, str);
}
String[] movies=getMovie().split(",");
for (String str : movies) {
movie.put(str, str);
}
String[] roles=getRole().split(",");
for (String str : roles) {
role.put(str, str);
}
}catch(Exception e){
}
}
public static String getFilepath() {
return props.getProperty("filepath");
}
public static String getConfigFilesPath() {
return props.getProperty("configfilespath");
}
public static String getMenuNodes() {
return props.getProperty("menunodes");
}
public static String getWorkflow() {
return props.getProperty("workflow");
}
public static String getDriverClassName() {
return props.getProperty("driverclassname");
}
public static String getJdbcUrl() {
return props.getProperty("jdbcurl");
}
public static String getJdbcUsername() {
return props.getProperty("jdbcusername");
}
public static String getJdbcPassword() {
return props.getProperty("jdbcpassword");
}
public static String getImage() {
return props.getProperty("img");
}
public static String getMovie() {
return props.getProperty("movie");
}
public static String getMusic() {
return props.getProperty("music");
}
public static String getFtpHostName() {
return props.getProperty("ftphostname");
}
public static String getFtpPort() {
return props.getProperty("ftpport");
}
public static String getFtpUserName() {
return props.getProperty("ftpusername");
}
public static String getFtpPassword() {
return props.getProperty("ftppassword");
}
public static String get() {
return props.getProperty("ftpremotepath");
}
public static String getFtpRemotePath() {
return props.getProperty("ftpremotepath");
}
public static String getRole(){
return props.getProperty("role");
}
public static String getCPID() {
return props.getProperty("cpid");
}
public static String getServiceID() {
return props.getProperty("serviceid");
}
public static String getSourceID() {
return props.getProperty("sourceid");
}
public static String getFileSubmitRequestURL() {
return props.getProperty("filesubmitrequesturl");
}
public static Map<String,String> role=new HashMap<String,String>();
public static Map<String,String> img=new HashMap<String,String>();
public static Map<String,String> movie=new HashMap<String,String>();
public static Map<String,String> music=new HashMap<String,String>();
public static void main(String[] args) {
try {
TreeConfig.load();
Map<String,Tree> nodes=TreeConfig.nodes;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Util {
public static final String GBK = "GBK";
public static final String FORMAT_DAT_01="yyyy年MM月dd日 HH点mm分";
public static final String FORMAT_DAT_02="yyyy-MM-dd";
public static final String FORMAT_DAT_03="yyyyMMdd";
public static final String FORMAT_DAT_04="yyyy-MM-dd HH:mm";
protected static final Log log = LogFactory.getLog(Util.class);
public static InputStream getConfigFile(String filename) throws Exception {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(filename);
return url.openStream();
}
public static String format(Date date, String format){
SimpleDateFormat f=new SimpleDateFormat(format);
return f.format(date);
}
public static Map<String, Task> parse(String filename) throws Exception {
WorkFlowHandler definedWorkFlowHandler = new WorkFlowHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
parser.parse(getConfigFile(filename), definedWorkFlowHandler);
return definedWorkFlowHandler.getTasks();
}
public static Map<String, Task> parse(StringBuffer xml,WorkFlowHandler definedWorkFlowHandler) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
InputStream inputStream = new ByteArrayInputStream(xml.toString().getBytes());
parser.parse(inputStream, definedWorkFlowHandler);
return definedWorkFlowHandler.getTasks();
}
public static Properties parse(String filename, ConfigHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
parser.parse(getConfigFile(filename), handle);
return handle.getProps();
}
public static Map<String, Tree> parse(String filename, TreeHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
parser.parse(getConfigFile(filename), handle);
arrange(handle.getAll2());
return handle.getNodes();
}
public static Map<String, Tree> parseAndArrange(StringBuffer xml, TreeHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
InputStream inputStream = new ByteArrayInputStream(xml.toString().getBytes());
parser.parse(inputStream, handle);
arrange(handle.getAll2());
return handle.getNodes();
}
public static Map<String, Tree> parse(StringBuffer xml, TreeHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
InputStream inputStream = new ByteArrayInputStream(xml.toString().getBytes());
parser.parse(inputStream, handle);
return handle.getNodes();
}
public static Map<String, Area> parse(String filename, CacheHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
parser.parse(getConfigFile(filename), handle);
return handle.getAreas();
}
public static Map<String, Viewer> parse(String filename, DisplayerHandler handle)
throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
parser.parse(getConfigFile(filename), handle);
return handle.getViewers();
}
private static void arrange(List<Tree> nodes) {
int i = 0;
for (Tree tree : nodes) {
Map<String, Tree> childs = new HashMap<String, Tree>();
for (int j = i + 1; j < nodes.size(); j++) {
Tree temp = nodes.get(j);
if (tree.getId().equals(temp.getId())) {
Set<String> keys = childs.keySet();
for (String key : keys) {
tree.getChildeNodes().add(childs.get(key));
}
break;
}
if (childs.get(temp.getId()) == null)
childs.put(temp.getId(), temp);
}
i++;
}
}
public static String toGBK(String str) throws UnsupportedEncodingException {
return changeCharset(str, GBK);
}
public static String changeCharset(String str, String newCharset)
throws UnsupportedEncodingException {
if (str != null) {
// 用默认字符编码解码字符串。
byte[] bs = str.getBytes();
// 用新的字符编码生成字符串
return new String(bs, newCharset);
}
return null;
}
public static String changeCharset(String str, String oldCharset,
String newCharset) throws UnsupportedEncodingException {
if (str != null) {
// 用旧的字符编码解码字符串。解码可能会出现异常。
byte[] bs = str.getBytes(oldCharset);
// 用新的字符编码生成字符串
return new String(bs, newCharset);
}
return null;
}
public static Object readObject(String fileName) throws Exception {
Object obj=null;
InputStream is=null;
ObjectInputStream ois=null;
try{
is = new FileInputStream(fileName);
ois = new ObjectInputStream(is);
obj=ois.readObject();
}finally{
if(ois!=null) ois.close();
if(is!=null) is.close();
}
return obj;
}
public static void writeObject(String filename, Object o) throws Exception {
FileOutputStream os = null;
ObjectOutputStream oos = null;
try {
File f = new File(filename);
if (f.exists()) {
f.delete();
}
os = new FileOutputStream(f);
oos = new ObjectOutputStream(os);
oos.writeObject(o);
} finally {
if (oos != null)
oos.close();
if (os != null)
os.close();
}
}
/**
* 序列化list<Object>到文件
*
* @param rsls
* @param filename
*/
public static void writeObjToFile(List<Object> rsls, String filename)
throws Exception {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
OutputStream os = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
Iterator item = rsls.iterator();
while (item.hasNext()) {
Object obj = item.next();
oos.writeObject(obj);
}
byte[] data = baos.toByteArray();
os = new FileOutputStream(new File(filename));
os.write(data);
os.flush();
} finally {
if (os != null)
os.close();
if (oos != null)
oos.close();
if (baos != null)
baos.close();
}
}
/**
* 从序列化文件中读取、并对象化
*
* @param filename
* @return
*/
public static List<Object> readObjFromFile(String filename)
throws Exception {
List<Object> rsls = new ArrayList<Object>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(filename);
ois = new ObjectInputStream(fis);
while (fis.available() > 0) {
rsls.add(ois.readObject());
}
} finally {
if(ois!=null) ois.close();
if(fis!=null) fis.close();
}
return rsls;
}
public static String getFileSuffixName(String filename) {
if (filename == null)
return null;
if (filename.indexOf(".") < 0)
return "";
return filename.substring(filename.lastIndexOf("."));
}
public static List<FileVO> getFileList(String extend) throws Exception {
List<FileVO> fileList = new ArrayList<FileVO>();
String ex=extend.replaceAll("&", "%=26%");
Document document = DocumentHelper.parseText(ex);
List<Element> list = document.getRootElement().elements();
for (int i = 0; i < list.size(); i++) {
FileVO file = new FileVO();
file.setSrc(list.get(i).attribute("src").getValue());
file.setSrc(file.getSrc().replaceAll("%=26%", "&"));
file.setType(list.get(i).attribute("type").getValue());
file.setOrder(list.get(i).attribute("order").getValue());
file.setFirst(list.get(i).attribute("first").getValue());
try{file.setMode(list.get(i).attribute("mode").getValue());}catch(Exception e){}
try{file.setFilename(list.get(i).attribute("filename").getValue());}catch(Exception e){}
try{file.setHignDefinition(list.get(i).attribute("higndefinition").getValue());}catch(Exception e){}
try{file.setFilesize(Integer.parseInt(list.get(i).attribute("filesize").getValue()));}catch(Exception e){}
fileList.add(file);
}
return fileList;
}
public static boolean doc2XmlFile(Document document, String filename) {
boolean flag = true;
try {
/* 将document中的内容写入文件中 */
// 默认为UTF-8格式,指定为"GB2312"
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(GBK);
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)), format);
writer.write(document);
writer.close();
} catch (Exception ex) {
flag = false;
log.error(ex);
}
return flag;
}
public static Document loadXML(File file) {
Document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(file);
} catch (Exception ex) {
log.error(ex);
}
return document;
}
public static String dateToStr(Date date,String f) {
if(date==null) return "";
SimpleDateFormat format = new SimpleDateFormat(f);
String str = format.format(date);
return str;
}
/**
*
* @param str
* @return date
*/
public static Date strToDate(String str, String f) {
SimpleDateFormat format = new SimpleDateFormat(f);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
log.error(e);
}
return date;
}
public static java.sql.Date strToSQLDate(Object obj, String f) {
if(obj==null) return null;
String str=(String)obj;
Date sDate = strToDate(str, f);
if(sDate==null) return null;
return new java.sql.Date(sDate.getTime());
}
public static java.sql.Timestamp strToSQLTimestamp(Object obj, String f) {
if(obj==null) return null;
String str=(String)obj;
Date sDate = strToDate(str, f);
if(sDate==null) return null;
return new java.sql.Timestamp(sDate.getTime());
}
public static String getValueFormDynaBean(DynaBean dynaBean,String name){
String reString="";
Object tmp=dynaBean.get(name);
if(null!=tmp)
reString=tmp.toString();
return reString;
}
}