DWR反向Ajax示例(2)

本文介绍了一个使用Direct Web Remoting (DWR)实现的反向Ajax示例,展示了如何通过Java后台代码将消息添加到数据库,并更新前端页面显示。示例包括了数据库操作、页面更新逻辑及Ajax交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值