【新手级】JavaWeb用户管理系统—使用JSP, Servlet, JDBC, MySQL

 前言

这是我学完JavaWeb后做的期末大作业,是一个用户管理系统,包括登录注册功能,对于列表的增、删、改、查功能,由于我也是参考的网上大佬的的代码,之后进行了一些修改,完成的这个新手项目,于是我也把这个项目源码放在这里供大家参考,同时也对这次学习做一个记录。

首先感谢大佬们的文章帮助,我把所参考的文章原文链接放在下面:

【Java学习】JSP + Servlet + JDBC + Mysql 实现增删改查_Tellsea的博客-CSDN博客_java jsp 实现增删改查

使用JSP+Servlet+MySQL实现登录注册功能【详细代码】_邵奈一的博客-CSDN博客

 正题

项目运行截图

 

 

 

 

 

 

1.环境信息:

Eclipse IDE for Enterprise Java Developers Version: 2020-12 (4.18.0)

MySQL workbench: 8.0.29

Tomcat: 9.0

2.所使用到的导入包下载地址以及线上仓库引用:

JDBC jar包:在Eclipse中使用JDBC连接MySQL(mysql-connector-java-8.0.28版本)_鸭巴子嘎嘎嘎的博客-CSDN博客_eclipse配置jdbc连接mysql

JSTL jar包以及引用语句:JSP 标准标签库(JSTL) | 菜鸟教程

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <!-- 引用JSTL核心标签 -->

jQuery引用以及下载网站:https://www.jq22.com/jquery-info122#google_vignette

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Bootstrap v3 引用以及网站:Bootstrap v3 中文文档 · Bootstrap 是最受欢迎的 HTML、CSS 和 JavaScript 框架,用于开发响应式布局、移动设备优先的 WEB 项目。 | Bootstrap 中文网

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

3.项目目录结构:

 

4.新建一个web项目

 5.新建jsp文件

 6.导入要使用的包

这里以mysql连接包举例,其他的类似,目录结构中其他两个包都是JSTL所用到的,我就导入了这三个包,都在上面的目录文件结构中列出了。

 

7.数据库表结构

 

 8.源代码

(1)首页以及接口

index1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>用户管理系统</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<div class="container">
	<nav class="navbar navbar-default">
	  <div class="container-fluid">
	    <!-- Brand and toggle get grouped for better mobile display -->
	    <div class="navbar-header">
	      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
	        <span class="sr-only">Toggle navigation</span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	      </button>
	      <a class="navbar-brand" href="#">用户管理系统</a>
	    </div>
	
	    <!-- Collect the nav links, forms, and other content for toggling -->
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      <ul class="nav navbar-nav">
	        <li class="active"><a href="<%=path%>/index1">首页 <span class="sr-only">(current)</span></a></li>
	        <li><a href="https://blog.csdn.net/weixin_54464792?type=blog">联系我们</a></li>
	      </ul>
	      <form class="navbar-form navbar-left">
	        <div class="form-group">
	          <input type="text" class="form-control" placeholder="Search">
	        </div>
	        <button type="submit" class="btn btn-default">搜索</button>
	      </form>
	      <ul class="nav navbar-nav navbar-right">
	        <li class="dropdown">
	          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户 <span class="caret"></span></a>
	          <ul class="dropdown-menu">
	            <li><a href="#">个人中心</a></li>
	            <li><a href="#">设置</a></li>
	            <li><a href="#">帮助</a></li>
	            <li role="separator" class="divider"></li>
	            <li><a href="<%=path%>/login">注销</a></li>
	          </ul>
	        </li>
	      </ul>
	    </div><!-- /.navbar-collapse -->
	  </div><!-- /.container-fluid -->
	</nav>
	
	<div class="row">
	
	  <div class="col-md-3">
	  	<div class="list-group">
		  <a class="list-group-item active" href="<%=path%>/index1">首页</a>      
		  <a class="list-group-item" href="<%=path%>/userInfoSave">添加用户</a>
		  <a class="list-group-item" href="<%=path%>/userInfoList">用户列表</a>
		</div>
	  </div>
	  
	  <div class="col-md-9">
	  	<div class="jumbotron">
		  <h1>欢迎!</h1>
		  <p style="margin-top:20px">这是Tang的用户管理系统,使用了 JSP, JavaServlet, JDBC, MySQL, jQuery以及Bootstrap框架,基于MVC模式开发。</p>
		  <p style="margin-top:20px"><a class="btn btn-primary btn-lg" href="#" role="button">更多</a></p>
		</div>
	  </div>
	  
	</div>
	
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

