DWR反向Ajax示例(2)

PS:上接DWR反向Ajax示例(1);
3.Java后台代码:
package test;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import database.DBConnection;
/**
 * DWR反向Ajax示例
 * @author rzy
 * @version 1.0
 * */
public class JavaChat 
{
	private static String[][] msgs = null;
	public static WebContext wctx = null;
	//把信息显示到页面上
	public void addMessage(String[][] messages)
	{
		wctx = WebContextFactory.get();
		Util utilThis = new Util(wctx.getScriptSession());
		utilThis.setValue("title", "");
		utilThis.setValue("content", "");
		String currentPage = "/dwrtest/javachat1.jsp";
		Collection sessions = wctx.getScriptSessionsByPage(currentPage);
		Util utilAll = new Util(sessions);
		utilAll.removeAllRows("msg");
		utilAll.addRows("msg", messages);
		utilAll.setStyle("msg", "color", "red");
	}
	//调用添加和显示方法
	public void sendRow(String title,String content)
	{
		addMsg(title,content);
		addRowMsg();
	}
	//添加到信息到数据库中
	public int addMsg(String title,String content)
	{
		String sql = "insert into messages(title,content,date) values ('"+title+"','"+content+"','"+getSysDate()+"')";
		DBConnection dbConn = new DBConnection();
		int row = dbConn.executeUpdate(sql);
		dbConn.close();
		return row;
	}
	//获取数据库已有信息并添加到页面上
	public void addRowMsg()
	{
		String sql = "select * from messages order by id desc";
		DBConnection dbConn = new DBConnection();
		dbConn.rs = dbConn.executeQuery(sql);
		try {
			dbConn.rs.last();
			int num = dbConn.rs.getRow();
			dbConn.rs.beforeFirst();
			msgs = new String[num][3];
			int i = 0;
			while(dbConn.rs.next())
			{
				for(int j=0;j<3;j++)
				{
					if(j==0)
					{
						msgs[i][j] = "["+dbConn.rs.getString("title")+"]";
					}else if(j==1)
					{
						msgs[i][j] = dbConn.rs.getString("content");
					}else if(j==2)
					{
						msgs[i][j] = dbConn.rs.getString("date");
					}
				}
				i++;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			dbConn.close();
		}
		addMessage(msgs);
	}
	//获取当前日期
	public static String getSysDate()
	{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String nowDate = format.format(date);
		return nowDate;
	}
}

PS:DBConnection类是一个对数据库连接和操作的封装类;
数据库:表名:messages,字段:id,title,content,date.

你可能感兴趣的:(java,sql,Ajax,DWR,J#)