This is a simple chat room that can't be simpler. This code contains the following functions
1. User registration.
2. User login.
3. Of course you can also chat.
DBUtil.java
The code copy is as follows:
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{
/**
* Initialize the data source. Different databases have different ways to obtain data sources. You can refer to the description of the corresponding database.
*/
MysqlDataSource mds=new MysqlDataSource();
mds.setURL("jdbc:mysql://localhost:3306/test");
mds.setUser("test");
mds.setPassword("123456");
mds.setCharacterEncoding("utf8");
dataSource=mds;
}
/**
* Get database connection
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* Close the database connection resource
* @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();
}
}
/**
* Execute database query statement
* @param sql query sql, use anonymous parameters? Indicates that the named parameters are represented by ": parameter name"
* @param params query parameters
* @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;
}
}
/**
* Perform insertion
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int insert(Object sql,Object... params) throws SQLException{
return DBUtil.update(sql, params);
}
/**
* Execute database record change statements (add, delete, modify)
* @param sql query sql, use anonymous parameters? Indicates that the named parameters are represented by ": parameter name"
* @param params query parameters
* @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;
}
}
/**
* Perform deletion
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int delete(Object sql,Object... params) throws SQLException{
return DBUtil.update(sql, params);
}
/**
* General Sql execution method
* @param sql query sql, use anonymous parameters? Indicates that the named parameters are represented by ": parameter name"
* @param params named parameters
* @return
* @throws SQLException
*/
public static Object executeSql(Object sql, Object... params) throws SQLException {
if(sql==null||"".equals(sql.toString().trim())) throw new SQLException("sql statement is empty!");
//Get sql statement
String sqlStr=sql.toString().trim();
//Processing named parameters
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) {
//Initialize query parameters
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);
}
}
}
// Process the result set
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);
// Processing returns result
if (result.size() == 0) {
return null;
} else if (result.size() == 1) {
return result.get(0);
} else {
return result;
}
} catch (SQLException e) {
throw new SQLException("Invalid sql!-->"+sql);
} finally {
DBUtil.close(conn, ps, rs);
}
}
}
WebServlet.java
The code copy is as follows:
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>();
/**
* Default access method
* @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_")){
//Inject Bean object to servlet
String beanName=name.substring("Bean_".length());
String beanClass=config.getInitParameter(name);
try {
if(beanClass==null||"".equals(beanClass.trim())) throw new Exception("Class name not configured! -->"+beanName);
Object bean = Class.forName(beanClass).newInstance();
this.getClass().getField(beanName).set(this,bean);
} catch (InstantiationException e) {
try {
throw new InstantiationException("Cannot instantiate ("+beanClass+")!");
} catch (InstantiationException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
try {
throw new ClassNotFoundException("Class not found -->"+beanClass);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
} catch (NoSuchFieldException e) {
try {
throw new NoSuchFieldException("Bean declaration field not found ("+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("Unsupported character set("+encoding+")");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String action=null;
try {
//Turn the request to the specified method according to the routing parameters
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("Method ("+action+") access denied!");
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
} catch (NoSuchMethodException e) {
try {
throw new NoSuchMethodException("Method not found("+action+")!");
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Display the specified page
* @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();
}
}
/**
* Print the specified string
* @param str
* @throws IOException
*/
protected void print(String str){
try {
response.getWriter().print(str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get the request parameter with the specified name
* @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;
}
}
/**
* Output specified parameters to the page
* @param name
* @param value
*/
protected void put(String name,Object value){
request.setAttribute(name,value);
}
}
Sql.java
The code copy is as follows:
package com.hongyuan.talk.cfg;
public enum Sql {
//Extract user information SQL statement
GET_USERINFO("select id,user_name,password from user where user_name=:userName and password=md5(:password)"),
//Save user information SQL statement
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
The code copy is as follows:
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{
/**
* Extract user information
* @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;
}
/**
* Save user information
* @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
The code copy is as follows:
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();
}
}
//Enter the login page
public void loginPage(){
show("login.jsp");
}
//Enter the registration page
public void regPage(){
show("reg.jsp");
}
//Log in
public void login() throws IOException{
String userName=this.get("userName","");
String password=this.get("password","");
if(!"".equals(userName)&&!"",.equals(password)){
//Extract user information
Map<String,Object> userInfo=talkBean.getUserInfo(userName, password);
if(userInfo!=null){
//Save user information into session
request.getSession().setAttribute("userInfo",userInfo);
response.sendRedirect("./talkService.srv?action=talkPage");
return;
}
}
show("login.jsp");
}
//register
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");
}
//Enter the chat page
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");
}
//Send a message
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);
}
}
}
Note: The following only contains the main code. See: http://pan.baidu.com/s/1dDIo085
The above is all about this article, I hope you like it.