IndexServlet.java

package Tang.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 首页控制器
 * @author TZQ
 *
 */
@WebServlet("/index1")
@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		req.getRequestDispatcher("/Index1.jsp").forward(req,resp);
		
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		//req.getRequestDispatcher(req.getContextPath()+"index.jsp");
		this.doGet(req, resp);
	}

}

MysqlUtils.java

package Tang.utils;

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import Tang.service.LoginInfoService;
import Tang.service.UserInfoService;
import Tang.service.impl.LoginInfoServiceImpl;
import Tang.service.impl.UserInfoServiceImpl;
import Tang.entity.LoginInfo;
import Tang.entity.UserInfo;

/**
 * MySQL连接工具类
 * @author TZQ
 *
 */

public class MysqlUtils {
	private static String url="jdbc:mysql://localhost:3306/javaweb";  //连接地址
	private static String userName="root";  //连接用户名
	private static String password="tzq";  //连接密码
	private static Connection conn=null;  //连接驱动
	
	public static Connection getConnection() {
		if(conn==null) {
			try {
              //com.mysql.jdbc.Driver是 mysql-connector-java 5版本中的
              //com.mysql.cj.jdbc.Driver是 mysql-connector-java 6版本及以上中的
				Class.forName("com.mysql.cj.jdbc.Driver"); 
				conn=DriverManager.getConnection(url,userName,password);
			} catch(ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	
	//测试
	public static void main(String[] args) {
		System.out.println(getConnection());
		LoginInfoService loginInfoService=new LoginInfoServiceImpl();
		LoginInfo user=new LoginInfo();
		user.setAccount("1");
		user.setPassword("2");
		loginInfoService.register(user);
		
		String account="1";
		String password="2";
		LoginInfo user1=loginInfoService.login(account, password);
		System.out.println(user1.toString());
		
		
		
//		UserInfoService userInfoService=new UserInfoServiceImpl();
//		UserInfo entity1=new UserInfo();
//		entity1.setName("芳华");
//		entity1.setPassword("rr36988");
//		entity1.setEmail("fh3236@123.com");
//		entity1.setAddress("天津");
//		userInfoService.saveUserInfo(entity1);
//		
//		
//		List<UserInfo> list=userInfoService.userInfoList();
//		list.forEach(entity ->{
//			System.out.println(entity);
//		});
		
	}
}

UserInfo.java

package Tang.entity;


/**
 * 用户实体类,也可以叫做bean
 * @author TZQ
 *
 */

public class UserInfo {
	private int id;
	private String name;
	private String password;
	private String email;
	private String address;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	
	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;
	}
	
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	
	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", address="
				+ address + "]";
	}

}

UserInfoService.java

package Tang.service;

import java.util.List;

import Tang.entity.UserInfo;

/**
 * 用户接口
 * @author TZQ
 *
 */

public interface UserInfoService {
	//接口只写方法特征,而不实现,方法记得加括号否则会成为变量并报错"not have been initialized",未被初始化
	
	//查询所有用户
	List<UserInfo> userInfoList();

	//新增用户
	void saveUserInfo(UserInfo entity);
	
	//根据id查询用户
	UserInfo getUserInfoById(int id);

	//根据id更新用户
	void updateUserInfoById(UserInfo entity);
	
	//根据id删除用户
    void deleteUserInfoById(int id);

}

UserInfoServiceImpl.java

package Tang.service.impl;

import Tang.service.UserInfoService;

import java.util.List;

import Tang.dao.UserInfoDao;
import Tang.entity.UserInfo;

/**
 * 用户接口实现类
 * @author TZQ
 *
 */

public class UserInfoServiceImpl implements UserInfoService {
	
