短消息论坛
一.搭好架构
1.1导入basedao
package cn.jbit.demo.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class BaseDao { protected Connection con = null; protected PreparedStatement ps = null; protected ResultSet rs = null; public static final String driver="com.mysql.jdbc.Driver"; public static final String url="jdbc:mysql://localhost:3306/message"; public static final String username="root"; public static final String password="1234"; public void openConnection(){ try { Class.forName(driver); if(con==null||con.isClosed()){ con=DriverManager.getConnection(url,username,password); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } //获取连接 protected void openConnection2(){ try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Message"); con = ds.getConnection(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } //更新新据库 public int executeUpdata(String sql, List<Object> list){ openConnection(); try { ps = con.prepareStatement(sql); if(list == null) return ps.executeUpdate(); int i = 1; for(Object obj:list){ ps.setObject(i, obj); i++; } return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ closeResource(); } return 0; } //关闭流 protected void closeResource(){ try { if(rs != null) rs.close(); if(ps != null) ps.close(); if(con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
二.登录,注册页面
2.1 UserInfo中的代码:
package cn.jbit.demo.entity; public class UserInfo{ private String username = null;//用户名 private String password = null;//密码 private String email = null;//电子邮箱 public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2.2 UserinfoDao
package cn.jbit.demo.dao; import java.util.List; import java.util.Map; import cn.jbit.demo.entity.UserInfo; public interface UserinfoDao { //查找用户 public List<UserInfo> getUsers(Map<String,String> contitions); //添加或更新用户 public int executeUpdate(String operate, UserInfo userinfo); }
2.3 UserinfoDaoImpl
package cn.jbit.demo.dao.impl; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import cn.jbit.demo.dao.BaseDao; import cn.jbit.demo.dao.UserinfoDao; import cn.jbit.demo.entity.UserInfo; public class UserinfoDaoImpl extends BaseDao implements UserinfoDao { //添加或更新用户 public int executeUpdate(String operate, UserInfo userinfo) { List<Object> list = null; String sql = null; if(operate.equals("update")){ sql = "update msg_userinfo set password=? where username = '" + userinfo.getUsername() + "'"; list = new ArrayList<Object>(); list.add(userinfo.getPassword()); }else if(operate.equals("insert")){ sql = "insert into msg_userinfo values(?,?,?)"; list = new ArrayList<Object>(); list.add(userinfo.getUsername()); list.add(userinfo.getPassword()); list.add(userinfo.getEmail()); } return executeUpdata(sql, list); } //查找用户 public List<UserInfo> getUsers(Map<String,String> contitions) { String username = (String) contitions.get("username"); String pwd = (String) contitions.get("pwd"); String operate = (String)contitions.get("operate"); String sql = "select * from msg_userinfo where 1=1 "; if(operate != null && operate.equals("except")){ sql += username != null ? " and username != '" + username + "'":""; }else{ sql += username != null ? " and username = '" + username + "'":""; } sql += pwd != null ? " and password = '" + pwd + "'":""; openConnection(); List<UserInfo> users = new ArrayList<UserInfo>(); try { ps = con.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ UserInfo uf = new UserInfo(); uf.setUsername(rs.getString("username")); uf.setPassword(rs.getString("password")); uf.setEmail(rs.getString("email")); users.add(uf); } } catch (SQLException e) { e.printStackTrace(); }finally{ closeResource(); } return users; } }
2.4 UserInfoBiz
package cn.jbit.demo.biz; import java.util.List; import java.util.Map; import cn.jbit.demo.entity.UserInfo; public interface UserInfoBiz { //查找用户 public List<UserInfo> findUser(Map<String,String> elements); //添加或更新用户 public int doInsertOrUpdateUser(String operate, UserInfo userinfo); }
2.5 UserInfoBizImpl
package cn.jbit.demo.biz.impl; import java.util.List; import java.util.Map; import cn.jbit.demo.biz.UserInfoBiz; import cn.jbit.demo.dao.UserinfoDao; import cn.jbit.demo.dao.impl.UserinfoDaoImpl; import cn.jbit.demo.entity.UserInfo; public class UserInfoBizImpl implements UserInfoBiz { private UserinfoDao userinfoDao = new UserinfoDaoImpl(); //添加或更新用户 public int doInsertOrUpdateUser(String operate, UserInfo userinfo) { return userinfoDao.executeUpdate(operate, userinfo); } //查找用户 public List<UserInfo> findUser(Map<String,String> elements) { return userinfoDao.getUsers(elements); } }
2.6 UserServlet
package cn.jbit.demo.web; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.jbit.demo.biz.UserInfoBiz; import cn.jbit.demo.biz.impl.UserInfoBizImpl; import cn.jbit.demo.entity.UserInfo; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); UserInfoBiz userInfoBiz=new UserInfoBizImpl(); if ("login".equals(action)) {//登录 String username = request.getParameter("username"); String password = request.getParameter("password"); Map<String,String> contitions = new HashMap<String,String>(); contitions.put("username", username); contitions.put("pwd", password); List <UserInfo>list = userInfoBiz.findUser(contitions); if(list == null || list.size() != 1){ request.setAttribute("error", "用户名或密码错误!"); request.getRequestDispatcher("index.jsp").forward(request,response); }else{ request.getSession().setAttribute("loginuser", username); response.sendRedirect("MsgServlet?action=list"); } }else if("regist".equals(action)){//注册 String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); Map<String,String> conditions = new HashMap<String,String>(); conditions.put("username", username); List <UserInfo>list = userInfoBiz.findUser(conditions); if(list.size() > 0){ request.setAttribute("error", "此用户名已被注册"); request.getRequestDispatcher("register.jsp").forward(request,response); }else{ UserInfo uf = new UserInfo(); uf.setUsername(username); uf.setPassword(password); uf.setEmail(email); int isRun = userInfoBiz.doInsertOrUpdateUser("insert", uf); if(isRun > 0){ request.setAttribute("error", "已经成功注册!"); request.getRequestDispatcher("index.jsp").forward(request,response); } } }else if("logout".equals(action)){//退出 request.getSession().removeAttribute("loginuser"); response.sendRedirect("index.jsp"); }else if("findUsers".equals(action)){//查找其它所有的用户 String username = (String)request.getSession().getAttribute("loginuser"); Map <String,String>contitions = new HashMap<String,String>(); contitions.put("username", username); contitions.put("operate","except"); List<UserInfo> list = userInfoBiz.findUser(contitions); request.setAttribute("users", list); request.getRequestDispatcher("newMsg.jsp").forward(request,response); } } }
三.信息页面
3.1 BBSMessage
package cn.jbit.demo.entity; import java.util.Date; public class BBSMessage{ private String msgid = null;//ID private String username = null;//发送方 private String title = null;//标题 private String content = null;//内容 private int state = 0;//用户名 private String sendto=null;//收件方 private Date datetime = null;//发送时间 public String getMsgid() { return msgid; } public void setMsgid(String msgid) { this.msgid = msgid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getSendto() { return sendto; } public void setSendto(String sendto) { this.sendto = sendto; } public Date getDatetime() { return datetime; } public void setDatetime(Date datetime) { this.datetime = datetime; } }
3.2 BBSMessageDao
package cn.jbit.demo.dao; import java.util.List; import java.util.Map; import cn.jbit.demo.entity.BBSMessage; public interface BBSMessageDao { //查询短信息 public List<BBSMessage> getMessagesByPage(Map<String,Object> elements); //更新短信息 public int executeUpdate(String operate, Map<String,Object> elements, Map<String,Object> conditions); //获取短信条数 public int getMsgsCount(String username); }
3.3 BBSMessageDaoImpl
package cn.jbit.demo.dao.impl; import java.sql.SQLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import cn.jbit.demo.dao.BBSMessageDao; import cn.jbit.demo.dao.BaseDao; import cn.jbit.demo.entity.BBSMessage; public class BBSMessageDaoImpl extends BaseDao implements BBSMessageDao { /* * 执行update操作 * @param * operate:执行插入、更新还是删除 * elements:需要插入或者更新的值集合,key对应column,value是插入或者更新的值 * conditions:update执行的条件集合,key对应column,value是条件值 */ public int executeUpdate(String operate, Map <String,Object>elements, Map <String,Object>conditions) { List<Object> list = null; String sql = null; String msgid= null ,username= null,title= null,msgcontent= null,state= null,sendto= null; Date msg_create_date=null; /* * 获取需要变更的值 */ if(elements!=null && elements.size()>0){ msgid = (String)elements.get("msgid"); username = (String)elements.get("username"); title = (String)elements.get("title"); msgcontent = (String)elements.get("msgcontent"); state = (String)elements.get("state"); sendto = (String)elements.get("sendto"); msg_create_date = (Date)elements.get("msg_create_date"); } /* * 更新操作 */ if(operate.equals("update")){ /* * 拼写更新sql */ sql = "update msg set "; /* * 获取条件元素 */ String ctn_msgid = (String)conditions.get("msgid"); String ctn_username = (String)conditions.get("username"); String ctn_title = (String)conditions.get("title"); String ctn_msgcontent = (String)conditions.get("msgcontent"); String ctn_state = (String)conditions.get("state"); String ctn_sendto = (String)conditions.get("sendto"); Date ctn_msg_create_date = (Date)conditions.get("msg_create_date"); /* * 写出sql更新语句 */ String and = ""; sql += msgid!=null ? and + " msgid=? ":""; and = msgid!=null ? " and ":""; sql += username!=null ? and + " username=? ":""; and = username!=null ? " and ":""; sql += title!=null ? and + " title='" + title + "' ":""; and = title!=null ? " and ":""; sql += msgcontent!=null ? and + " msgcontent=? ":""; and = msgcontent!=null ? " and ":""; sql += sendto!=null ? and + " sendto=? ":""; and = sendto!=null ? " and ":""; sql += state!=null ? and + " state=? ":""; and = state!=null ? " and ":""; sql += msg_create_date != null ? and + " msg_create_date=? ":""; /* * 写出sql条件语句 */ sql = sql + " where 1=1 "; sql += ctn_msgid != null ? " and msgid=? ":""; sql += ctn_username != null ? " and username=? ":""; sql += ctn_title != null ? " and title='" + title + "' ":""; sql += ctn_msgcontent != null ? " and msgcontent=? ":""; sql += ctn_sendto != null ? " and sendto=? ":""; sql += ctn_state != null ? " and state=? ":""; sql += ctn_msg_create_date != null ? " and msg_create_date=? ":""; list = new ArrayList<Object>(); /* * 设置更新参数 */ if(msgid != null) list.add(msgid); if(username != null) list.add(username); if(title != null) list.add(title); if(msgcontent != null) list.add(msgcontent); if(sendto != null) list.add(sendto); if(state != null) list.add(state); if(msg_create_date != null) list.add(new Timestamp(msg_create_date.getTime())); /* * 设置条件参数 */ if(ctn_msgid != null) list.add(ctn_msgid); if(ctn_username != null) list.add(ctn_username); if(ctn_title != null) list.add(ctn_title); if(ctn_msgcontent != null) list.add(ctn_msgcontent); if(ctn_sendto != null) list.add(ctn_sendto); if(ctn_state != null) list.add(ctn_state); if(ctn_msg_create_date != null) list.add(new Timestamp(ctn_msg_create_date.getTime())); } /* * 添加操作 */ else if(operate.equals("insert")){ sql = "insert into msg values(?,?,?,?,?,?,?)"; list = new ArrayList<Object>(); list.add(msgid); list.add(username); list.add(title); list.add(msgcontent); list.add(state); list.add(sendto); list.add(new Timestamp(msg_create_date.getTime())); } /* * 删除操作 */ else if(operate.equals("delete")){ sql = "delete from msg where msgid = ?"; list = new ArrayList<Object>(); msgid = (String)conditions.get("msgid"); list.add(msgid); } return executeUpdata(sql, list); } /* * 执行查询操作 * @param * elements:查询条件集合 */ public List<BBSMessage> getMessagesByPage(Map<String,Object> elements) { /* * 获取查询语句中的条件参数 */ Integer msgs_in_one_page = (Integer)elements.get("msgs_in_one_page"); Integer page_no = (Integer)elements.get("page_no"); String username = (String)elements.get("username"); String msgid = (String)elements.get("msgid"); String title = (String)elements.get("title"); String msgcontent = (String)elements.get("msgcontent"); String sendto = (String)elements.get("sendto"); Integer state = (Integer)elements.get("state"); Date msg_create_date = (Date)elements.get("msg_create_date"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); /* * 拼写sql */ String sql = null; if(page_no == null){ sql = "select * from msg where 1 = 1 "; }else{ sql = "select * from" + "(select msg.*,rownum r from msg where 1=1 and " + username + title + msgcontent + sendto + state + msg_create_date + " and rownum <= " + msgs_in_one_page*page_no + ") " + "t where t.r >" + msgs_in_one_page*(page_no - 1); } /* * 编写条件语句 */ sql += msgid!=null ? " and msgid='" + msgid + "' ":""; sql += username != null?" and username='" + username + "' ":""; sql += title!=null ? " and title='" + title + "' ":""; sql += msgcontent!=null ? " and msgcontent='" + msgcontent + "' ":""; sql += sendto!=null ? " and sendto='" + sendto + "' ":""; sql += state!=null ? " and state=" + state + " ":""; sql += msg_create_date!=null ? " and msg_create_date='" + sdf.format(msg_create_date) + "' ":""; /* * 返回结果 */ List <BBSMessage>list = null; openConnection(); list = new ArrayList<BBSMessage>(); try { ps = con.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ BBSMessage bms = new BBSMessage(); bms.setMsgid(rs.getString("msgid")); bms.setTitle(rs.getString("title")); bms.setContent(rs.getString("msgcontent")); bms.setSendto(rs.getString("sendto")); bms.setState(rs.getInt("state")); bms.setDatetime(rs.getDate("msg_create_date")); bms.setUsername(rs.getString("username")); list.add(bms); } } catch (SQLException e) { e.printStackTrace(); }finally{ closeResource(); } return list; } public int getMsgsCount(String username) { String always_true = " where 1=1 "; int count = 0; if(username == null){ username = ""; }else{ username = " and username = '" + username + "'"; } String sql = "select count(*) from msg " + always_true + username; openConnection(); try { ps = con.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) count = rs.getInt(1); } catch (SQLException e) { e.printStackTrace(); } return count; } }
3.4 BBSMessageBiz
package cn.jbit.demo.biz; import java.util.List; import java.util.Map; import cn.jbit.demo.entity.BBSMessage; public interface BBSMessageBiz { //查询短信息 public List<BBSMessage> findMessages(Map<String,Object> elements); //更新或删除短信息 public int doInsertOrUpdateMsg(String operate, Map<String,Object> elements, Map<String,Object> conditions); }
3.5 BBSMessageBizImpl
package cn.jbit.demo.biz.impl; import java.util.List; import java.util.Map; import cn.jbit.demo.biz.BBSMessageBiz; import cn.jbit.demo.dao.BBSMessageDao; import cn.jbit.demo.dao.impl.BBSMessageDaoImpl; import cn.jbit.demo.entity.BBSMessage; public class BBSMessageBizImpl implements BBSMessageBiz { private BBSMessageDao bmd = new BBSMessageDaoImpl(); //更新或删除短信息 public int doInsertOrUpdateMsg(String operate, Map<String,Object> elements, Map<String,Object> conditions) { return bmd.executeUpdate(operate, elements, conditions); } //查询短信息 public List<BBSMessage> findMessages(Map<String,Object> elements) { return bmd.getMessagesByPage(elements); } }
3.6 MsgServlet
package cn.jbit.demo.web; import java.io.IOException; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.jbit.demo.biz.BBSMessageBiz; import cn.jbit.demo.biz.impl.BBSMessageBizImpl; import cn.jbit.demo.entity.BBSMessage; public class MsgServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BBSMessageBiz bmb=new BBSMessageBizImpl(); String action = request.getParameter("action"); if(action.equals("del")){//删除短信息 String msgid = request.getParameter("msgid"); Map<String,Object> conditions = new HashMap<String,Object>(); conditions.put("msgid", msgid); int isSuccess = bmb.doInsertOrUpdateMsg("delete",new HashMap<String,Object>(),conditions); if(isSuccess > 0){ request.setAttribute("error", "删除成功!"); request.getRequestDispatcher("MsgServlet?action=list").forward(request,response); }else{ request.setAttribute("error", "删除属于非法操作,请确认当前用户权限!"); request.getRequestDispatcher("MsgServlet?action=list").forward(request,response); } }else if(action.equals("send")){//发送短信息 Random r = new Random(); String msgid = String.valueOf(r.nextInt()); String fromUser = (String)request.getSession().getAttribute("loginuser"); String toUser = request.getParameter("toUser"); String title = request.getParameter("title"); String content = request.getParameter("content"); String state = "0"; Timestamp ts = new Timestamp((new Date()).getTime()); Map <String,Object>map = new HashMap<String,Object>(); map.put("msgid", msgid); map.put("sendto", toUser); map.put("title", title); map.put("msgcontent",content); map.put("state", state); map.put("username", fromUser); map.put("msg_create_date", ts); bmb.doInsertOrUpdateMsg("insert",map,null); response.sendRedirect("MsgServlet?action=list"); }else if(action.equals("list")){//显示当前用户的收件箱 String username = (String)request.getSession().getAttribute("loginuser"); Map <String,Object>map = new HashMap<String,Object>(); map.put("sendto", username); List<BBSMessage> list = bmb.findMessages(map); request.setAttribute("msgs", list); request.getRequestDispatcher("main.jsp").forward(request,response); }else if(action.equals("read")){//读取某条短信息 Map <String,Object>elements = null; Map<String,Object> conditions = null; String msgid = request.getParameter("msgid"); String state = request.getParameter("state"); if(state.equals("0")){ elements = new HashMap<String,Object>(); conditions = new HashMap<String,Object>(); elements.put("state", "1"); conditions.put("msgid", msgid); bmb.doInsertOrUpdateMsg("update", elements, conditions); } if(conditions == null){ conditions = new HashMap<String,Object> (); conditions.put("msgid", msgid); } List<BBSMessage> list = bmb.findMessages(conditions); request.setAttribute("msg", list); request.getRequestDispatcher("readMsg.jsp").forward(request,response); } } }
四.数据表