这几天学习了一些基础的jquery,还有一些springmvc,于是顺手写了个基于浏览器的聊天室,并没有用到很多的springmvc里面的方便的特性
以下是用到的文件
login.jsp 简单的登录窗口
chat.jsp 聊天窗口
java文件
RootConfig.java
WebAppInitializer.java
WebConfig.java
这三个文件代替了web.xml
AjaxController,很简单的controller
接下来开始给代码
我用maven配置的项目,这是pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>chatroom</groupId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring-framework.version>4.1.7.RELEASE</spring-framework.version>
<java-version>1.8</java-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Unit Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<artifactId>chatroom</artifactId>
</project>
里面有些东西没有用到,可以删掉
------------------------------------------------------分割线------------------------------------------------------------
接下来是spring的配置,
WebAppInitializer.java
package config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
从WebConfig和RootConfig加载配置,通过getServletMappings设置映射
RootConfig.java
package config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RootConfig {
}
这个只是个placeholder而已
接下来是WebConfig.java
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="web")
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/chat/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
配置了ViewResolver
这个controller没用到springmvc提供的很多功能,大家不要学我,可以自己改进改进
package web;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping({"/"})
public class AjaxController {
private List<String> messages = new ArrayList<String>();
private List<String> usernames = new ArrayList<String>();
// 这里基本上没用到spring点的什么功能,大家千万不要学我
@RequestMapping("/login")
public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
// 检测username
if (username == null || usernames.contains(username)) {
return "login";
}
HttpSession session = request.getSession();
session.setAttribute("username", username);
usernames.add(username);
// 初始化第一次的信息
request.setAttribute("messages", messages);
System.out.println(username + " logged on");
return "chat";
}
@RequestMapping("/chat")
public void chat(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获得用户发的信息和用户名
String username = request.getParameter("username");
String content = request.getParameter("content");
// 设置返回的文件类型和编码
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
Writer writer = response.getWriter();
if (!content.equals("")) {
Calendar rightNow = Calendar.getInstance();
String time = rightNow.getTime().toString();
// json格式发给前端
String message = "{" + "\"username\"" + ":\"" + username + "\","
+ "\"time\":\"" + time + "\","
+ "\"content\":\"" + content+"\"}";
messages.add(message);
}
writer.write(messages.toString());
writer.close();
}
}
--------------------------------------------分割线-------------------------------------------
接下来是login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>login</title>
</head>
<body>
<form id="form" action="login" method="post">
<input type="text" name="username" id="username" value="" />
<input type="submit" value="登录" />
</form>
</body>
</html>
这里只用了一个表格,post到服务器,然后AjaxController会把username储存到ArrayList中
chat.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>chatroom</title>
<script src="/chatroom/resources/jquery.js"></script>
<style>
#chatroom {
width:100%;
height:100%;
}
</style>
</head>
<body>
<textarea name="chatroom" id="chatroom" cols="50" rows="20" readonly="true"></textarea>
<form id="form">
<input type="text" name="content" id="content" />
<input type="text" name="" id="" style="display:none" />
<input type="hidden" name="username" id="username" value="${username}" />
<input type="button" value="发送" />
</form>
<script>
$(document).ready(function () {
updateChat();
scrollDownTextArea();
})
function scrollDownTextArea () {
var scrollHeight = $('#chatroom')[0].scrollHeight;
$('#chatroom').scrollTop(scrollHeight);
}
// 使用ajax发送内容到服务器
function getHistory(url,sendData) {
var success = function (data) {
var res = eval(data);
var str = '';
for (var i = 0; i < res.length; i++) {
str += res[i].username+' ('+res[i].time+') \n';
str += res[i].content+'\n';
};
// 保存原来的scrolltop
// 这里我想实现滚动条自动滑倒最底部
// 如果用户在看上面的信息,则不滑动
var oldScrollTop = $('#chatroom')[0].scrollTop;
$('#chatroom').text(str);
var clientHeight = $('#chatroom')[0].clientHeight;
var scrollHeight = $('#chatroom')[0].scrollHeight;
var scrollTop = $('#chatroom')[0].scrollTop;
if (clientHeight + scrollTop >= scrollHeight) {
$('#chatroom').scrollTop(scrollHeight + 100);
} else {
$('#chatroom').scrollTop(oldScrollTop);
}
};
$.ajax({
url:url,
type:'post',
data:sendData,
success:success
});
}
// 实现enter自动发送信息
$('#content').keydown(function (e) {
if (e.keyCode == 13) {
if ($('#content').val() !== "") {
scrollDownTextArea();
$('input[type=button]').trigger('click');
}
}
})
$('input[type=button]').click(function () {
var url = "chat";
var sendData = $('#form').serialize();
getHistory(url,sendData);
$('#content').val('');
})
function updateChat () {
var sendData = {
"username":$('input[type=hidden]').val(),
"content":""
}
getHistory("chat",sendData);
};
// 每5秒自动获取数据
setInterval(updateChat,5000);
</script>
</body>
</html>
这里用的是定时获取数据,应该还有更好的实现方法,而且我的服务器是会每次把所有的消息记录发送出去,高并发的话会很糟糕,需要改进