	public List<UserInfo> userInfoList(){
		return UserInfoDao.userInfoList();
	}

	@Override
	public void saveUserInfo(UserInfo entity) {
		UserInfoDao.saveUserInfo(entity);  //调用dao层的相关方法
		
	}

	@Override
	public UserInfo getUserInfoById(int id) {
		return UserInfoDao.getUserInfoById(id);
		
	}

	@Override
	public void updateUserInfoById(UserInfo entity) {
		UserInfoDao.updateUserInfoById(entity);
		
	}

	@Override
	public void deleteUserInfoById(int id) {
		UserInfoDao.deleteUserInfoById(id);
		
	}

}

UserInfoDao.java

package Tang.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 Tang.entity.UserInfo;
import Tang.utils.MysqlUtils;

/**
 * 用户数据交互层
 * @author TZQ
 *
 */

public class UserInfoDao {

	public static List<UserInfo> userInfoList() {
		List<UserInfo> list=new ArrayList<>();
		Connection conn=MysqlUtils.getConnection();
		String sql="select * from user_info;";
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			ResultSet resultSet=pStatement.executeQuery();
			UserInfo entity=null;
			while(resultSet.next()) {
				entity=new UserInfo();
				entity.setId(resultSet.getInt("id"));
				entity.setName(resultSet.getString("name"));
				entity.setPassword(resultSet.getString("password"));
				entity.setEmail(resultSet.getString("email"));
				entity.setAddress(resultSet.getString("address"));
				list.add(entity);
			}
			resultSet.close(); //避免造成性能浪费
			pStatement.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return list;
	}

	public static void saveUserInfo(UserInfo entity) {
		//添加用户的sql语句
		String sql="insert into user_info(name,password,email,address) values(?,?,?,?);";
		Connection conn=MysqlUtils.getConnection();  //得到数据库连接
		
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);  //使用预处理方法执行sql语句
			//从实体类实例中得到相关数据并设置到sql语句的相关位置
			pStatement.setString(1, entity.getName());  
			pStatement.setString(2, entity.getPassword());
			pStatement.setString(3, entity.getEmail());
			pStatement.setString(4, entity.getAddress());
			int count=pStatement.executeUpdate();  //执行sql语句
			pStatement.close();  //执行完成后执行该close方法,避免资源浪费
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	public static UserInfo getUserInfoById(int id) {
		String sql="select U.id, U.name, U.password, U.email, U.address from user_info U where U.id= "+id+";";
		Connection conn=MysqlUtils.getConnection();
		UserInfo entity=null;
		
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			ResultSet resultSet=pStatement.executeQuery();
			while(resultSet.next()) {
				entity=new UserInfo();
				entity.setId(resultSet.getInt("id"));
				entity.setName(resultSet.getString("name"));
				entity.setPassword(resultSet.getString("password"));
				entity.setEmail(resultSet.getString("email"));
				entity.setAddress(resultSet.getString("address"));
			}
			resultSet.close(); //避免造成性能浪费
			pStatement.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return entity;
		
	}

	public static void updateUserInfoById(UserInfo entity) {
		String sql="update user_info set name=?,password=?,email=?,address=? where id=?;";
		Connection conn=MysqlUtils.getConnection();
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			pStatement.setString(1, entity.getName());
			pStatement.setString(2, entity.getPassword());
			pStatement.setString(3, entity.getEmail());
			pStatement.setString(4, entity.getAddress());
			pStatement.setInt(5, entity.getId());
			pStatement.executeUpdate();
			pStatement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
	}

	public static void deleteUserInfoById(int id) {
		String sql="delete from user_info where id="+id+";";
		Connection conn=MysqlUtils.getConnection();
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			pStatement.executeUpdate();
			pStatement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}

(2)查看列表

UserInfoListServlet.java

package Tang.servlet;

import java.io.IOException;
import java.util.List;

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 Tang.entity.UserInfo;
import Tang.service.UserInfoService;
import Tang.service.impl.UserInfoServiceImpl;

/**
 * 用户列表控制器
 * @author TZQ
 * MVC(视图层View,服务层Service,持久层Dao)
 *控制层(Servlet)->接口层(Service)->接口层实现类(ServiceImpL)->数据交互层(Dao)
 */
@WebServlet("/userInfoList")
@SuppressWarnings("serial")
public class UserInfoListServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		this.doPost(req, resp);
		
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		//查询出所有用户
		UserInfoService userInfoService=new UserInfoServiceImpl();
		List<UserInfo> list=userInfoService.userInfoList();
		req.setAttribute("userInfoList", list);
		req.getRequestDispatcher("/user_info_list.jsp").forward(req, resp);
		
		
	}
	

}

user_info_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <!-- 引用JSTL核心标签 -->
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<div class="container">
	<nav class="navbar navbar-default">
	  <div class="container-fluid">
	    <!-- Brand and toggle get grouped for better mobile display -->
	    <div class="navbar-header">
	      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
	        <span class="sr-only">Toggle navigation</span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	      </button>
	      <a class="navbar-brand" href="#">用户管理系统</a>
	    </div>
	
	    <!-- Collect the nav links, forms, and other content for toggling -->
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      <ul class="nav navbar-nav">
	        <li class="active"><a href="<%=path%>/index1">首页 <span class="sr-only">(current)</span></a></li>
	        <li><a href="https://blog.csdn.net/weixin_54464792?type=blog">联系我们</a></li>
	      </ul>
	      <form class="navbar-form navbar-left">
	        <div class="form-group">
	          <input type="text" class="form-control" placeholder="Search">
	        </div>
	        <button type="submit" class="btn btn-default">搜索</button>
	      </form>
	      <ul class="nav navbar-nav navbar-right">
	        <li class="dropdown">
	          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户 <span class="caret"></span></a>
	          <ul class="dropdown-menu">
	            <li><a href="#">个人中心</a></li>
	            <li><a href="#">设置</a></li>
	            <li><a href="#">帮助</a></li>
	            <li role="separator" class="divider"></li>
	            <li><a href="<%=path%>/login">注销</a></li>
	          </ul>
	        </li>
	      </ul>
	    </div><!-- /.navbar-collapse -->
	  </div><!-- /.container-fluid -->
	</nav>
	
	<div class="row">
	
	  <div class="col-md-3">
	  	<div class="list-group">
		  <a class="list-group-item" href="<%=path%>/index1">首页</a>      
		  <a class="list-group-item" href="<%=path%>/userInfoSave">添加用户</a>
		  <a class="list-group-item active" href="<%=path%>/userInfoList">用户列表</a>
		</div>
	  </div>
	  
	  <div class="col-md-9">
	  	<table class="table table-hover">
		  	<thead>
		  	 <tr>
		  	  <th>序号</th>
		  	  <th>姓名</th>
		  	  <th>密码</th>
		  	  <th>邮箱</th>
		  	  <th>地址</th>
		  	 </tr>
		  	</thead>
		  	
		  	<tbody>
		  	<!-- 使用JSTL -->
			  	<c:forEach items="${userInfoList}" var="entity" varStatus="status">      
				  	 <tr>
				  	  <td>${status.index+1}</td>
				  	  <td>${entity.name }</td>
				  	  <td>${entity.password }</td>
				  	  <td>${entity.email }</td>
				  	  <td>${entity.address }</td>
				  	  <td>
				  	    <a href="<%=path%>/userInfoUpdate?id=${entity.id}">修改</a>
				  	    <a style="margin-left: 15px ; color:red " href="<%=path%>/userInfoDelete?id=${entity.id}">删除</a> 	    
				  	  </td>
				  	 </tr>
			  	 </c:forEach>
		  	</tbody>
	          
	        </table>
		
	  </div>
	  
	</div>
	
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

(3)添加用户

UserInfoSaveServlet.java

package Tang.servlet;

import java.io.IOException;
import java.util.List;

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 Tang.entity.UserInfo;
import Tang.service.UserInfoService;
import Tang.service.impl.UserInfoServiceImpl;

/**
 *新增用户控制器
 * @author TZQ
 *
 */
@WebServlet("/userInfoSave")
@SuppressWarnings("serial")
public class UserInfoSaveServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		req.getRequestDispatcher("/user_info_save.jsp").forward(req, resp);
		
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		//新增用户
		//req.getParameter方法从前端页面的name标签中拿到用户输入的数据,getBytes("ISO-8859-1"),"UTF-8"解决乱码问题
		String name=new String(req.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");  
		String password=req.getParameter("password");
		String email=req.getParameter("email");
		String address=new String(req.getParameter("address").getBytes("ISO-8859-1"),"UTF-8");
		
		//实例化一个用户对象,使用set方法将输入的数据设置给这个对象
		UserInfo entity=new UserInfo();  
		entity.setName(name);
		entity.setPassword(password);
		entity.setEmail(email);
		entity.setAddress(address);
		
		UserInfoService userInfoService=new UserInfoServiceImpl();
		userInfoService.saveUserInfo(entity);  //调用接口中的方法
		req.getRequestDispatcher("/userInfoList").forward(req, resp);  //转发跳转
		//resp.sendRedirect("/userInfoList");  //转发重定向
		
		
	}

}

user_info_save.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<div class="container">
	<nav class="navbar navbar-default">
	  <div class="container-fluid">
	    <!-- Brand and toggle get grouped for better mobile display -->
	    <div class="navbar-header">
	      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
	        <span class="sr-only">Toggle navigation</span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	      </button>
	      <a class="navbar-brand" href="#">用户管理系统</a>
	    </div>
	
	    <!-- Collect the nav links, forms, and other content for toggling -->
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      <ul class="nav navbar-nav">
	        <li class="active"><a href="<%=path%>/index1">首页 <span class="sr-only">(current)</span></a></li>
	        <li><a href="https://blog.csdn.net/weixin_54464792?type=blog">联系我们</a></li>
	      </ul>
	      <form class="navbar-form navbar-left">
	        <div class="form-group">
	          <input type="text" class="form-control" placeholder="Search">
	        </div>
	        <button type="submit" class="btn btn-default">搜索</button>
	      </form>
	      <ul class="nav navbar-nav navbar-right">
	        <li class="dropdown">
	          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户 <span class="caret"></span></a>
	          <ul class="dropdown-menu">
	            <li><a href="#">个人中心</a></li>
	            <li><a href="#">设置</a></li>
	            <li><a href="#">帮助</a></li>
	            <li role="separator" class="divider"></li>
	            <li><a href="<%=path%>/login">注销</a></li>
	          </ul>
	        </li>
	      </ul>
	    </div><!-- /.navbar-collapse -->
	  </div><!-- /.container-fluid -->
	</nav>
	
	<div class="row">
	
	  <div class="col-md-3">
	  	<div class="list-group">
		  <a class="list-group-item" href="<%=path%>/index1">首页</a>      
		  <a class="list-group-item active" href="<%=path%>/userInfoSave">添加用户</a>
		  <a class="list-group-item" href="<%=path%>/userInfoList">用户列表</a>
		</div>
	  </div>
	  
	  <div class="col-md-9">
	  	<form action="<%=path%>/userInfoSave" method="post">
		  <div class="form-group">
		    <label>姓名</label>
		    <input type="text" name="name" class="form-control" placeholder="Please input your name here">
		  </div>
		  
		  <div class="form-group">
		    <label>密码</label>
		    <input type="password" name="password" class="form-control" placeholder="Please input your password here">
		  </div>
		  
		  <div class="form-group">
		    <label>邮箱</label>
		    <input type="email" name="email" class="form-control" placeholder="Please input your E-mail here">
		  </div>
		  
		  <div class="form-group">
		    <label>地址</label>
		    <input type="text" name="address" class="form-control" placeholder="Please input your address here">
		  </div>
		  
		  <button type="submit" class="btn btn-primary">保存(Submit)</button>
		  <button type="reset" class="btn btn-warning">重置(Reset)</button>
		</form>
	  </div>
	  
	</div>
	
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

(4)修改用户

UserInfoUpdateServlet.java

package Tang.servlet;

import java.io.IOException;
import java.util.List;

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 Tang.entity.UserInfo;
import Tang.service.UserInfoService;
import Tang.service.impl.UserInfoServiceImpl;

