五、在线列表展示

项目 专栏收录该内容
7 篇文章 0 订阅

一、在线列展示项目

项目源码下载,提取码:xfnu

	1.该项目实现用户登录在线列表展示功能。
	2.用户只能单点登录

1.1 创建数据库的SQL

// 会员表
CREATE TABLE `member` (
  `id` varchar(200) NOT NULL,
  `name` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


1.2 代码

1.2.1 dao层

BaseDao.java
public class BaseDao<T> {
	
	private Connection conn;
	private PreparedStatement pst;
	private ResultSet rs;
	
	/**
	 * 更新
	 * 
	 * @param sql
	 * @param params
	 */
	public  void update(String sql,Object ... params) {
		try {
			 conn = JdbcUtil.getCon();
			PreparedStatement pst = conn.prepareStatement(sql);
			ParameterMetaData pst_matsData = pst.getParameterMetaData();
			
			int count = pst_matsData.getParameterCount();
			for(int i=0;i<count;i++) {
				pst.setObject(i+1, params[i]);
			}
			
			pst.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(conn, pst);
		}
	}
	
	/**
	 * 查询
	 * 
	 * @param <T>
	 * @param sql
	 * @param clazz
	 * @param params
	 * @return
	 */
	public <T>  List<T>  query(String sql , Class<T> clazz , Object ... params) {
		
		List<T> result=new ArrayList<T>();
		
		try {
			conn = JdbcUtil.getCon();
			PreparedStatement pst = conn.prepareStatement(sql);
			ParameterMetaData pst_matsData = pst.getParameterMetaData();
			
			int count = pst_matsData.getParameterCount();
			for(int i=0;i<count;i++) {
				pst.setObject(i+1, params[i]);
			}
			
			 rs = pst.executeQuery();
			
			ResultSetMetaData rs_metadata = rs.getMetaData();
			int columnCount = rs_metadata.getColumnCount();
			while(rs.next()) {
				T t=clazz.newInstance();
				for(int i=0;i<columnCount;i++) {
					String columnName = rs_metadata.getColumnName(i+1);
					Object value = rs.getObject(columnName);
					BeanUtils.setProperty(t, columnName, value);
				}
				result.add(t);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(conn, pst, rs);
		}
		return result;
	}
}

MemberDao .java

public class MemberDao extends BaseDao<MemberEntity>{
	
	public MemberEntity findByName(String name) {
		String sql="select * from member where name=?";
		List<MemberEntity> result = super.query(sql, MemberEntity.class,name);
		if(result==null||result.size()==0) {
			return null;
		}
		return result.get(0);
	}
}


1.2.2 实体层

MemberEntity .java
public class MemberEntity {
	
	private String name;
	private String password;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null) {
			return false;
		}
		
		MemberEntity in=(MemberEntity) obj;
		
		if(this.getName().equals(in.getName())) {
			return true;
		}
		
		return false;
	}
	
}
OnlineEntity .java
public class OnlineEntity {
	
	private HttpSession httpSession;
	private MemberEntity entity;
	private Date createDate;
	
	
	public MemberEntity getEntity() {
		return entity;
	}
	public void setEntity(MemberEntity entity) {
		this.entity = entity;
	}
	public HttpSession getHttpSession() {
		return httpSession;
	}
	public void setHttpSession(HttpSession httpSession) {
		this.httpSession = httpSession;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	
	
}


1.2.3 filter

LoginFilter .java
public class LoginFilter  implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		
		String requestURI = req.getRequestURI();
		
		//登录jsp、登录处理器放行
		if(requestURI.startsWith("/nowlist/admin")||requestURI.startsWith("/nowlist/login.jsp")) {
			chain.doFilter(req, resp);
			return;
		}
		
		//其余拦截
		HttpSession session = req.getSession(false);
		if(session==null) {
			req.setAttribute("msg", "请登录");
			req.getRequestDispatcher("./login.jsp").forward(req, resp);
			return;
		}
		
		MemberEntity admin = (MemberEntity) session.getAttribute("admin");
		if(admin==null) {
			req.setAttribute("msg", "请登录");
			req.getRequestDispatcher("./login.jsp").forward(req, resp);
			return;
		}
		
		chain.doFilter(req, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}


MyHttpSessionListener.java
public class MyHttpSessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("...sessionXIAOHUI");
		ServletContext ac = arg0.getSession().getServletContext();
		MemberEntity admin=(MemberEntity) arg0.getSession().getAttribute("admin");
		
		//session销毁时,从在线列表中取出
		LinkedHashMap<String, OnlineEntity> map=(LinkedHashMap<String, OnlineEntity>) ac.getAttribute("online");
		map.remove(admin.getName());
	}

}

MyServletContextListener .java
public class MyServletContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		
		//在线列表
		sc.setAttribute("online", new LinkedHashMap<String, OnlineEntity>());

		
	}

}

1.2.4 service

LoginService .java
public class LoginService {
	
	private MemberDao memberDao=new MemberDao();
	
