JSP生成HTML

| No Comments | No TrackBacks

1、JSP
<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.text.*" %>
<%@ page import="javax.servlet.*,javax.servlet.http.*"%>
<jsp:useBean id="conn" scope="page" class="DBLink.DBSQL"/>
<jsp:useBean id="ReadTemplates" scope="page" class="ball.news.ReadTemplates"/>
<jsp:useBean id="WriteHtml" scope="page" class="ball.news.WriteHtml"/>
<jsp:useBean id="ReplaceAll" scope="page" class="ball.news.ReplaceAll"/>
<%
//request.setCharacterEncoding("gb2312");

try{
String dir=request.getRealPath(".");
DiskFileUpload fu = new DiskFileUpload();


fu.setSizeMax(4194304); //设置文件大小. 这里文件只能上传4M以内的

fu.setSizeThreshold(4096); //设置缓冲大小.

fu.setRepositoryPath(dir+"/ball/news/images"); //设置临时目录.

List fileItems = fu.parseRequest(request); //解析请求,返回一个集合.


Iterator i = fileItems.iterator();
String fieldvalue="";
String ff = "";
String picname="false";
Object tt = "";
Vector v = new Vector();

while(i.hasNext())
{

FileItem fi = (FileItem)i.next();

if(fi.isFormField()) //这是用来确定是否为文件属性,
{

String fieldName = fi.getFieldName(); //这里取得表单名
fieldvalue=fi.getString(); //这里取得表单值

v.addElement(fieldvalue);

}

else //这里开始外理文件
{

File fullFile = new File(fi.getName());
ff = fullFile.getName();
String rr = "";


java.util.Date date2 = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddHHmmss"); //取得时间
String str2 = formatter.format(date2);
StringTokenizer st = new StringTokenizer(ff,".");
if (st.hasMoreTokens()){
String test12 = st.nextToken();
rr = st.nextToken();
//System.out.println(rr);
}
if (rr.equals("")&&!rr.equals("gif")&&!rr.equals("jpg")&&!rr.equals("jpeg"))
{
picname = "false";
}

else
{
picname = str2+"."+rr; //以时间为图片名称

File savedFile = new File(getServletContext().getRealPath("/ball/news/images/"),picname);

fi.write(savedFile); //上传到服务器
}
//System.out.println("picname------------------------"+picname);
}
//System.out.println("v------------------------"+v);
}
String[] flag = {"<temp_title>","<temp_date>","<temp_author>","<temp_content>","<str_Temp>","<temp_picture>"};

//将数据写入到数据库
Object newtype1 = v.elementAt(0);
String t = newtype1.toString();
int newtype = Integer.parseInt(t);
Object rowid1 = v.elementAt(1);
String rowid = rowid1.toString();
Object title1 = v.elementAt(2);
String title = title1.toString();
Object content1 = v.elementAt(3);
String content = content1.toString();
// System.out.println(down);
java.util.Date date = new java.util.Date();
String strdate = date.toLocaleString();

java.util.Date StrDate1 = new java.util.Date();
String StrDate = StrDate1.toLocaleString(); // 新闻发布时间
//String newtype="0";
conn.openDB();
String sql = "select top 5 * from b_news where newtype="+newtype+" order by id desc";
String strTemp="<tr><td>相关新闻</td></tr>";
ResultSet rs = conn.executeQuery(sql);
while (rs.next())
{
String t2 = rs.getString(2);
String t4 = rs.getString(4);
strTemp += "<tr><td>";
strTemp +="<a href=../../../"+t4+">";
strTemp += t2;
strTemp +="</a>";
}
strTemp +="</td></tr>";
rs.close();


//读取模板

String filePath = "";
filePath = request.getRealPath("\\ball\\news\\pnews.template");
String templateContent = null;
try{
templateContent = ReadTemplates.getTlpContent(filePath);
System.out.println(templateContent);
}
catch(Exception e)
{
System.out.println("error to template!");
}
//替换模板中的内容
//System.out.println("picname--------------------------------"+picname);

templateContent = ReplaceAll.replace(templateContent,flag[0],title);
templateContent = ReplaceAll.replace(templateContent,flag[1],StrDate);
//templateContent = ReplaceAll.replace(templateContent,flag[2],editer);
templateContent = ReplaceAll.replace(templateContent,flag[3],content);
templateContent = ReplaceAll.replace(templateContent,flag[4],strTemp);
templateContent = ReplaceAll.replace(templateContent,flag[5],picname);

// 根据时间得文件名与路径名

Calendar calendar = Calendar.getInstance();
String fileName = String.valueOf(calendar.getTimeInMillis()) +".html";
String pathName = request.getRealPath("ball/news")+"\\"+ calendar.get(Calendar.YEAR) + "\\"+ (calendar.get(Calendar.MONTH)+1) +"\\"+ calendar.get(Calendar.DAY_OF_MONTH)+"\\";
String url = calendar.get(Calendar.YEAR) + "/"+ (calendar.get(Calendar.MONTH)+1) +"/"+ calendar.get(Calendar.DAY_OF_MONTH)+"/";
url +=fileName;
//System.out.println(url);

try{
WriteHtml.save(templateContent,pathName,fileName);
}catch(Exception e){
System.out.println("error to html!-----------"+e.getMessage());
}


//写入数据库
String sqlInsert = null;
if (!picname.equals("false")){
sqlInsert = "insert into b_news (title,content,url,picture,newtype,addtime,rowid) values ('"+title+"','"+content+"','"+url+"','"+picname+"','"+newtype+"',getdate(),'"+rowid+"')";
}
else
{
picname="images/"+picname;
sqlInsert = "insert into b_news (title,content,url,newtype,addtime,rowid) values ('"+title+"','"+content+"','"+url+"','"+newtype+"',getdate(),'"+rowid+"')";
}
//System.out.println("sql insert---------------"+sqlInsert);
conn.executeUpdate (sqlInsert);
}
catch(Exception e)
{
System.out.println("upload error------------------"+e.getMessage());
}



