maven+spring+springmvc+mybatis+ajax 框架下实现简单的聊天室
2014-12-21 15:05
936 查看
首先非常感谢SSM框架——详细整合教程这篇博文对框架整合的详细说明和Spring注解学习手札对spring注解的详细解释
搭建完之后刚好看到一本不错的书《锋利的jQuery》,结合最后的例子使用ajax实现了这个简单的聊天室。
controller表示控制层负责同页面数据的传输和页面的跳转,service表示服务层,dao和mapping负责持久层,pojo表示数据传输对象。resources下有jdbc.properties,log4j.properties,spring-mvc.xml,spring-mybatis.xml。另外还有一些日志文件,静态文件,JSP文件。完整目录结构如下:
关于jar包的GroupId,ArtifactId,Version问题,可以在search.maven.org这里进行查找,至于jar包的依赖问题,maven可以直接帮你做到
[html] view
plaincopy
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wzy</groupId>
<artifactId>carsmanage</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>carsmanage Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本号 -->
<spring.version>3.2.4.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.9</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>6.0.32</version>
<scope>provided</scope>
</dependency>
<!-- spring核心包 -->
<!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 阿里巴巴数据源包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.2</version>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>springmvc</finalName>
</build>
</project>
[html] view
plaincopy
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=admin
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最大等待时长
maxWait=60000
[html] view
plaincopy
#定义log输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
建立spring-mybatis.xml配置文件,将spring和mybatis整合在一起
[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.chatroom" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/chatroom/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.chatroom.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 开启事务注解驱动 -->
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
从这里开始因为要涉及一些编码,同业务联系在一起,以免开始写代码时再推到重来。对于这个简单的聊天室,用户登录是通过数据库访问,聊天信息和在线人员信息放在application中。表数据结构只需要用户名,密码等一些简单的数据即可
可以mybatis generator自动生成实体类,dao接口,mybatis映射文件 使用方法参考这里
service实现类:UserService.java
[java] view
plaincopy
@Service
public class UserService implements IUserService {
@Resource
IUserDao userDao;
@Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
}
测试类:TestMybatis.java
[java] view
plaincopy
@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMyBatis {
private static Logger logger = Logger.getLogger(TestMyBatis.class);
@Resource
private IUserService userService = null;
@Test
public void test1() {
User user = userService.getUserById(1);
logger.info(JSON.toJSONString(user));
}
}
[java] view
plaincopy
[com.test.TestMyBatis] - {"age":22,"id":1,"password":"wzy","userName":"wzy"}
至此spring和mybatis已经整合成功下面开始同springmvc的整合
[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.chatroom.controller" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<!-- 多动作控制器必须有此配置 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 引入静态文件 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
整合已经完毕下边开始编码
[css] view
plaincopy
body
{
font-size:11px
}
h3
{
margin:0px
}
.divShow
{
border:solid 1px #ccc;
height:300px;
padding:5px;
font-size:12px;
overflow-y:scroll
}
#divMain
{
border:soild 5px #ccc
}
#divMain .divTop
{
padding:10px
}
#divMain .divTop .divL
{
float:left;
width:78%
}
#divMain .divTop .divR
{
float:right;
width:20%
}
#divMain .divBot
{
clear:both;
padding:10px
}
#divMain .divBot .pb
{
padding-bottom:3px
}
#divMain .divBot .pl
{
padding-left:12px
}
#divMain .divBot .pt
{
padding-top:3px;
color:#555
}
.clsTip
{
position:absolute;
width:160px;
text-align:center;
font-size:13px;
border:soild 1px #cc3300;
margin-top:5px;
padding:2px;
margin-bottom:5px;
backgroudn-color:#ffe0a3;
display:none
}
.btn
{
border:soild 1px #666;
padding:2px;
width:135px;
height:54px;
font-size:16px;
filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff,
EndColorStr=#ECE9D8)
}
.txt
{
border:#666 1px solid;
padding:2px;
margin-right:3px
}
[javascript] view
plaincopy
$(function(){
//绑定全局ajaxStart事件
// $("#divMsg").ajaxStart(function(){
// $(this).show()
//})
//绑定全局ajaxStop事件
// $("#divMsg").ajaxStop(function(){
// $(this).hide()
// })
initFace();//初始化表情
getMessageList();//取得聊天信息
getOnlineList();//取得在线人员
/**
* 点击发送按钮
*/
$("#btnSend").bind("click",function(){
var $content = $("#txtContent")
if($content.val()!=""){
sendContent($content.val())
}else{
alert("发送内容不能为空")
$content.foucus()
return false
}
})
/**
* 点击表情图标
*/
$("table tr td img").bind("click",function(){
var strContent = $("#txtContent").val()+"<:"+this.id+":>"
$("#txtContent").val(strContent)
})
})
/**
* 发送聊天内容函数
* @param content 聊天内容
*/
function sendContent(content){
$.ajax({
type:'get',
data:{"content":content},
url:'sentContent.html',
dataType:'text',
success:function(data){
if(data=="success"){
getMessageList();
$("#txtContent").val("")
}else{
alert("发送失败")
return false
}
}
})
}
/**
* 取得聊天内容数据
*/
function getMessageList(){
$.ajax({
type:"get",
url:"getMassageList.html",
dataType:"text",
success:function(data){
$("#divContent").html(data)
}
})
autoUpdContent() //定时获取聊天信息
}
/**
* 获取在线用户
*/
function getOnlineList(){
$.ajax({
type:"get",
url:"getOnlineList.html",
dataType:"text",
success:function(data){
$("#divOnLine").html(data)
}
})
}
/**
* 设置表情图标函数
*/
function initFace(){
var strHTML = "";
for(var i=1;i<=10;i++){
strHTML += "<img src='/chatroom/static/pic/"+i+".gif' id='"+i+"'/>"
}
$("#divFace").html(strHTML)
}
/**
* 定时返回聊天内容和在线人数
*/
function autoUpdContent(){
setTimeout(getMessageList,5000)
setTimeout(getOnlineList,6000)
}
[javascript] view
plaincopy
$(document).ready(function(){
//全局ajax开始事件
$("#msg").ajaxStart(function(){
$(this).html("正在登陆聊天室中···")
})
$("#btnLogin").bind("click",function(){
var $name = $("#txtName")
var $password = $("#txtPassword")
if($name.val()==""){
alert("用户名不能为空")
$name.focus()
return false
}else if($password.val()==""){
alert("密码不能为空")
$password.focus()
return false
}else{
userLogin($name.val(),$password.val())
}
})
})
//ajax登陆处理
function userLogin(name,password){
$.ajax({
type:"GET",
url:"login.html",
data:{"name":name,"password":password},
dataType:'text',
success:function(data){
if(data == "success"){
window.location.href="/chatroom/user/toChatMain.html";
}else{
$("#msg").html("用户名或密码错误,请重新登录")
return false
}
}
})
}
这个随意,名称只要是1、2、3···
[html] view
plaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>大家的聊天室</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/chatMain.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/chatMain.css" />
</head>
<body>
<div id="divMain">
<div class="divTop">
<div class="divL">
<h3>大家的聊天室</h3>
<div class="divShow" id="divContent"></div>
</div>
<div class="divR">
<h3>当前在线人员</h3>
<div class="divShow" id="divOnLine"></div>
</div>
</div>
<div class="divBot">
<table cellpadding="0" cellspacing="0">
<tr><td colspan="2" id="divFace" class="pb"></td></tr>
<tr>
<td>
<textarea rows="3" cols="64" id="txtContent"></textarea>
</td>
<td class="p1">
<input type="button" id="btnSend" value="发送" class="btn"> </input>
</td>
</tr>
<tr><td colspan="2" class="pt">发送内容不能为空 </td></tr>
</table>
</div>
<span id="divMsg" class="clsTip">正在发送数据。。。</span>
</div>
</body>
</html>
[html] view
plaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆</title>
<style type="text/css">
@CHARSET "UTF-8";
/* 全局控制 */
* {
margin:0;
padding:0;
}
body {
font-size: 12px;
font-family: "宋体";
text-align: center;
}
a {
color: #e3e3e3;
text-decoration: none;
padding: 2px;
}
a:hover {
color: #e3e3e3;
background-color: #606870;
}
ul {
list-style: none;
margin: 10px auto;
}
li {
margin: 3px 1px;
line-height: 24px;
height: 24px;
}
li:hover {
background-color: #eee;
}
button {
line-height: 24px;
height: 26px;
}
fieldset {
height: 120px;
width: 250px;
padding: 5px;
}
label {
width: 80px;
float: left;
text-align: right;
}
input {
width: 150px;
}
</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/login.js"></script>
</head>
<body>
<fieldset><legend>登录</legend>
<ul>
<li><span>用户名:</span><input type="text" id="txtName"></input></li>
<li><span>密码:</span><input type="password" id="txtPassword"></input></li>
<li>
<button id="btnLogin">登录</button>
<button id="btnReset" type="reset">重置</button>
</li>
</ul>
<span id="msg"></span>
</fieldset>
</body>
</html>
[html] view
plaincopy
<script type="text/javascript">
window.location.href="/chatroom/user/toLogin.html";
</script>
[java] view
plaincopy
package com.chatroom.controller;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.chatroom.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 95163763702302820L;
@Resource
private IUserService userService;
//获取session
HttpSession session ;
ServletContext application;
/**
* 控制跳转到登录界面
* @param request
* @param model
* @return
*/
@RequestMapping(value="/toLogin.html")
public String toLogin(HttpServletRequest request,Model model){
return "login";
}
/**
* 执行登录操作
* @param request
* @param model
* @param out
*/
@RequestMapping(value="/login.html",method = RequestMethod.GET)
public void login(HttpServletRequest request,Model model,PrintWriter out){
String name = request.getParameter("name");
String password = request.getParameter("password");
String s = userService.login(name, password);
session = request.getSession();
if(s=="success"){
session.setAttribute("name", name); // 保存当前登录的用户名
//
application = request.getSession().getServletContext();
if(application.getAttribute("onLine")==null){
application.setAttribute("onLine", "");
}
String onLine = application.getAttribute("onLine").toString();
onLine += name+"<br/>";
application.setAttribute("onLine", onLine);
}
//写入返回结果
out.write(s);
}
/**
* 控制跳转到聊天主界面
* @param request
* @param model
* @return
*/
@RequestMapping("/toChatMain.html")
public String toChatMain(HttpServletRequest request,Model model){
return "chatMain";
}
/**
* 前端发送聊天内容
* @param request
* @param model
*/
@RequestMapping("sentContent.html")
public void sentContent(HttpServletRequest request,Model model,PrintWriter out){
//存储信息的全局变量
application = request.getSession().getServletContext();
session = request.getSession();
if(application.getAttribute("message")==null){
application.setAttribute("message", "");
}
//获取application中存储的聊天内容
String sourceMessage = application.getAttribute("message").toString();
//获取前端发送的聊天内容
String content = request.getParameter("content");
content = content.replace("<:", "<img src='/chatroom/static/pic/");
content = content.replace(":>", ".gif'/>");
// 获取session中的登陆者
String name = session.getAttribute("name").toString();
sourceMessage += this.getTime()+ "<font color='blue'><strong> "+name+"</strong></font> :"+content+"</br>";
application.setAttribute("message", sourceMessage);
//写入返回结果
out.write("success");
}
/**
* 前端定时获取聊天信息
* @param request
* @param model
* @param out
*/
@RequestMapping("/getMassageList.html")
public void getMassageList(HttpServletRequest request,Model model,PrintWriter out){
application = request.getSession().getServletContext();
if(application.getAttribute("message")==null){
application.setAttribute("message", "");
}
//获取application中存储的聊天内容
String sourceMessage = application.getAttribute("message").toString();
String str = null;
try {
str = new String (sourceMessage.getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
out.write(str);
}
/**
* 前端定时获取在线人员
* @param request
* @param model
* @param out
*/
@RequestMapping("getOnlineList.html")
public void getOnlineList(HttpServletRequest request,Model model,PrintWriter out){
application = request.getSession().getServletContext();
if(application.getAttribute("onLine")==null){
application.setAttribute("onLine", "");
}
//获取application中存储在 线人员
String sourceOnline = application.getAttribute("onLine").toString();
out.write(sourceOnline);
}
/**
* 自定义日期格式
* @return
*/
private String getTime(){
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return df.format(date);
}
}
[java] view
plaincopy
package com.chatroom.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.chatroom.dao.IUserDao;
import com.chatroom.pojo.User;
import com.chatroom.service.IUserService;
@Service
public class UserService implements IUserService {
@Resource
IUserDao userDao;
@Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public void insertUser(List<User> users) {
// TODO Auto-generated method stub
}
@Override
public String login(String name, String password) {
User record = new User();
record.setUserName(name);
record.setPassword(password);
User user = userDao.selectUserForLogin(record);
if(user==null){
return "fail";
}else{
return "success";
}
}
}
[java] view
plaincopy
package com.chatroom.service;
import java.util.List;
import com.chatroom.pojo.User;
public interface IUserService {
public User getUserById(int userId);
public void insertUser(List<User> users);
/**
* 登陆处理
* @param name
* @param password
* @return
*/
public String login(String name,String password);
}
只多了一行用于登陆的代码
[java] view
plaincopy
User selectUserForLogin(User record);
只多了一个用于select的语句,id和IUserDao的方法名一致
[html] view
plaincopy
<select id="selectUserForLogin" resultMap="BaseResultMap" parameterType="com.chatroom.pojo.User" >
select
<include refid="Base_Column_List" />
from user_t
where user_name = #{userName,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
至此所有代码已经结束,下面让我们看一下运行结果
基本功能已经完成就是这样,再次感谢文章开头那篇博文对框架整合的指导。
源码下载地址:http://download.csdn.net/detail/a582127421/8064265
搭建完之后刚好看到一本不错的书《锋利的jQuery》,结合最后的例子使用ajax实现了这个简单的聊天室。
1.项目目录创建
controller表示控制层负责同页面数据的传输和页面的跳转,service表示服务层,dao和mapping负责持久层,pojo表示数据传输对象。resources下有jdbc.properties,log4j.properties,spring-mvc.xml,spring-mybatis.xml。另外还有一些日志文件,静态文件,JSP文件。完整目录结构如下:
2.配置pom文件,引入jar包
关于jar包的GroupId,ArtifactId,Version问题,可以在search.maven.org这里进行查找,至于jar包的依赖问题,maven可以直接帮你做到[html] view
plaincopy
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wzy</groupId>
<artifactId>carsmanage</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>carsmanage Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本号 -->
<spring.version>3.2.4.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.9</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>6.0.32</version>
<scope>provided</scope>
</dependency>
<!-- spring核心包 -->
<!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 阿里巴巴数据源包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.2</version>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>springmvc</finalName>
</build>
</project>
3.jdbc配置文件
[html] viewplaincopy
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=admin
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最大等待时长
maxWait=60000
4.log4j配置文件
[html] viewplaincopy
#定义log输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
5.spring mybatis配置文件
建立spring-mybatis.xml配置文件,将spring和mybatis整合在一起[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.chatroom" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/chatroom/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.chatroom.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 开启事务注解驱动 -->
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
6.使用junit测试spring和mybatis整合结果
从这里开始因为要涉及一些编码,同业务联系在一起,以免开始写代码时再推到重来。对于这个简单的聊天室,用户登录是通过数据库访问,聊天信息和在线人员信息放在application中。表数据结构只需要用户名,密码等一些简单的数据即可
6.1 建表
6.2代码
可以mybatis generator自动生成实体类,dao接口,mybatis映射文件 使用方法参考这里service实现类:UserService.java
[java] view
plaincopy
@Service
public class UserService implements IUserService {
@Resource
IUserDao userDao;
@Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
}
测试类:TestMybatis.java
[java] view
plaincopy
@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMyBatis {
private static Logger logger = Logger.getLogger(TestMyBatis.class);
@Resource
private IUserService userService = null;
@Test
public void test1() {
User user = userService.getUserById(1);
logger.info(JSON.toJSONString(user));
}
}
6.3测试结果:
[java] viewplaincopy
[com.test.TestMyBatis] - {"age":22,"id":1,"password":"wzy","userName":"wzy"}
至此spring和mybatis已经整合成功下面开始同springmvc的整合
7.建立spring-mvc.xml配置文件
[html] viewplaincopy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.chatroom.controller" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<!-- 多动作控制器必须有此配置 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
8 配置web.xml文件
[html] viewplaincopy
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 引入静态文件 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
9 编码
整合已经完毕下边开始编码
9.1前端
chatMain.css
[css] viewplaincopy
body
{
font-size:11px
}
h3
{
margin:0px
}
.divShow
{
border:solid 1px #ccc;
height:300px;
padding:5px;
font-size:12px;
overflow-y:scroll
}
#divMain
{
border:soild 5px #ccc
}
#divMain .divTop
{
padding:10px
}
#divMain .divTop .divL
{
float:left;
width:78%
}
#divMain .divTop .divR
{
float:right;
width:20%
}
#divMain .divBot
{
clear:both;
padding:10px
}
#divMain .divBot .pb
{
padding-bottom:3px
}
#divMain .divBot .pl
{
padding-left:12px
}
#divMain .divBot .pt
{
padding-top:3px;
color:#555
}
.clsTip
{
position:absolute;
width:160px;
text-align:center;
font-size:13px;
border:soild 1px #cc3300;
margin-top:5px;
padding:2px;
margin-bottom:5px;
backgroudn-color:#ffe0a3;
display:none
}
.btn
{
border:soild 1px #666;
padding:2px;
width:135px;
height:54px;
font-size:16px;
filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff,
EndColorStr=#ECE9D8)
}
.txt
{
border:#666 1px solid;
padding:2px;
margin-right:3px
}
chatMain.js
[javascript] viewplaincopy
$(function(){
//绑定全局ajaxStart事件
// $("#divMsg").ajaxStart(function(){
// $(this).show()
//})
//绑定全局ajaxStop事件
// $("#divMsg").ajaxStop(function(){
// $(this).hide()
// })
initFace();//初始化表情
getMessageList();//取得聊天信息
getOnlineList();//取得在线人员
/**
* 点击发送按钮
*/
$("#btnSend").bind("click",function(){
var $content = $("#txtContent")
if($content.val()!=""){
sendContent($content.val())
}else{
alert("发送内容不能为空")
$content.foucus()
return false
}
})
/**
* 点击表情图标
*/
$("table tr td img").bind("click",function(){
var strContent = $("#txtContent").val()+"<:"+this.id+":>"
$("#txtContent").val(strContent)
})
})
/**
* 发送聊天内容函数
* @param content 聊天内容
*/
function sendContent(content){
$.ajax({
type:'get',
data:{"content":content},
url:'sentContent.html',
dataType:'text',
success:function(data){
if(data=="success"){
getMessageList();
$("#txtContent").val("")
}else{
alert("发送失败")
return false
}
}
})
}
/**
* 取得聊天内容数据
*/
function getMessageList(){
$.ajax({
type:"get",
url:"getMassageList.html",
dataType:"text",
success:function(data){
$("#divContent").html(data)
}
})
autoUpdContent() //定时获取聊天信息
}
/**
* 获取在线用户
*/
function getOnlineList(){
$.ajax({
type:"get",
url:"getOnlineList.html",
dataType:"text",
success:function(data){
$("#divOnLine").html(data)
}
})
}
/**
* 设置表情图标函数
*/
function initFace(){
var strHTML = "";
for(var i=1;i<=10;i++){
strHTML += "<img src='/chatroom/static/pic/"+i+".gif' id='"+i+"'/>"
}
$("#divFace").html(strHTML)
}
/**
* 定时返回聊天内容和在线人数
*/
function autoUpdContent(){
setTimeout(getMessageList,5000)
setTimeout(getOnlineList,6000)
}
login.js
[javascript] viewplaincopy
$(document).ready(function(){
//全局ajax开始事件
$("#msg").ajaxStart(function(){
$(this).html("正在登陆聊天室中···")
})
$("#btnLogin").bind("click",function(){
var $name = $("#txtName")
var $password = $("#txtPassword")
if($name.val()==""){
alert("用户名不能为空")
$name.focus()
return false
}else if($password.val()==""){
alert("密码不能为空")
$password.focus()
return false
}else{
userLogin($name.val(),$password.val())
}
})
})
//ajax登陆处理
function userLogin(name,password){
$.ajax({
type:"GET",
url:"login.html",
data:{"name":name,"password":password},
dataType:'text',
success:function(data){
if(data == "success"){
window.location.href="/chatroom/user/toChatMain.html";
}else{
$("#msg").html("用户名或密码错误,请重新登录")
return false
}
}
})
}
pic
这个随意,名称只要是1、2、3···
chatMain.jsp
[html] viewplaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>大家的聊天室</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/chatMain.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/chatMain.css" />
</head>
<body>
<div id="divMain">
<div class="divTop">
<div class="divL">
<h3>大家的聊天室</h3>
<div class="divShow" id="divContent"></div>
</div>
<div class="divR">
<h3>当前在线人员</h3>
<div class="divShow" id="divOnLine"></div>
</div>
</div>
<div class="divBot">
<table cellpadding="0" cellspacing="0">
<tr><td colspan="2" id="divFace" class="pb"></td></tr>
<tr>
<td>
<textarea rows="3" cols="64" id="txtContent"></textarea>
</td>
<td class="p1">
<input type="button" id="btnSend" value="发送" class="btn"> </input>
</td>
</tr>
<tr><td colspan="2" class="pt">发送内容不能为空 </td></tr>
</table>
</div>
<span id="divMsg" class="clsTip">正在发送数据。。。</span>
</div>
</body>
</html>
login.jsp
[html] viewplaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆</title>
<style type="text/css">
@CHARSET "UTF-8";
/* 全局控制 */
* {
margin:0;
padding:0;
}
body {
font-size: 12px;
font-family: "宋体";
text-align: center;
}
a {
color: #e3e3e3;
text-decoration: none;
padding: 2px;
}
a:hover {
color: #e3e3e3;
background-color: #606870;
}
ul {
list-style: none;
margin: 10px auto;
}
li {
margin: 3px 1px;
line-height: 24px;
height: 24px;
}
li:hover {
background-color: #eee;
}
button {
line-height: 24px;
height: 26px;
}
fieldset {
height: 120px;
width: 250px;
padding: 5px;
}
label {
width: 80px;
float: left;
text-align: right;
}
input {
width: 150px;
}
</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/login.js"></script>
</head>
<body>
<fieldset><legend>登录</legend>
<ul>
<li><span>用户名:</span><input type="text" id="txtName"></input></li>
<li><span>密码:</span><input type="password" id="txtPassword"></input></li>
<li>
<button id="btnLogin">登录</button>
<button id="btnReset" type="reset">重置</button>
</li>
</ul>
<span id="msg"></span>
</fieldset>
</body>
</html>
index.jsp
[html] viewplaincopy
<script type="text/javascript">
window.location.href="/chatroom/user/toLogin.html";
</script>
9.2 后台
UserController.java
[java] viewplaincopy
package com.chatroom.controller;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.chatroom.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 95163763702302820L;
@Resource
private IUserService userService;
//获取session
HttpSession session ;
ServletContext application;
/**
* 控制跳转到登录界面
* @param request
* @param model
* @return
*/
@RequestMapping(value="/toLogin.html")
public String toLogin(HttpServletRequest request,Model model){
return "login";
}
/**
* 执行登录操作
* @param request
* @param model
* @param out
*/
@RequestMapping(value="/login.html",method = RequestMethod.GET)
public void login(HttpServletRequest request,Model model,PrintWriter out){
String name = request.getParameter("name");
String password = request.getParameter("password");
String s = userService.login(name, password);
session = request.getSession();
if(s=="success"){
session.setAttribute("name", name); // 保存当前登录的用户名
//
application = request.getSession().getServletContext();
if(application.getAttribute("onLine")==null){
application.setAttribute("onLine", "");
}
String onLine = application.getAttribute("onLine").toString();
onLine += name+"<br/>";
application.setAttribute("onLine", onLine);
}
//写入返回结果
out.write(s);
}
/**
* 控制跳转到聊天主界面
* @param request
* @param model
* @return
*/
@RequestMapping("/toChatMain.html")
public String toChatMain(HttpServletRequest request,Model model){
return "chatMain";
}
/**
* 前端发送聊天内容
* @param request
* @param model
*/
@RequestMapping("sentContent.html")
public void sentContent(HttpServletRequest request,Model model,PrintWriter out){
//存储信息的全局变量
application = request.getSession().getServletContext();
session = request.getSession();
if(application.getAttribute("message")==null){
application.setAttribute("message", "");
}
//获取application中存储的聊天内容
String sourceMessage = application.getAttribute("message").toString();
//获取前端发送的聊天内容
String content = request.getParameter("content");
content = content.replace("<:", "<img src='/chatroom/static/pic/");
content = content.replace(":>", ".gif'/>");
// 获取session中的登陆者
String name = session.getAttribute("name").toString();
sourceMessage += this.getTime()+ "<font color='blue'><strong> "+name+"</strong></font> :"+content+"</br>";
application.setAttribute("message", sourceMessage);
//写入返回结果
out.write("success");
}
/**
* 前端定时获取聊天信息
* @param request
* @param model
* @param out
*/
@RequestMapping("/getMassageList.html")
public void getMassageList(HttpServletRequest request,Model model,PrintWriter out){
application = request.getSession().getServletContext();
if(application.getAttribute("message")==null){
application.setAttribute("message", "");
}
//获取application中存储的聊天内容
String sourceMessage = application.getAttribute("message").toString();
String str = null;
try {
str = new String (sourceMessage.getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
out.write(str);
}
/**
* 前端定时获取在线人员
* @param request
* @param model
* @param out
*/
@RequestMapping("getOnlineList.html")
public void getOnlineList(HttpServletRequest request,Model model,PrintWriter out){
application = request.getSession().getServletContext();
if(application.getAttribute("onLine")==null){
application.setAttribute("onLine", "");
}
//获取application中存储在 线人员
String sourceOnline = application.getAttribute("onLine").toString();
out.write(sourceOnline);
}
/**
* 自定义日期格式
* @return
*/
private String getTime(){
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return df.format(date);
}
}
UserService.java
[java] viewplaincopy
package com.chatroom.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.chatroom.dao.IUserDao;
import com.chatroom.pojo.User;
import com.chatroom.service.IUserService;
@Service
public class UserService implements IUserService {
@Resource
IUserDao userDao;
@Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public void insertUser(List<User> users) {
// TODO Auto-generated method stub
}
@Override
public String login(String name, String password) {
User record = new User();
record.setUserName(name);
record.setPassword(password);
User user = userDao.selectUserForLogin(record);
if(user==null){
return "fail";
}else{
return "success";
}
}
}
IUserService.java
[java] viewplaincopy
package com.chatroom.service;
import java.util.List;
import com.chatroom.pojo.User;
public interface IUserService {
public User getUserById(int userId);
public void insertUser(List<User> users);
/**
* 登陆处理
* @param name
* @param password
* @return
*/
public String login(String name,String password);
}
IUserDao.java
只多了一行用于登陆的代码[java] view
plaincopy
User selectUserForLogin(User record);
UserMapper.xml
只多了一个用于select的语句,id和IUserDao的方法名一致[html] view
plaincopy
<select id="selectUserForLogin" resultMap="BaseResultMap" parameterType="com.chatroom.pojo.User" >
select
<include refid="Base_Column_List" />
from user_t
where user_name = #{userName,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
至此所有代码已经结束,下面让我们看一下运行结果
基本功能已经完成就是这样,再次感谢文章开头那篇博文对框架整合的指导。
源码下载地址:http://download.csdn.net/detail/a582127421/8064265
相关文章推荐
- maven+spring+springmvc+mybatis+ajax 框架下实现简单的聊天室
- maven+spring+springmvc+mybatis+ajax 框架下实现简单的聊天室
- 整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架
- Dubbo+spring+springmvc+mybatis+Maven+Jetty+Mysql+Ajax多框架融合学习网址收藏
- 用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能
- 用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能
- 用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能(二)
- Maven + Spring MVC+Mybatis + MySQL +AngularJS + Bootstrap 实现简单微博应用(三)前后台交互
- springmvc+spring+mybatis+maven+mysql项目(二)Springmvc + ajax 实现javaweb验证码的制作及进行异步验证
- Dubbo+spring+springmvc+mybatis+Maven+Jetty+Mysql+Ajax多框架融合学习网址收藏
- 使用maven,实现ssm(spring+springmvc+mybatis)三大框架的整合DEMO
- J2EE项目系列(四)--SSM框架构建积分系统和基本商品检索系统(Spring+SpringMVC+MyBatis)(3)Ajax使用详解(级联列表)以及企业级报表Excel导入导出实现
- 用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能(二)
- 用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能
- 手把手搭建最简单的SSM框架Maven,idea(spring+springmvc+mybatis)附源代码
- Maven + Spring MVC+Mybatis + MySQL +AngularJS + Bootstrap 实现简单微博应用(二)访问数据库
- 整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架
- [置顶] java实现微信支付宝等多个支付平台合一的二维码支付(maven+spring springmvc mybatis框架)
- Maven + Spring MVC+Mybatis + MySQL +AngularJS + Bootstrap 实现简单微博应用(一)环境搭建
- 基于Maven的SpringMVC+Mybatis+mysql的框架搭建