这是一个简单的不能再简单的聊天室,本代码包含以下功能
1.用户注册。
2.用户登录。
3.当然还可以聊天。
DBUtil.java
package com.hongyuan.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class DBUtil {
private static DataSource dataSource = null;
static{
/**
* 初始化数据源,不同的数据库获取数据源的方式不同,可参考相应数据库的说明文档。
*/
MysqlDataSource mds=new MysqlDataSource();
mds.setURL("jdbc:mysql://localhost:3306/test");
mds.setUser("test");
mds.setPassword("123456");
mds.setCharacterEncoding("utf8");
dataSource=mds;
}
/**
* 获取数据库连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 关闭数据库连接资源
* @param conn
* @param s
* @param rs
* @throws SQLException
*/
public static void close(Connection conn, Statement s, ResultSet rs){
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (s != null) s.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行数据库查询语句
* @param sql 查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
* @param params 查询参数
* @return
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public static List<Map<String,Object>> select(Object sql,Object... params) throws SQLException{
Object result=DBUtil.executeSql(sql,params);
if(result==null){
return null;
}else{
return (List<Map<String,Object>>)result;
}
}
/**
* 执行插入
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int insert(Object sql,Object... params) throws SQLException{
return DBUtil.update(sql, params);
}
/**
* 执行数据库记录变更语句(增,删,改)
* @param sql 查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
* @param params 查询参数
* @return
* @throws SQLException
*/
public static int update(Object sql,Object... params) throws SQLException{
Object result=DBUtil.executeSql(sql,params);
if(result==null){
return 0;
}else{
return (Integer)result;
}
}
/**
* 执行删除
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int delete(Object sql,Object... params) throws SQLException{
return DBUtil.update(sql, params);
}
/**
* 通用Sql执行方法
* @param sql 查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
* @param params 命名参数
* @return
* @throws SQLException
*/
public static Object executeSql(Object sql, Object... params) throws SQLException {
if(sql==null||"".equals(sql.toString().trim())) throw new SQLException("sql语句为空!");
//获取sql语句
String sqlStr=sql.toString().trim();
//处理命名参数
if(params!=null&¶ms.length==1&¶ms[0] instanceof Map){
List<Object> pList=new ArrayList<Object>();
Map<String,Object> pMap=(Map<String, Object>)params[0];
Matcher pMatcher = Pattern.compile(":(\\w+)").matcher(sqlStr);
while(pMatcher.find()){
String pName=pMatcher.group(1);
pList.add(pMap.get(pName));
}
sqlStr=pMatcher.replaceAll("?");
params=pList.toArray();
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
ps = conn.prepareStatement(sqlStr);
if (null != params) {
//初始化查询参数
for(int i=0;i<params.length;i++){
Object param = params[i];
if(param!=null){
ps.setObject(i+1,param);
}else{
ps.setNull(i+1,Types.NULL);
}
}
}
//处理结果集
boolean isResultSet = ps.execute();
List<Object> result = new ArrayList<Object>();
do {
if (isResultSet) {
List<Map<String,Object>> tableData=new ArrayList<Map<String,Object>>();
ResultSet resultSet=ps.getResultSet();
while(resultSet.next()){
Map<String,Object> rowData=new HashMap<String,Object>();
for(int i=1;i<=resultSet.getMetaData().getColumnCount();i++){
rowData.put(resultSet.getMetaData().getColumnName(i),resultSet.getObject(i));
}
tableData.add(rowData);
}
result.add(tableData);
} else {
result.add(new Integer(ps.getUpdateCount()));
}
} while ((isResultSet = ps.getMoreResults()) == true || ps.getUpdateCount() != -1);
//处理返回结果
if (result.size() == 0) {
return null;
} else if (result.size() == 1) {
return result.get(0);
} else {
return result;
}
} catch (SQLException e) {
throw new SQLException("无效sql!-->"+sql);
} finally {
DBUtil.close(conn, ps, rs);
}
}
}
WebServlet.java
package com.hongyuan.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class WebServlet extends HttpServlet {
protected HttpServletRequest request=null;
protected HttpServletResponse response=null;
protected Map<String,String> cfgParams=new HashMap<String,String>();
/**
* 默认访问方法
* @throws Exception
*/
public void initPage() throws Exception{}
@Override
public final void init(ServletConfig config) throws ServletException {
@SuppressWarnings("unchecked")
Enumeration<String> names = config.getInitParameterNames();
while(names.hasMoreElements()){
String name=names.nextElement();
if(name.startsWith("Bean_")){
//为servlet注入Bean对象
String beanName=name.substring("Bean_".length());
String beanClass=config.getInitParameter(name);
try {
if(beanClass==null||"".equals(beanClass.trim())) throw new Exception("未配置类名!-->"+beanName);
Object bean = Class.forName(beanClass).newInstance();
this.getClass().getField(beanName).set(this,bean);
} catch (InstantiationException e) {
try {
throw new InstantiationException("无法实例化("+beanClass+")!");
} catch (InstantiationException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
try {
throw new ClassNotFoundException("未找到类-->"+beanClass);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
} catch (NoSuchFieldException e) {
try {
throw new NoSuchFieldException("未找到Bean声明字段("+beanName+")");
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
cfgParams.put(name,config.getInitParameter(name));
}
}
}
@Override
public final void service(HttpServletRequest request, HttpServletResponse response){
this.request=request;
this.response=response;
String encoding=null;
try {
encoding=cfgParams.get("encoding");
if(encoding==null||"".equals(encoding.trim())) encoding="utf-8";
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
} catch (UnsupportedEncodingException e2) {
try {
throw new UnsupportedEncodingException("不支持的字符集("+encoding+")");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String action=null;
try {
//根据路由参数将请求转交到指定方法执行
String routeParam=cfgParams.get("routeParam");
action=this.get((routeParam==null||"".equals(routeParam))?"action":routeParam,"initPage");
this.getClass().getMethod(action).invoke(this);
} catch (IllegalAccessException e) {
try {
throw new IllegalAccessException("方法("+action+")拒绝访问!");
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
} catch (NoSuchMethodException e) {
try {
throw new NoSuchMethodException("未找到方法("+action+")!");
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 展示指定页面
* @param page
* @throws IOException
* @throws ServletException
*/
protected void show(String page){
String pagePath=cfgParams.get("pagePath");
try {
request.getRequestDispatcher(((pagePath==null||"".equals(pagePath))?"/WEB-INF/pages/":pagePath)+page).forward(request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打印指定字符串
* @param str
* @throws IOException
*/
protected void print(String str){
try {
response.getWriter().print(str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取指定名称的请求参数
* @param name
* @param def
* @return
*/
protected String get(String name,String def){
String value=request.getParameter(name);
if(value!=null&&!"".equals(value.trim())){
return value;
}else{
return def;
}
}
/**
* 向页面输出指定参数
* @param name
* @param value
*/
protected void put(String name,Object value){
request.setAttribute(name,value);
}
}
Sql.java
package com.hongyuan.talk.cfg;
public enum Sql {
//提取用户信息SQL语句
GET_USERINFO("select id,user_name,password from user where user_name=:userName and password=md5(:password)"),
//保存用户信息SQL语句
SAVE_USER("insert into user(user_name,password) values(:userName,md5(:password))");
private final String value;
private Sql(String value){
this.value=value;
}
public String getValue(){
return this.value;
}
@Override
public String toString() {
return this.value;
}
}
TalkBean.java
package com.hongyuan.talk;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.hongyuan.core.DBUtil;
import com.hongyuan.talk.cfg.Sql;
public class TalkBean{
/**
* 提取用户信息
* @param userName
* @param password
* @return
*/
public Map<String,Object> getUserInfo(final String userName,final String password) {
try {
List<Map<String,Object>> userInfo=DBUtil.select(Sql.GET_USERINFO,new HashMap<String,Object>(){{
put("userName",userName);
put("password",password);
}});
if(userInfo!=null&&userInfo.size()==1){
return userInfo.get(0);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 保存用户信息
* @param userName
* @param password
* @return
*/
public boolean saveUser(final String userName,final String password){
try {
int count=DBUtil.insert(Sql.SAVE_USER,new HashMap<String,Object>(){{
put("userName",userName);
put("password",password);
}});
if(count==1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
TalkServlet.java
package com.hongyuan.talk;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;
import com.hongyuan.core.WebServlet;
public class TalkServlet extends WebServlet {
public TalkBean talkBean;
@Override
public void initPage(){
Object userInfo = request.getSession().getAttribute("userInfo");
if(userInfo!=null){
talkPage();
}else{
loginPage();
}
}
//进入登陆页面
public void loginPage(){
show("login.jsp");
}
//进入注册页面
public void regPage(){
show("reg.jsp");
}
//登录
public void login() throws IOException{
String userName=this.get("userName","");
String password=this.get("password","");
if(!"".equals(userName)&&!"".equals(password)){
//提取用户信息
Map<String,Object> userInfo=talkBean.getUserInfo(userName, password);
if(userInfo!=null){
//将用户信息存入session
request.getSession().setAttribute("userInfo",userInfo);
response.sendRedirect("./talkService.srv?action=talkPage");
return;
}
}
show("login.jsp");
}
//注册
public void reg() throws IOException{
String userName=this.get("userName","");
String password=this.get("password","");
String passConfirm=this.get("passConfirm","");
if(!"".equals(userName)&&!"".equals(password)&&password.equals(passConfirm)){
if(talkBean.saveUser(userName, password)){
response.sendRedirect("./talkService.srv?action=loginPage");
return;
}
}
show("reg.jsp");
}
//进入聊天页面
public void talkPage(){
Object userInfo = request.getSession().getAttribute("userInfo");
if(userInfo!=null){
Map<String,Object> info=(Map<String,Object>)userInfo;
this.put("userName",info.get("user_name"));
show("talk.jsp");
return;
}
show("login.jsp");
}
//发送消息
public void sendMsg() throws UnsupportedEncodingException{
String msg=this.get("message","");
if(!"".equals(msg)){
Event event=Event.createDataEvent("/message/world");
Object userInfo = request.getSession().getAttribute("userInfo");
if(userInfo!=null){
Map<String,Object> info=(Map<String,Object>)userInfo;
event.setField("userName",new String(info.get("user_name").toString().getBytes("utf-8"),"iso-8859-1"));
}
event.setField("message",new String(msg.getBytes("utf-8"),"iso-8859-1"));
Dispatcher.getInstance().multicast(event);
}
}
}
注:以下仅包含主要代码,完整工程代码见:http://pan.baidu.com/s/1dDIo085
以上就是本文的全部内容了,希望大家能够喜欢。