Skip to content

Instantly share code, notes, and snippets.

@benbai123
Created April 9, 2013 15:02
Show Gist options
  • Save benbai123/5346429 to your computer and use it in GitHub Desktop.
Save benbai123/5346429 to your computer and use it in GitHub Desktop.
files for JSPChat servlet 2.4 version
package test.jsp.simplechat;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
public class Chat extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 113880057049845876L;
// message map, mapping user UID with a message list
private static Map<String, List<String>> _chat = new HashMap<String, List<String>>();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String action = req.getParameter("action");
// send message
if ("send".equals(action)) {
// get param with UTF-8 enconding
String msg = new String(req.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
String uid = (String)req.getSession().getAttribute("UID");
for (String s : _chat.keySet()) {
if (!s.equals(uid)) {
synchronized (_chat.get(s)) {
// put message to any other user's msg list
_chat.get(s).add(uid+" said: "+msg);
}
}
}
} else if ("get".equals(action)) { // get message
String uid = (String)req.getSession().getAttribute("UID");
if (uid == null)
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
List<String> l = _chat.get(uid);
synchronized (l) {
if (l.size() > 0) {
// for UTF-8 chars
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
JSONArray jsna = new JSONArray();
// add all msg to json array and clear list
while (l.size() > 0)
jsna.add(l.remove(0));
out.println(jsna);
out.close();
}
}
}
}
public static Map<String, List<String>> getChatMap () {
return _chat;
}
}
<%@ page isErrorPage="true" language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored ="false" %>
<!-- Redirect to index.jsp if no UID -->
<c:if test="${UID == null}">
<c:redirect url="index.jsp" />
</c:if>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"/>
<title>Login page</title>
<link href="css/chat.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/chat.js"></script>
</head>
<body>
<form action="logout.go" method="post">
<div>This is chat page</div>
<div>Type message then press ENTER key to send message</div>
<div>Click logout to return the login page</div>
<div>Your name: <span id="uid">${UID}</span></div>
<div id="content" class="content"></div>
<div>
<!-- listen to keyup to send message if enter pressed -->
<textarea class="msg-input" onkeyup="chat.dokeyup(event);">input text here</textarea>
</div>
<input type="submit" value="logout" />
</form>
</body>
</html>
<%@ page isErrorPage="true" language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored ="false" %>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"/>
<title>Login page</title>
</head>
<body>
<form action="login.go" method="post">
<span>Type a name then press login to enter chat room</span>
<input id="userId" type="text" value="Your ID" name="uid" />
<input type="submit" value="login"/>
</form>
</body>
</html>
package test.jsp.simplechat;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8873939883201271898L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String uid = new String(req.getParameter("uid").getBytes("ISO-8859-1"), "UTF-8");
String newUid = uid;
int i = 2;
Map<String, List<String>> chat = Chat.getChatMap();
synchronized (chat) {
// prevent uid conflict
if ("you".equalsIgnoreCase(newUid))
newUid = uid + i++;
while (chat.containsKey(newUid))
newUid = uid + i++;
uid = newUid;
chat.put(uid, new ArrayList<String>());
}
req.getSession().setAttribute("UID", uid);
resp.sendRedirect("chat.jsp");
}
}
package test.jsp.simplechat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// practice: invalidate session
public class Logout extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6175876557872938832L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getSession().invalidate();
resp.sendRedirect("index.jsp");
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>test.jsp.simplechat.Login</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.go</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ChatServlet</servlet-name>
<servlet-class>test.jsp.simplechat.Chat</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ChatServlet</servlet-name>
<url-pattern>/chat.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>test.jsp.simplechat.Logout</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/logout.go</url-pattern>
</servlet-mapping>
</web-app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment