基于Javaweb、MySQL、jsp的简单的学生信息管理系统,查看所有学生信息,登录验证,增加学生信息,修改和删除就不写了,就是在表单中增加两个链接跳转到servlet控制Mysql
总览
数据库
1.连接池
package utils;
import java.sql.*;
/**
* @author yicheng
* @date 2021-08-30
* 针对JDBS操作的工具类
* */
public class JDBCUtils {
static final String DRIVERNAME="com.mysql.cj.jdbc.Driver";
static final String URL = "jdbc:mysql://127.0.0.1:3306/class?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
static final String USER="root";
static final String PASSWORD="qwer1234";
static {
try {
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static Connection connection = null;
static PreparedStatement statement = null;
static ResultSet resultSet = null;
/**
* 获取数据库连接的封装方法
* @return Connection
* */
public static Connection getconnection(){
try {
connection = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
/**
* 查询
* @param1 sql语句
* @param2 sql中需要填充的参数
*/
public static ResultSet query(String sql,Object... objs){
//预处理
getconnection();
try {
statement = connection.prepareStatement(sql);
//判断objs是否为空或为0
if(objs != null && objs.length > 0){
for (int i = 0; i < objs.length; i++) {
statement.setObject(i+1,objs[i]);
}
}
//查询操作
resultSet = statement.executeQuery();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return resultSet;
}
/**
* 增
*
* @return
*/
public static void add(String sql){
getconnection();
try {
statement = connection.prepareStatement(sql);
System.out.println("影响行数:"+ statement.executeUpdate(sql));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 删
*
*/
public static void delete(String sql){
getconnection();
try {
statement = connection.prepareStatement(sql);
System.out.println("executeUpdate:"+ statement.executeUpdate(sql));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 改
*
*/
public static void update(String sql){
getconnection();
try {
statement = connection.prepareStatement(sql);
System.out.println("executeUpdate:"+ statement.executeUpdate(sql));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 资源释放
*/
public static void free(){
if (null != resultSet){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != statement){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
对登陆界面的控制类:
package controller;
import dao.StudentDao;
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 java.io.IOException;
import java.net.URLEncoder;
@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设定编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
//获取表单数据
String account = req.getParameter("account");
String password = req.getParameter("password");
System.out.println("account = " + account);
System.out.println("password = " + password);
//七天免密登录
Cookie cookie = new Cookie("nameinfo", URLEncoder.encode(account+"-"+password,"utf-8") );
//一天免登录,待验证remember
cookie.setMaxAge(24*60*60);
//增加Cookie到responce
resp.addCookie(cookie);
String error;
//账号密码的非空校验 trim去空格
if (account == null || account.trim().length() == 0 || password == null || password.trim().length() == 0){
//告知用户不能为空,同时用户依然停留在登录界面
error = "用户名或密码不能为空!";
//资源的跳转: 重定向 转发
//重定向:根据当前的url进行资源的跳转 /表示是web容器的根路径 但是我们自己想在跳转url的同时携带信息
// resp.sendRedirect(req.getContextPath() + "/html/*");
//转发:根据url进行服务器内部资源的转发,此时可以共享信息(req,resp)
req.setAttribute("error", error);
//创建一个分发器,转发到登录页面资源
// RequestDispatcher dispatcher = req.getRequestDispatcher("/loginPage");
// dispatcher.forward(req,resp);
req.getRequestDispatcher("/LoginPageServlet").forward(req,resp);
}else {
//校验账号密码是否正确
StudentDao userDao = new StudentDao();
boolean b = userDao.loginQuery(account, password);
if (b){
//返回true表示登陆成功,跳转到首页
req.setAttribute("name",account);
//重定向
req.getRequestDispatcher("home.jsp").forward(req,resp);
System.out.println(account + "登陆成功!");
}else {
//返回false表示登陆失败,重新返回登录页面,并告知用户名密码错误
error = "账号或密码错误!";
req.setAttribute("error",error);
//转发
req.getRequestDispatcher("/LoginPageServlet").forward(req,resp);
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
pojo包下的Student封装类:
package pojo;
import utils.JDBCUtils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Student {
private String id;
private String name;
private String password;
private String sex;
private String major;
private int age;
public Student() {
}
public Student(String id, String name, String password, String sex, String major, int age) {
super();
this.id = id;
this.name = name;
this.password = password;
this.sex = sex;
this.major = major;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String 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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//添加
public static void saveStudent(Student student) {
String sql = "insert into student(id, name, password,sex,major,age) values(?,?,?,?,?,?)";
try {
PreparedStatement pstmt = JDBCUtils.getconnection().prepareStatement(sql);
pstmt.setString(1,student.getId());
System.out.println(student.getId());
pstmt.setString(2,student.getName());
System.out.println(student.getName());
pstmt.setString(3,student.getPassword());
System.out.println(student.getPassword());
pstmt.setString(4,student.getSex());
System.out.println(student.getSex());
pstmt.setString(5,student.getMajor());
System.out.println(student.getMajor());
pstmt.setInt(6,student.getAge());
System.out.println(student.getAge());
int rs = pstmt.executeUpdate();
System.out.println("影响行数:" + rs);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//显示所有学生信息
public List<Student> findAllStudents(){
List<Student> stuList = new ArrayList<Student>();
String sql = "select * from student";
PreparedStatement pstmt = null;
try {
pstmt = JDBCUtils.getconnection().prepareStatement(sql);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String password = rs.getString("password");
String sex = rs.getString("sex");
String major = rs.getString("major");
int age = rs.getInt("age");
Student stu = new Student(id,name,password,sex,major,age);
stuList.add(stu);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.free();
}
return stuList;
}
}
还涉及到免密登录
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%--
Created by IntelliJ IDEA.
User: HP
Date: 2021/10/18
Time: 20:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<%
/*Cookie实现免密登录*/
Cookie[] cookies = request.getCookies();
String[] s = null;
if (cookies!=null){
for (Cookie cookie : cookies) {
if (URLDecoder.decode(cookie.getName(), "utf-8").equals("nameinfo")){
String str = URLDecoder.decode(cookie.getValue(),"utf-8" );
s = str.split("-");
}
}
}
%>
<form action="LoginServlet" method="post">
<table align="center" width="600px" bgcolor="#f0f8ff" height="320px">
<%
if (s!=null) {
%>
<tr><th colspan="600px" height="120px" align="center"><font size="5px" color="black">登录</font></th></tr>
<tr><td colspan="600px" height="50px" align="center"><input type="text" name="account" placeholder="请输入账号" value="<%=s[0]%>"></td></tr>
<tr><td colspan="600px" height="50px" align="center"><input type="password" name="password" placeholder="请输入密码" value="<%=s[1]%>"></td></tr>
<%
}else{
%>
<tr><th colspan="600px" height="120px" align="center"><font size="5px" color="black">登录</font></th></tr>
<tr><td colspan="600px" height="50px" align="center"><input type="text" name="account" placeholder="请输入账号"></td></tr>
<tr><td colspan="600px" height="50px" align="center"><input type="password" name="password" placeholder="请输入密码"></td></tr>
<tr><td colspan="600px" height="50px" align="center"><input type="checkbox" name="remember" value="1">记住我</td></tr>
<%}
%>
<tr><th width="260px" height="40px" align="right"><input type="submit" value="登录"></th><th width="118px" align="right"><input type="reset" value="重置"></th><th></th><th></th></tr>
<tr><th height="60px"></th></tr>
</table>
</form>
</body>
</html>
项目源码在Gitee:
代码有些许不足之处后续会优化,没做过多的详细描述,自我感觉看一遍代码,自己打一遍代码,更能提升水平(在理解大部分知识的基础上),此项目运行完全没问题
若想更深入了解原理和映射关系可以去哔哩哔哩搜JavaWeb学生管理系统,那里的老师讲的挺好的,听完一边,自己敲一遍定能查漏补缺。
此项目为个人编写,不涉及复制粘贴问题。项目也是写完好久了,打算把初期写的这个不完整项目总结一下,完整项目是用了SpringBoot,优化完之后会上传进阶版(“🙂”)
Gitee源码请点击访问