JavaWeb安全登录功能+记住密码+监听在线人数+列表展示+过滤器-爱代码爱编程
JavaWeb
数据库搭建
-- 创建数据库javaweb
CREATE DATABASE IF NOT EXISTS javaweb;
-- 创建用户表
CREATE TABLE users(
uid INT PRIMARY KEY auto_increment,
username VARCHAR(10) NOT NULL,
password VARCHAR(17) NOT NULL
);
创建javaweb项目
1.导入所需jar包
在WEB-INF的lib里导入
2.创建好需要的包和资源文件
3.书写工具类用于数据库的连接和关闭
package com.gty.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class BaseDao {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
//创建资源文件对象,用于存放四要素
Properties pro = new Properties();
//通过反射获取类加载器 的 getResourceAsStream方法以字节流的方式读取
InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
//加载
pro.load(in);
//取出四要素 赋值
driver = pro.getProperty("driver");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//连接方法
public static Connection getCon() {
Connection con = null;
try {
//连接数据库
con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
//关流方法 //以数组的形式存放
public static void close(AutoCloseable...autoCloseables) {
for (AutoCloseable autoCloseable : autoCloseables) {
if(autoCloseable!=null) {
try {
autoCloseable.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//main方法检验是否连接
public static void main(String[] args) {
System.out.println(getCon());
}
}
返回结果为:
4.JSP
登录页面
<%@page import="java.net.URLDecoder"%>
<%@ 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>
<%
String username = "";
String password = "";
String type = "";
//通过请求对象获取到cookie对象
Cookie[] ck = request.getCookies();
//判断不为空 且 有数据
if(ck!=null&&ck.length>0){
for(Cookie co:ck){ //循环遍历
if("username".equals(co.getName())){
//解码
username = URLDecoder.decode(co.getValue(), "utf-8");
}
if("password".equals(co.getName())){
password = co.getValue();
}
if("type".equals(co.getName())){
type = co.getValue();
}
}
}
%>
<span style="color:red;">${msg }</span>
<form action="userServlet?method=login" method="post">
用户名:<input type="text" name="username" value="<%=username%>"/>
密码:<input type="text" name="password" value="<%=password%>"/>
记住密码:<input type="checkbox" name="type" value="1" <%="1".equals(type)?"checked":"" %>/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
列表展示页面
<%@ 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>
<span style="color:red;">${username }</span>
登录成功! <a href="userServlet?method=logout">注销</a>
当前在线人数:<span>${allUsers.size() }</span>人
<table>
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>爱好</th>
<th>生日</th>
<th>班级</th>
</tr>
<c:forEach items="${list }" var="stu">
<tr>
<td>${stu.sid }</td>
<td>${stu.sname }</td>
<td>${stu.sex==1?"男":"女" }</td>
<td>${stu.hobby }</td>
<td>${stu.birthday }</td>
<td>${stu.clazz }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
5.书写servlet
package com.gty.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.gty.dao.IUserDao;
import com.gty.dao.UserDaoImpl;
import com.gty.entity.User;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
private IUserDao dao = new UserDaoImpl();
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
if ("login".equals(method)) {
this.login(request,response);
}else if("list".equals(method)) {
this.list(request,response);
}else if("logout".equals(method)) {
this.logout(request,response);
}
}
//注销功能
private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取session域对象
HttpSession session = request.getSession();
//删除当前用户
session.removeAttribute("username");
//销毁session
session.invalidate();
//重定向到登录页面
response.sendRedirect("login.jsp");
}
//列表展示
private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//返回学生集合
List<User> list = dao.list();
//将集合存入域对象中
request.setAttribute("list", list);
//转发到list.jsp页面
request.getRequestDispatcher("list.jsp").forward(request, response);
}
//登录功能
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String type = request.getParameter("type");
System.out.println(username);
//返回结果为true 登录成功 反之失败
boolean flag = dao.login(username,password);
if (flag) {
//存入session域对象中
request.getSession().setAttribute("username", username);
//创建cookie对象 将用户名密码存入
//加密
Cookie c1 = new Cookie("username", URLEncoder.encode(username, "utf-8"));
Cookie c2 = new Cookie("password", password);
Cookie c3 = new Cookie("type", type);
if(!"1".equals(type)) { //非选中状态
c1 = new Cookie("username", "");
c2 = new Cookie("password", "");
c3 = new Cookie("type", "");
}
//响应到浏览器
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
//重定向
response.sendRedirect("userServlet?method=list");
}else {
//存入域对象
request.setAttribute("msg", "用户名或密码有误!");
//跳转到登录界面
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
6.数据访问层
接口
package com.gty.dao;
import java.util.List;
import com.gty.entity.User;
public interface IUserDao {
boolean login(String username, String password);
List<User> list();
}
实现类
package com.gty.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.gty.entity.User;
import com.gty.util.BaseDao;
public class UserDaoImpl implements IUserDao {
@Override
public boolean login(String username, String password) {
boolean flag = false;
//书写sql语句
String sql = "select * from users where username=? and password=?";
//获取数据库连接对象
Connection con = BaseDao.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
try {
//创建预编译对象
ps = con.prepareStatement(sql);
//填充占位符
ps.setString(1, username);
ps.setString(2, password);
//执行SQL语句
rs = ps.executeQuery();
//有数据返回true 反之false
flag = rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关流
BaseDao.close(rs,ps,con);
}
return flag;
}
@Override
public List<User> list() {
List<User> list = new ArrayList<User>();
//书写sql语句
String sql = "select * from student ";
//获取数据库连接对象
Connection con = BaseDao.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
try {
//创建预编译对象
ps = con.prepareStatement(sql);
//执行SQL语句
rs = ps.executeQuery();
while (rs.next()) {
//将学生存入集合中
list.add(new User(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5), rs.getString(6)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关流
BaseDao.close(rs,ps,con);
}
return list;
}
}
7.过滤器
package com.gty.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/*")
public class UserFilter implements Filter {
public void destroy() {
System.out.println("过滤器销毁");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//设置请求编码
req.setCharacterEncoding("utf-8");
//设置响应编码
resp.setContentType("text/html;charset=utf-8");
// 获取session对象
HttpSession session = req.getSession();
// 获取session域对象中的用户名
String username = (String) session.getAttribute("username");
// 获取method 用于判定用户是否正在登录
String method = req.getParameter("method");
// 获取路径
String path = req.getServletPath();
/*
* 判断 session中用户名不为空则说明已经登录成功
* 判断method 为login 说明用户正在执行登录
* 判断路径中包含login.jsp 说明
* 用户在登录界面
* 以上三种情况放行
*/
if(username!=null || "login".equals(method) || path.contains("login.jsp") ) {
//放行
chain.doFilter(req, resp);
}else { //否则 重定向到 登录页面
resp.sendRedirect("login.jsp");
}
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("过滤器创建");
}
}
8.监听器
package com.gty.listener;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class UserListener implements ServletContextListener, HttpSessionAttributeListener {
//全局域对象
private ServletContext context = null;
//服务器的销毁
public void contextDestroyed(ServletContextEvent e) {
// TODO Auto-generated method stub
}
//session对象属性的添加
public void attributeAdded(HttpSessionBindingEvent e) {
//获取当前session中的用户名
String username = (String) e.getValue();
//获取set集合
Set<String> set = (Set<String>) context.getAttribute("allUsers");
//把用户名添加到set集合中
set.add(username);
}
//session对象属性的删除
public void attributeRemoved(HttpSessionBindingEvent e) {
//获取当前session中的用户名
String username = (String) e.getValue();
//获取set集合
Set<String> set = (Set<String>) context.getAttribute("allUsers");
//把用户名从set集合中删除
set.remove(username);
}
//session对象属性的修改
public void attributeReplaced(HttpSessionBindingEvent e) {
// TODO Auto-generated method stub
}
//服务器的创建
public void contextInitialized(ServletContextEvent e) {
//获取全局域对象
context = e.getServletContext();
//创建set集合
Set<String> set = new HashSet<String>();
//将集合存入域对象中
context.setAttribute("allUsers", set);
}
}
登录的效果展示
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/weixin_46524944/article/details/111104123