/**
 * 修改用户控制器
 * @author TZQ
 *
 */
@WebServlet("/userInfoUpdate")
@SuppressWarnings("serial")
public class UserInfoUpdateServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		//查询需要编辑的信息
		UserInfoService userInfoService=new UserInfoServiceImpl();
		UserInfo entity=userInfoService.getUserInfoById(Integer.parseInt(req.getParameter("id")));
		req.setAttribute("entity", entity);
		req.getRequestDispatcher("/user_info_update.jsp").forward(req, resp);
		
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		int id=Integer.parseInt(req.getParameter("id"));
		String name=new String(req.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");  //解决乱码问题
		String password=req.getParameter("password");
		String email=req.getParameter("email");
		String address=new String(req.getParameter("address").getBytes("ISO-8859-1"),"UTF-8");
		
		UserInfo entity=new UserInfo();
		entity.setId(id);
		entity.setName(name);
		entity.setPassword(password);
		entity.setEmail(email);
		entity.setAddress(address);
		
		UserInfoService userInfoService=new UserInfoServiceImpl();
		userInfoService.updateUserInfoById(entity);
		req.getRequestDispatcher("/userInfoList").forward(req, resp);
		//resp.sendRedirect("/UserManagementTang/WebContent/user_info_update.jsp");  //转发重定向
		
		
	}

}

user_info_update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>更新用户</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<div class="container">
	<nav class="navbar navbar-default">
	  <div class="container-fluid">
	    <!-- Brand and toggle get grouped for better mobile display -->
	    <div class="navbar-header">
	      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
	        <span class="sr-only">Toggle navigation</span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	      </button>
	      <a class="navbar-brand" href="#">用户管理系统</a>
	    </div>
	
	    <!-- Collect the nav links, forms, and other content for toggling -->
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      <ul class="nav navbar-nav">
	        <li class="active"><a href="<%=path%>/index1">首页 <span class="sr-only">(current)</span></a></li>
	        <li><a href="https://blog.csdn.net/weixin_54464792?type=blog">联系我们</a></li>
	      </ul>
	      <form class="navbar-form navbar-left">
	        <div class="form-group">
	          <input type="text" class="form-control" placeholder="Search">
	        </div>
	        <button type="submit" class="btn btn-default">搜索</button>
	      </form>
	      <ul class="nav navbar-nav navbar-right">
	        <li class="dropdown">
	          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户 <span class="caret"></span></a>
	          <ul class="dropdown-menu">
	            <li><a href="#">个人中心</a></li>
	            <li><a href="#">设置</a></li>
	            <li><a href="#">帮助</a></li>
	            <li role="separator" class="divider"></li>
	            <li><a href="<%=path%>/login">注销</a></li>
	          </ul>
	        </li>
	      </ul>
	    </div><!-- /.navbar-collapse -->
	  </div><!-- /.container-fluid -->
	</nav>
	
	<div class="row">
	
	  <div class="col-md-3">
	  	<div class="list-group">
		  <a class="list-group-item" href="<%=path%>/index1">首页</a>      
		  <a class="list-group-item" href="<%=path%>/userInfoSave">添加用户</a>
		  <a class="list-group-item" href="<%=path%>/userInfoList">用户列表</a>
		</div>
	  </div>
	  
	  <div class="col-md-9">
	  	<form action="<%=path%>/userInfoUpdate" method="post">
	  		<input type="hidden" name="id" value="${entity.id}">
		  <div class="form-group">
		    <label>姓名</label>
		    <input type="text" name="name" value="${entity.name}" class="form-control" placeholder="Please input your name here">
		  </div>
		  
		  <div class="form-group">
		    <label>密码</label>
		    <input type="password" name="password" value="${entity.password}" class="form-control" placeholder="Please input your password here">
		  </div>
		  
		  <div class="form-group">
		    <label>邮箱</label>
		    <input type="email" name="email" value="${entity.email}" class="form-control" placeholder="Please input your E-mail here">
		  </div>
		  
		  <div class="form-group">
		    <label>地址</label>
		    <input type="text" name="address" value="${entity.address}" class="form-control" placeholder="Please input your address here">
		  </div>
		  
		  <button type="submit" class="btn btn-primary center-block">修改(Update)</button>
		</form>
	  </div>
	  
	</div>
	
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