%>
<%out.println("新闻生成html成功了!");%>

2、WriteHtml
WriteHtml.java

package ball.news;


import java.io.*;


public class WriteHtml
{


    public WriteHtml()
    {
    }


    public static void save(String s, String s1, String s2)
       
    {
        try
        {
            a(s1);
            FileOutputStream fileoutputstream = new FileOutputStream(s1 + s2);
            byte abyte0[] = s.getBytes();
            fileoutputstream.write(abyte0);
            fileoutputstream.close();
        }
        catch(IOException e)
        {
         System.out.println("write html error"+e.getMessage());
        }
    }


    private static void a(String s)
    {
       try
       {
        File file = new File(s);
        if(!file.exists())
            file.mkdirs();
       }
       catch (Exception e)
       {
        System.out.println("mkdirs error!"+e.getMessage());
       }
    }
}

3、ReadTemplates
ReadTemplates.java

package ball.news;
import java.io.*;
import java.util.*;


public class ReadTemplates
{


    private String temp = null;
    private Object a = new Object();


    public ReadTemplates()
    {
    }


    public String getTlpContent(String s)
       
    {
        if(temp == null)
            synchronized(a)
            {
                if(temp == null)
                    try
                    {
                        System.out.println("----------------------------");
                        temp = a(s);
                        //System.out.println("test the temp"+temp);
                    }
                    catch(Exception e)
                    {      
                       System.out.println("get tlpconente error"+e.getMessage());               
                    }
            }
        return temp;
    }


    private synchronized String a(String s)
       
    {
        String s1 = null;
        try
        {
            FileInputStream fileinputstream = new FileInputStream(s);
            int i = fileinputstream.available();
            byte abyte0[] = new byte[i];
            fileinputstream.read(abyte0);
            fileinputstream.close();
            s1 = new String(abyte0);
        }
        catch(IOException e)
        {
         System.out.println("ioexception error"+e.getMessage()); 
        }
        return s1;
    }


}

No TrackBacks

TrackBack URL: http://www.wujianrong.com/mt-tb.cgi/1656

Leave a comment

About this Entry

This page contains a single entry by kevinwu published on January 30, 2007 2:41 PM.

Java Configuration for Blandware AtLeap was the previous entry in this blog.

Plugging Aptana into an existing Eclipse configuration is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.