	public MemberEntity login(MemberEntity member) {
		if(member.getName()==null||"".equals(member.getName())) {
			throw new RuntimeException("名称为空");
		}
		if(member.getPassword()==null||"".equals(member.getPassword())) {
			throw new RuntimeException("密码为空");
		}
		
		MemberEntity item = memberDao.findByName(member.getName());
		if(item==null) {
			throw new RuntimeException("没有该用户");
		}
		if(!item.getPassword().equals(member.getPassword())) {
			throw new RuntimeException("密码错误");
		}
		
		return item;
	}
}

1.2.6 util

WebUtils .java
public class WebUtils {
	
	public static  <T> T  convert2Bean(HttpServletRequest req,Class<T> clazz) {
		
		try {
			T t=clazz.newInstance();
			Map<String, String[]> mpa = req.getParameterMap();
			BeanUtils.populate(t, mpa);
			
			return t;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
}


JdbcUtil .java
/**
 * 使用JDBC1.0版本(驱动注册方式)
 * @author BGS
 *
 */
public class JdbcUtil {
	
	private static Connection  conn;
	
	static {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static Connection getCon() {
	
		try {
			String url="jdbc:mysql://localhost:3306/day11";
			String user="root";
			String password="root";
			return  DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void close(Connection conn,Statement st,ResultSet rs) {
		
		try {
			if(rs!=null) {
				rs.close();
			}
			
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(Connection conn,Statement st) {
		
		try {
	
			
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}


1.2.6 controller

AdminController .java
/**
 * 登录业务逻辑
 * @author BGS
 *
 */
public class AdminController  extends HttpServlet{
	
	private LoginService loginService=new LoginService();
	
	@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			this.doPost(req, resp);
		}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String method = req.getParameter("method");
		
		//登录
		if("login".equals(method)) {
			doLogin(req,resp);
		}
		
		//注销
		if("out".equals(method)) {
			doOut(req,resp);
		}
	}
	
	/**
	 * 	登录
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		MemberEntity admin = WebUtils.convert2Bean(req, MemberEntity.class);
		
		try {
			
			//登录
			admin = loginService.login(admin);
			HttpSession session = req.getSession();
			session.setAttribute("admin", admin);
			//设置seesion有效时间是3秒
			session.setMaxInactiveInterval(3000);
			
			
			//session信息
			OnlineEntity  ol=new OnlineEntity();
			ol.setEntity(admin);
			ol.setCreateDate(new Date());
			ol.setHttpSession(session);
			
			//登记到上线列表中
			LinkedHashMap<String, OnlineEntity> map=(LinkedHashMap<String, OnlineEntity>) req.getServletContext().getAttribute("online");
			
			//如果重复登录,则自动取去除上一次信息
			if(map.containsKey(admin.getName())) {
				try {
					OnlineEntity old = map.get(admin.getName());
					session = old.getHttpSession();
					session.invalidate();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			map.put(admin.getName(), ol);

			System.out.println(map);
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("msg", e.getMessage());
			req.getRequestDispatcher("./login.jsp").forward(req, resp);
			return;
		}
		
		resp.sendRedirect("./list.jsp");
		
	}

	private void doOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String uri="";
		HttpSession session = req.getSession(false);
		if(session==null) {
			uri="./login.jsp";
		}else {
			MemberEntity admin=(MemberEntity) session.getAttribute("admin");
			if(admin==null) {
				uri="./login.jsp";
			}else {
				uri="./login.jsp";
				session.invalidate();
			}
		}
		
		
		System.out.println(".....");
		resp.sendRedirect(uri);
	}

	
	
	

}

1.2.7 配置

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 
  <listener>
  	<listener-class>org.jsoft.filter.MyServletContextListener</listener-class>
  </listener>
  
  <listener>
  		<listener-class>org.jsoft.filter.MyHttpSessionListener</listener-class>
  </listener>
  
  <filter>
  		<filter-name>loginFilter</filter-name>
  		<filter-class>org.jsoft.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
  		<filter-name>loginFilter</filter-name>
  		<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.jsoft.controller.AdminController</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/admin</url-pattern>
  </servlet-mapping>
 
 <error-page>
 		<error-code>405</error-code>
 		<location>/login.jsp</location>
 </error-page>
 
</web-app>

1.2.8 前端

login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


	${msg}
	<form action="./admin?method=login" method="post">
			<table>
				<tr>
						<td>用户名:</td>
						<td><input type="text" name="name"></td>
				</tr>
				<tr>
						<td>密码:</td>
						<td><input type="password" name="password"></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="提交"></td>
				</tr>				
			</table>
	</form>

</body>
</html>
list.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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="./header.jsp"></jsp:include>
		<table border="1" style="margin:100px auto; width:400px;" cellspacing="1" cellpadding="0">
				<c:if test="${not empty online}">
					<c:forEach items="${online }" var="item" varStatus="indexObj">
						<tr>
							<td>${indexObj.count }</td>
							<td>${item.key}	</td>
							<td>${item.value.entity.name}	</td>
							<td>${item.value.createDate}	</td>
					
						</tr>
					
					</c:forEach>
				
				</c:if>
				
		</table>

</body>
</html>
header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎${admin.name} !  <a href="${pageContext.request.contextPath }/admin?method=out">注销</a>

</body>
</html>

1.4 实现效果

登录界面

在这里插入图片描述

在线列表展示界面

在这里插入图片描述

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值