(5)删除用户

UserInfoDeleteServlet.java

package Tang.servlet;

import java.io.IOException;
import java.util.List;

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 Tang.entity.UserInfo;
import Tang.service.UserInfoService;
import Tang.service.impl.UserInfoServiceImpl;

/**
 * 用户删除控制器
 * @author TZQ
 *
 */

@WebServlet("/userInfoDelete")
@SuppressWarnings("serial")
public class UserInfoDeleteServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		this.doPost(req, resp);
		
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		//根据id删除
		UserInfoService userInfoService=new UserInfoServiceImpl();
		userInfoService.deleteUserInfoById(Integer.parseInt(req.getParameter("id")));
		req.getRequestDispatcher("/userInfoList").forward(req, resp);
		//resp.sendRedirect("/userInfoList");  //转发重定向
		
		
	}
}

(6)登录

LoginInfo.java

package Tang.entity;


/**
 * 注册登录实体类
 * @author TZQ
 *
 */
public class LoginInfo {
	private String account;
	private String password;
	
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "LoginInfo [account=" + account + ", password=" + password + "]";
	}
	
	
	

}

LoginInfoService.java

package Tang.service;

import Tang.entity.LoginInfo;

/**
 * 登录接口
 * @author TZQ
 *
 */

public interface LoginInfoService {
	
	LoginInfo login(String account, String password);

	void register(LoginInfo user);

}

LoginInfoServiceImpl.java

package Tang.service.impl;

import Tang.dao.LoginInfoDao;
import Tang.entity.LoginInfo;
import Tang.service.LoginInfoService;

/**
 * 登录接口实现类
 * @author TZQ
 *
 */

public class LoginInfoServiceImpl implements LoginInfoService {

	@Override
	public LoginInfo login(String account, String password) {
		return LoginInfoDao.login(account,password);
	}

	@Override
	public void register(LoginInfo user) {
		LoginInfoDao.register(user);
		
	}

}

LoginInfoDao.java

package Tang.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import Tang.entity.LoginInfo;
import Tang.utils.MysqlUtils;

/**
 * 登录功能类
 * @author TZQ
 *
 */

public class LoginInfoDao {

	public static LoginInfo login(String account, String password) {
		String sql="select * from login_info where account="+"'"+account+"'"+" and password="+"'"+password+"'"+";";
		Connection conn=MysqlUtils.getConnection();
		LoginInfo user=new LoginInfo();
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			ResultSet resultSet=pStatement.executeQuery();
			if(resultSet.next()) {
				user.setAccount(resultSet.getString("account"));
				user.setPassword(resultSet.getString("password"));
				System.out.println(user+"登录成功!");
			}
			else {
				System.out.println("用户名或密码错误!");
			}
			resultSet.close();
			pStatement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		return user;
	}

	public static void register(LoginInfo user) {
		String sql="insert into login_info(account,password) values(?,?);";
		Connection conn=MysqlUtils.getConnection();
		
		try {
			PreparedStatement pStatement=conn.prepareStatement(sql);
			pStatement.setString(1, user.getAccount());
			pStatement.setString(2, user.getPassword());
			pStatement.executeUpdate();
			pStatement.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}



}

LoginServlet.java

package Tang.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 Tang.entity.LoginInfo;
import Tang.service.LoginInfoService;
import Tang.service.impl.LoginInfoServiceImpl;

/**
 * 登录控制器
 * @author TZQ
 *
 */
@WebServlet("/login")
@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		req.getRequestDispatcher("/login.jsp").forward(req,resp);
		
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		String account= req.getParameter("account");
		String password= req.getParameter("password");
		LoginInfoService loginInfoService=new LoginInfoServiceImpl();
		LoginInfo user=loginInfoService.login(account, password);
		
