欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用java基于pushlet和bootstrap实现的简单聊天室

程序员文章站 2024-03-03 20:39:58
这是一个简单的不能再简单的聊天室,本代码包含以下功能 1.用户注册。 2.用户登录。 3.当然还可以聊天。 dbutil.java 复制代码 代码如下: pac...

这是一个简单的不能再简单的聊天室,本代码包含以下功能

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&&params.length==1&&params[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);
        }
    }
}

使用java基于pushlet和bootstrap实现的简单聊天室

使用java基于pushlet和bootstrap实现的简单聊天室

使用java基于pushlet和bootstrap实现的简单聊天室

使用java基于pushlet和bootstrap实现的简单聊天室

注:以下仅包含主要代码,完整工程代码见:http://pan.baidu.com/s/1ddio085

以上就是本文的全部内容了,希望大家能够喜欢。