创建数据库连接
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBC {
public static final String DRIVER = "mysql.jdbc.Driver";//数据库驱动
public static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8";//数据库路径,找到对应的数据库
public static final String DBNAME = "root";
public static final String PASSWORD = "zhangsan";
public static Connection getConn() throws Exception{
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL, DBNAME, PASSWORD);
return conn;
}
}
创建实体类User
package com.User;
import java.io.Serializable;//接口的类是可序列化的
public class User implements Serializable{ //序列化功能的接口
private static final long serialVersionUID = 7554548269035753256L;
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
}
UserDao.class 使用登录方法
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.DBUtil.JDBC;
public class UserDao {
public User login(String username, String password) {
User user=null;
Connection conn = null;
PreparedStatement pstate = null;
ResultSet res = null;
try {
conn=JDBC.getConn();
String sql="select id,username from userinfo where username=? and password=?";
pstate = conn.prepareStatement(sql);
pstate.setString(1, username);
pstate.setString(2, password);
res = pstate.executeQuery();
while(res.next()){
user=new User(res.getInt(1),username,null);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
res.close();
pstate.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
}
监视器Listener
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* Application Lifecycle Listener implementation class Listener
*
*/
@WebListener
public class Listener implements ServletContextListener, ServletContextAttributeListener {
ServletContext application = null;
public Listener() {
// TODO Auto-generated constructor stub
}
public void contextInitialized(ServletContextEvent sce) {
List<String> list = new ArrayList<String>();
//用来保存所有已登录的用户
application = sce.getServletContext();
//取得application对象
application.setAttribute("allUser", list);
//将集合设置到application范围属性中去
}
public void attributeAdded(ServletContextAttributeEvent scae) {
List<String> list = (List<String>)application.getAttribute("allUser");
//假设:用户登陆成功之后,只将户名设置到session中
String userName = (String)scae.getValue();
//取得用户名
if(list.indexOf(userName) == -1){
//表示此用户之前没有登陆
list.add(userName);
application.setAttribute("allUser", list);
}
}
public void attributeRemoved(ServletContextAttributeEvent scae) {
List<String> list = (List<String>)application.getAttribute("allUser");
list.remove((String)scae.getValue());
application.setAttribute("allUser", list);
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("服务器关闭");
}
public void attributeReplaced(ServletContextAttributeEvent scae) {
// TODO Auto-generated method stub
}
}
servlet
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.User.UserDao;
import com.User.User;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/Login")
public class UserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getContextPath();
response.setContentType("text/html; charset=utf-8");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
ServletContext application = this.getServletContext();//取得application对象
List<String> list = (List<String>) application.getAttribute("allUser");
if(list.indexOf(username) == -1){
User pojo = new UserDao().login(username, password);
if(null != pojo){
HttpSession session = request.getSession(true);//取得session对象
session.setAttribute("userName", username);
}
}
response.sendRedirect(path+"/index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
xml配置
<listener>
<listener-class>com.Listener.Listener</listener-class>
</listener>
登录页login,jsp
<%@page contentType="text/html; charset=utf-8"%>
<%@page import="java.util.*" %>
<%
String path = request.getContextPath();
%>
<html>
<body>
<form action="<%=path %>/Login" method="get">
账号:
<input type="text" name="username" />
<br />
密码:
<input type="password" name="password" />
<br />
<input type="submit" value="提交" />
</form>
</body>
</html>
主页面 index.jsp 统计登录人数
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title></title>
</head>
<body>
<ul>
<%
System.out.println(application.getAttribute("allUser"));
if(null != application.getAttribute("allUser")){
List<String> list = (List<String>)application.getAttribute("allUser");
%>
<h2>在线人数:<%=list.size() %></h2>
<%
for(String s:list){
%>
<a>姓名:</a><%=s %><a>---->此时在线</a><br>
<%
}
}
%>
</ul>
<hr/>
<a href="<%=path %>/logout.jsp">注销</a>
</body>
</html>
注销页
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>logout</title>
</head>
<body>
<%
session.removeAttribute("username");
session.invalidate();
response.sendRedirect("login.jsp");
%>
</body>
</html>