應用java基於pushlet和bootstrap完成的簡略聊天室。本站提示廣大學習愛好者:(應用java基於pushlet和bootstrap完成的簡略聊天室)文章只能為提供參考,不一定能成為您想要的結果。以下是應用java基於pushlet和bootstrap完成的簡略聊天室正文
這是一個簡略的不克不及再簡略的聊天室,本代碼包括以下功效
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.百度.com/s/1dDIo085
以上就是本文的全體內容了,願望年夜家可以或許愛好。