		if(user.getAccount()!=null) {
			req.getRequestDispatcher("/index1").forward(req,resp);
		}
		else {
			//这句话的意思,是让浏览器用utf8来解析返回的数据  
			resp.setHeader("Content-type", "text/html;charset=UTF-8");
			//这句话的意思,是告诉servlet用UTF-8转码
			resp.setCharacterEncoding("UTF-8");
			//实现弹窗功能
			PrintWriter out=resp.getWriter();
			out.print("<script>alert('用户名或密码错误,请重新输入!'); window.location='login.jsp';</script>");
			out.flush();
			out.close();
		}
		
	}


}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
        }
        body {
            height: 100%;
        }
        .container {
            height: 100%;
            width:100%;
            background-color:#fbfbfb;
        }
        .login-wrapper {
            background-color:#cececf;
            opacity:0.9;
            width: 358px;
            height: 500px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 46%;
            transform: translate(-50%, -50%);
            box-shadow:8px 8px 8px rgba(0,0,0,0.6);
        }
        .header {
            font-size: 30px;
            font-weight: bold;
            text-align: center;
            line-height: 200px;
        }
        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 15px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
            border-radius: 4px;
        }
        .input-item:placeholder {
            text-transform: uppercase;
        }

        .msg {
            text-align: center;
            line-height: 88px;
        }
        a {
            text-decoration-line: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="login-wrapper">
            <div class="header">用户管理系统</div>
            <form class="form-wrapper" action="<%=path%>/login" method="post">
                <input type="text" name="account" placeholder="账号" class="input-item">
                <input type="password" name="password" placeholder="密码" class="input-item">
                <button type="submit" class="btn btn-primary" style="width:100%; margin-top:12px">登录</button>
            </form>
            <div class="msg">
                还没有账号?
                <a href="<%=path%>/register">注册</a>
            </div>
        </div>
    </div>
</body>
</html>


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

(7)注册

 RegisterServlet.java

package Tang.servlet;

import java.io.IOException;

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 Tang.entity.LoginInfo;
import Tang.service.LoginInfoService;
import Tang.service.impl.LoginInfoServiceImpl;

/**
 * 注册控制器
 * @author TZQ
 *
 */

@WebServlet("/register")
@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		req.getRequestDispatcher("/register.jsp").forward(req,resp);
		
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		String account= req.getParameter("account");
		String password= req.getParameter("password");
		LoginInfoService loginInfoService=new LoginInfoServiceImpl();
		LoginInfo user=new LoginInfo();
		user.setAccount(account);
		user.setPassword(password);
		loginInfoService.register(user);
		req.getRequestDispatcher("/login.jsp").forward(req,resp);
		
	}

}

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%String path=request.getContextPath(); %>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>

<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
        }
        body {
            height: 100%;
        }
        .container {
            height: 100%;
            width:100%;
            background-color:#fbfbfb;
            
        }
        .login-wrapper {
            background-color:#cececf;
            opacity:0.9;
            width: 358px;
            height: 530px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 46%;
            transform: translate(-50%, -50%);
            box-shadow:8px 8px 8px rgba(0,0,0,0.6);
        }
        .header {
            font-size: 25px;
            font-weight: bold;
            text-align: center;
            line-height: 170px;
        }
        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
            border-radius: 4px;
        }
        .input-item:placeholder {
            text-transform: uppercase;
        }

        .msg {
            text-align: center;
            line-height: 88px;
        }
        a {
            text-decoration-line: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="login-wrapper">
            <div class="header">用户管理系统注册</div>
            <form class="form-wrapper" action="<%=path%>/register" method="post">
                <input type="text" placeholder="手机号" class="input-item">
                <input type="text" name="account" placeholder="账号" class="input-item">
                <input type="password" name="password" placeholder="密码" class="input-item">
                <button type="submit" class="btn btn-warning" style="width:100%; margin-top:25px">注册账号</button>
            </form>
        </div>
    </div>
</body>
</html>


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

</body>
</html>

结束

每个人的配置环境不一样遇到的问题也不一样,不是说代码原封不动的复制过去就能运行,遇到问题先百度。上面的代码还是建议跟着Tellsea大佬的教学视频敲一遍,原文链接已经在开头给出。

 

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值