一、项目简介
本学员管理系统采用servlet 实现在网页上面进行学员信息的管理。通过登录之后对学员信息进行增加,删除,查询,修改等操作。通过不同的页面跳转,对应着相应的功能。清晰,简单的操作指引,为客户提供更简单便捷的操作。
源代码地址:jsp学员管理系统
相关项目:小白进阶大佬之路——你的第一个JDBC商城订单系统
Lombok插件学习文档:Lombok插件从简介到安装的一条龙服务
二、工具及环境
1、eclipse-jee-2018
2、JDK11
3、tomcat9
4、lombok-1.18.6
5、MySQL8
三、文件目录
四、项目创建
1、创建web项目
(1)点击File->New->Dynamic Web Project或者右键右键选择New->Dynamic Web Project,如果像我一样没有此选项,可以选择Other选项;
然后输入dynamic(一般输入dy就可以),选择Dynamic Web Project。
(2)输入项目名称,选择运行时环境(中间件环境),选择web相应的版本;
(3)在创建的空项目中添加所需要的jar包;
将下列jar包复制添加到lib文件夹中;
(4)将刚刚复制到文件夹的jar包添加至项目依赖;
项目对应文件夹中出现了新添加的依赖则表示添加成功;
(5)右键单击项目名称,按照下列顺序添加Lombok插件依赖;
按照下列步骤找到Lombok的路径;
选择打开eclipse安装路径中的Lombok.jar;
添加后,点击应用并关闭;
可以看到项目中已经成功Lombok的依赖。
(6)在源码src文件夹中创建对应的文件夹与配置文件;
(7)在WebContent文件夹中创建登录的页面,在WEB-INF文件夹中新建page文件夹,将其他的页面创建在page文件夹中。
2、创建数据源配置文件
源码:
#配置数据源
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=admin
#配置连接池参数
jdbc.initialSize=10
jdbc.maxTotal=5
jdbc.maxIdle=5
jdbc.maxWaitMillis=5000
若复制粘贴的配置文件出现乱码的情况,右键单击配置文件,选择点击列表最后的Properties,在窗口的Other中选择UTF-8编码方式,点击应用即可恢复。
3、创建工具类
3.1、DBCP数据库连接池
/**
* Title: Dbcp
* Description:
* 演示dbcp数据库连接池
* 使用Commons-DBCP组件
*/
public class Dbcp {
public static final String DB_CONFIG_FILEPATH="dbconfig.properties";
private static Properties properties;
private static Dbcp dbcp;
static {
try {
properties=new Properties();
InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(DB_CONFIG_FILEPATH);
properties.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BasicDataSource dataSource=null;
private Dbcp() {
//创建Commons-DBCP连接池对象
dataSource=new BasicDataSource();
//设置数据源参数
dataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
dataSource.setUrl(properties.getProperty("jdbc.url"));
dataSource.setUsername(properties.getProperty("jdbc.username"));
dataSource.setPassword(properties.getProperty("jdbc.password"));
//设置连接池参数
dataSource.setInitialSize(Integer.parseInt(properties.getProperty("jdbc.initialSize")));//初始化容量
dataSource.setMaxTotal(Integer.parseInt(properties.getProperty("jdbc.maxTotal")));//最大活动数
dataSource.setMaxIdle(Integer.parseInt(properties.getProperty("jdbc.maxIdle")));//最大空闲数
dataSource.setMaxWaitMillis(Long.parseLong(properties.getProperty("jdbc.maxWaitMillis")));//最长等待时间
}
public static Dbcp getInstance() {
if(dbcp==null) {
dbcp=new Dbcp();
}
return dbcp;
}
//返回数据源对象
public BasicDataSource getDataSource() {
return dataSource;
}
/**
* 连接池获取连接对象
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
return dataSource==null?null:dataSource.getConnection();
}
/**
* 归还连接
*/
public void close(Connection conn,Statement psmt,ResultSet rs) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
close(conn, psmt);
}
public void close(Connection conn,Statement psmt) {
if(psmt!=null) {
try {
psmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3.2、JDBC模板工具类
/**
*
* Title: JDBCTemplate
* Description:
* JDBC模板工具类:封装了JDBC步骤
*/
public class JDBCTemplate {
/**
* 封装更新操作
* @param psmtCreator 获取PreparedStatement对象
* @return
*/
public static final int update(PreparedStatementCreator psmtCreator) {
Connection conn=null;
PreparedStatement psmt=null;
int result=-1;
try {
//使用数据库连接池获取连接
conn=Dbcp.getInstance().getConnection();
conn.setAutoCommit(false);
psmt=psmtCreator.create(conn);
result=psmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
if(conn!=null) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.printStackTrace();
}finally {
Dbcp.getInstance().close(conn, psmt);
}
return result;
}
/**
* 封装查询操作
* @param psmtCreator 获取PreparedStatement对象
* @param rsExtractor 解析结果集,获取解析后的对象
* @return 返回解析后的查询结果
*/
public static final Object query(PreparedStatementCreator psmtCreator,ResultSetExtractor rsExtractor) {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
Object result=null;
try {
conn=Dbcp.getInstance().getConnection();
conn.setAutoCommit(false);
psmt=psmtCreator.create(conn);
rs=psmt.executeQuery();
result=rsExtractor.extractor(rs);
conn.commit();
} catch (SQLException e) {
if(conn!=null) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.printStackTrace();
}finally {
Dbcp.getInstance().close(conn, psmt, rs);
}
return result;
}
}
3.3、PreparedStatement回调接口
/**
*
* Title: PreparedStatementCreator
* Description:
* PreparedStatement回调接口
*/
public interface PreparedStatementCreator {
/**
* 通过连接对象获取预编译对象
* @param conn 连接对象
* @return 预编译语句对象
* @throws SQLException 抛出SQL异常
*/
PreparedStatement create(Connection conn) throws SQLException;
}
3.4、处理结果集
/**
*
* Title: ResultSetExtractor
* Description:
*
*/
public interface ResultSetExtractor {
/**
*
*处理结果集封装目标对象
* @param rs 结果集对象
* @return 封装好的Object对象
* @throws SQLException 抛出SQL异常
*/
Object extractor(ResultSet rs) throws SQLException;
}
4、创建实体类
4.1、Admin对象
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Admin {
private int id;
private String username;//账号
private String pwd;//密码
}
由于导入了Lombok插件的依赖,通过注解就能实现对无参、有参构造,get/set方法的创建。
4.2、Student对象
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(exclude="id")
public class Student {
private int id;
private String sno;//编号
private String sname;//姓名
private String address;//地址
}
5、创建DAO接口
DAO,全名为Data Access Object,数据库访问对象。DAO通常包括三个部分:DAO接口,DAO实现类,DAO工厂类。
DAO接口:用来声明对数据库表的操作,如增删改查记录。
DAO实现类:用来实现DAO接口,并实现其接口的所有方法。
DAO工厂类:用来返回一个DAO接口类型的DAO实现类实例对象。
5.1、AdminDAO接口
public interface AdminDAO {
//登录功能
Admin findAdmin(String username,String pwd);
//注册功能
int addAdmin(Admin admin);
}
5.2、StudentDAO接口
public interface StudentDAO {
//查询所有
List<Student> findAllStudent();
//新增
int addStudent(Student student);
//删除
int deleteStudent(int id);
//更新
int updateStudent(Student student);
//查询
List<Student> findStudentBySname(String sname);
//通过编号查询
Student findStudentById(int id);
}
6、创建DAO接口实现类
6.1、AdminDAOImpl接口实现类
源码:
public class AdminDAOImpl implements AdminDAO {
//登录
@Override
public Admin findAdmin(String username, String pwd) {
// TODO Auto-generated method stub
return (Admin) JDBCTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="select * from admin where username=? and password=?";
PreparedStatement psmt=conn.prepareStatement(sql);
psmt.setString(1, username);
psmt.setString(2, pwd);
return psmt;
}
}, new ResultSetExtractor() {
@Override
public Object extractor(ResultSet rs) throws SQLException {
Admin admin=null;
if (rs.next()) {
int id=rs.getInt(1);
String username=rs.getString(2);
String pwd=rs.getString(3);
admin=new Admin(id, username, pwd);
}
return admin;
}
});
}
//注册
@Override
public int addAdmin(Admin admin) {
// TODO Auto-generated method stub
return JDBCTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="insert into admin(username,password) values(?,?)";
PreparedStatement psmt=null;
psmt=conn.prepareStatement(sql);
psmt.setString(1, admin.getUsername());
psmt.setString(2, admin.getPwd());
return psmt;
}
});
}
}
6.2、StudentDAOImpl接口实现类
源码:
public class StudentDAOImpl implements StudentDAO {
//查询所有学员信息
@SuppressWarnings("unchecked")
@Override
public List<Student> findAllStudent() {
// TODO Auto-generated method stub
return (List<Student>) JDBCTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="select * from student";
PreparedStatement psmt=null;
psmt=conn.prepareStatement(sql);
return psmt;
}
}, new ResultSetExtractor() {
@Override
public Object extractor(ResultSet rs) throws SQLException {
List<Student> students=new ArrayList<Student>();
while (rs.next()) {
int id=rs.getInt(1);
String sno=rs.getString(2);
String sname=rs.getString(3);
String address=rs.getString(4);
Student student=new Student(id, sno, sname, address);
students.add(student);
}
return students;
}
});
}
//添加学员信息
@Override
public int addStudent(Student student) {
// TODO Auto-generated method stub
return JDBCTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="insert into student(sno,sname,address) values(?,?,?)";
PreparedStatement psmt=null;
psmt=conn.prepareStatement(sql);
psmt.setString(1, student.getSno());
psmt.setString(2, student.getSname());
psmt.setString(3, student.getAddress());
return psmt;
}
});
}
//删除学员信息
@Override
public int deleteStudent(int id) {
// TODO Auto-generated method stub
return JDBCTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="delete from student where id=?";
PreparedStatement psmt=conn.prepareStatement(sql);
psmt.setInt(1, id);
return psmt;
}
});
}
//修改学员信息
@Override
public int updateStudent(Student student) {
// TODO Auto-generated method stub
return JDBCTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
String sql="update student set sno=?,sname=?,address=? where id=?";
PreparedStatement psmt=conn.prepareStatement(sql);
psmt.setString(1, student.getSno());
psmt.setString(2, student.getSname());
psmt.setString(3,student.getAddress());
psmt.setInt(4, student.getId());
return psmt;
}
});
}
//通过id找学员信息
@Override
public Student findStudentById(int id) {
// TODO Auto-generated method stub
return (Student) JDBCTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
// TODO Auto-generated method stub
PreparedStatement psmt=null;
String sql="select * from student where id=?";
psmt=conn.prepareStatement(sql);
psmt.setInt(1, id);
return psmt;
}
}, new ResultSetExtractor() {
@Override
public Object extractor(ResultSet rs) throws SQLException {
// TODO Auto-generated method stub
Student student=null;
if (rs.next()) {
int id=rs.getInt(1);
String sno=rs.getString(2);
String sname=rs.getString(3);
String address=rs.getString(4);
student=new Student(id, sno, sname, address);
}
return student;
}
});
}
//模糊查询
@SuppressWarnings("unchecked")
@Override
public List<Student> findStudentBySname(String sname) {
// TODO Auto-generated method stub
return (List<Student>) JDBCTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement create(Connection conn) throws SQLException {
// TODO Auto-generated method stub
String sql="select * from student where sname like ?";
PreparedStatement psmt=conn.prepareStatement(sql);
psmt.setString(1, "%"+sname+"%");
return psmt;
}
}, new ResultSetExtractor() {
@Override
public Object extractor(ResultSet rs) throws SQLException {
// TODO Auto-generated method stub
List<Student> students=new ArrayList<Student>();
while(rs.next()) {
int id=rs.getInt(1);
String sno=rs.getString(2);
String sname=rs.getString(3);
String address=rs.getString(4);
Student student=new Student(id, sno, sname, address);
students.add(student);
}
return students;
}
});
}
}
7、创建Service接口
7.1、AdminService接口
源码:
public interface AdminService {
//登录功能
Admin login(String username,String pwd);
//注册功能
boolean addAdmin(Admin admin);
}
7.2、StudentService接口
源码:
public interface StudentService {
//查询所有学员
List<Student> findAllStudent();
//删除
boolean delStudent(int id);
//添加
boolean addStudent(Student student);
//修改
boolean upStudent(Student student);
//查找
Student findStudent(int id);
//模糊查询
List<Student> findStudentSname(String sname);
}
8、创建Service接口实现类
8.1、AdminServiceImpl接口实现类
源码:
public class AdminServiceImpl implements AdminService {
private AdminDAO adminDAO=new AdminDAOImpl();
//登录
@Override
public Admin login(String username, String pwd) {
// TODO Auto-generated method stub
return adminDAO.findAdmin(username, pwd);
}
//注册
@Override
public boolean addAdmin(Admin admin) {
// TODO Auto-generated method stub
return adminDAO.addAdmin(admin)>0?true:false;
}
}
8.2、StudentServiceImpl接口实现类
源码:
public class StudentServiceImpl implements StudentService {
private StudentDAO studentDAO=new StudentDAOImpl();
@Override
public List<Student> findAllStudent() {
// TODO Auto-generated method stub
return studentDAO.findAllStudent();
}
@Override
public boolean delStudent(int id) {
// TODO Auto-generated method stub
return studentDAO.deleteStudent(id)>0?true:false;
}
@Override
public boolean addStudent(Student student) {
// TODO Auto-generated method stub
return studentDAO.addStudent(student)>0?true:false;
}
@Override
public boolean upStudent(Student student) {
// TODO Auto-generated method stub
return studentDAO.updateStudent(student)>0?true:false;
}
@Override
public Student findStudent(int id) {
// TODO Auto-generated method stub
return studentDAO.findStudentById(id);
}
@Override
public List<Student> findStudentSname(String sname) {
// TODO Auto-generated method stub
return studentDAO.findStudentBySname(sname);
}
}
9、创建Servlet接口的实现类
Servlet(Server Applet),全称Java Servlet,未有中文译文。是用Java编写的服务器端程序。其主要功能在于交互式地浏览和修改数据,生成动态Web内容。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。
Servlet的工作模式:
客户端发送请求至服务器;
服务器启动并调用Servlet,Servlet根据客户端请求生成响应内容并将其传给服务器;
服务器将响应返回客户端。
9.1、LoginServlet实现类
/**
* Servlet implementation class LoginServlet
* 登录
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private AdminService adminService=new AdminServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//登录功能
String username=request.getParameter("username");
String pwd=request.getParameter("pwd");
//jdbc 数据库查询
Admin admin=adminService.login(username, pwd);
HttpSession session=request.getSession();
if(admin!=null) {
//登录成功
//保存当前用户信息
session.setAttribute("currAdmin", admin);
//相对路径
//查询所有书籍
response.sendRedirect("student/findAll");
}else {
//重新登录
response.sendRedirect("login.jsp?info=1");//相当于 url地址直接访问
}
}
}
9.2、RegisterServlet实现类
/**
* Servlet implementation class RegisterServlet
* 注册
*/
@WebServlet("/register/*")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private AdminService adminService=new AdminServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo=request.getPathInfo();
HttpSession session=request.getSession();
//注册
if ("/reg".equals(pathInfo)) {
request.getRequestDispatcher("/WEB-INF/page/register.jsp").forward(request, response);
}
if ("/doregister".equals(pathInfo)) {
String username=request.getParameter("username");
String password=request.getParameter("pwd");
Admin admin=new Admin(0, username, password);
adminService.addAdmin(admin);
response.sendRedirect("/WebStudent/login.jsp");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
9.3、StudentServlet实现类
/**
* Servlet implementation class StudentServlet
*/
@WebServlet("/student/*")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentService studentService=new StudentServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public StudentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo=request.getPathInfo();
HttpSession session=request.getSession();
if ("/findAll".equals(pathInfo)) {
//查询所有信息
List<Student> students=studentService.findAllStudent();
//保存session域中
session.setAttribute("students", students);
//跳转页面
request.getRequestDispatcher("/WEB-INF/page/main.jsp").forward(request, response);
}
//删除
if ("/del".equals(pathInfo)) {
//获取要删除信息的id
int id=Integer.parseInt(request.getParameter("id"));
studentService.delStudent(id);
response.sendRedirect("findAll");
}
//添加
if ("/add".equals(pathInfo)) {
//转发到addStudent.jsp中
request.getRequestDispatcher("/WEB-INF/page/addstudent.jsp").forward(request, response);
}
if ("/doadd".equals(pathInfo)) {
String sno=request.getParameter("sno");
String sname=request.getParameter("sname");
String address=request.getParameter("address");
Student student=new Student(0, sno, sname, address);
//添加至数据库
studentService.addStudent(student);
response.sendRedirect("findAll");
}
//修改信息
if ("/findstudent".equals(pathInfo)) {
int id=Integer.parseInt(request.getParameter("id"));
Student student=studentService.findStudent(id);
session.setAttribute("currStudent", student);//保存数据
request.getRequestDispatcher("/WEB-INF/page/updatestudent.jsp").forward(request, response);
}
if ("/doupdate".equals(pathInfo)) {
Student student=(Student) session.getAttribute("currStudent");
student.setSno(request.getParameter("sno1"));
student.setSname(request.getParameter("sname1"));
student.setAddress(request.getParameter("address1"));
studentService.upStudent(student);
response.sendRedirect("findAll");
}
//模糊查询
if ("/findsname".equals(pathInfo)) {
String sname=request.getParameter("search");
List<Student> students=new StudentServiceImpl().findStudentSname(sname);
if (students!=null&&students.size()>0) {
session.setAttribute("students", students);
request.getRequestDispatcher("/WEB-INF/page/find.jsp").forward(request, response);
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
10、创建JSP网页
10.1、login.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>登录</title>
<style>
.formDiv{
width: 70%;
margin-left: 15%;
border:2px #46BCAF solid;
text-align: center;
margin-top: 10%;
padding-top: 5%;
padding-bottom:5%;
}
.formDiv .btn{
width: 200px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.formDiv .btn:focus{
border:1px #46BCAF solid;
}
.formDiv .btn1{
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left: 47px;
font-size:15px;
}
.formDiv .btn1:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
.formDiv .btn2{
display: inline-block;
text-decoration: none;
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 26px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left: 47px;
font-size:15px;
padding-top:4px;
}
.formDiv .btn2:hover{
background-color: #46BCAF;
color: #fff;
}
.top{
width: 100%;
border:0px solid red;
height: 1%;
font-size: 14px;
color: red;
margin-left:20px;
}
.div1{
margin-top:-50px;
color:#46BCAF;
font-size:20px;
}
</style>
</head>
<body>
<div class="formDiv">
<div class="div1">
<span>学员管理系统</span>
</div>
<br>
<div class="top">
<c:if test="${param.info==1 }">
<span>账号或密码错误,请重新登录</span>
</c:if>
<c:if test="${param.info==2 }">
<span>请先登录</span>
</c:if>
</div>
<form action="login" method="post">
账号:<input type="text" name="username" placeholder="请输入账号" class="btn"/>
<br><br>
密码:<input type="password" name="pwd" placeholder="请输入密码" class="btn"/>
<br><br><br>
<input type="submit" value="登录" class="btn1">
<a href="/WebStudent/register/reg" class="btn2">注册</a>
<!-- <input type="button" value="注册" class="btn1" > -->
</form>
</div>
</body>
</html>
10.2、register.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>注册</title>
<style>
.formDiv{
width: 70%;
margin-left: 15%;
border:1px #DFDFDF solid;
text-align: center;
margin-top: 10%;
padding-top: 5%;
padding-bottom:5%;
}
.formDiv .btn{
width: 200px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.formDiv .btn:focus{
border:1px #46BCAF solid;
}
.formDiv .btn1{
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left: 47px;
font-size:15px;
}
.formDiv .btn1:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
.formDiv .btn2{
display: inline-block;
text-decoration: none;
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 26px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left: 47px;
font-size:15px;
padding-top:4px;
}
.formDiv .btn2:hover{
background-color: #46BCAF;
color: #fff;
}
.top{
width: 100%;
border:0px solid red;
height: 1%;
font-size: 14px;
color: red;
margin-left:20px;
}
</style>
</head>
<body>
<div class="formDiv">
<form action="/WebStudent/register/doregister" method="post">
账号:<input type="text" name="username" placeholder="请输入账号" class="btn"/>
<br><br>
密码:<input type="password" name="pwd" placeholder="请输入密码" class="btn"/>
<br><br><br>
<input type="submit" value="注册" class="btn1">
<a href="#" class="btn2" onclick="javascript:window.history.back(-1);">返回</a>
<!-- <input type="button" value="注册" class="btn1" > -->
</form>
</div>
</body>
</html>
10.3、main.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>主页</title>
<style>
*{
margin:0;
padding:0;
}
.main{
margin-top:50px;
width:80%;
margin-left:10%;
border:0px #DFDFDF solid;
text-align: center;
}
table,th,td{
border:1px #46BCAF solid;
}
.btn{
display: inline-block;
height: 30px;
background-color: #EEEEEE;
text-decoration: none;
line-height: 30px;
color: #000;
}
.btn:hover{
background-color: #46BCAF;
color: #fff;
}
table{
border-collapse: collapse;
width: 90%;
margin-left: 5%;
}
table .btn{
width: 70px;
}
.div1{
text-align: left;
width: 90%;
height:100px;
margin-left:5%;
margin-bottom:30px;
/* border:1px red solid; */
}
.div1 a{
width: 100px;
height:30px;
text-align: center;
margin-top:10px;
border-radius: 5px;
}
.div2{
weight:100%;
height:50px;
}
.div2 .a1{
background-color: #EEEEEE;
color:#000;
width: 100px;
height: 30px;
font-size:15px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left:77%;
}
.a1:hover{
background-color: #46BCAF;
color: #fff;
}
.div3{
weight:100%;
height:50px;
/* border:1px green solid; */
}
.div3 .put1{
width: 400px;
height: 40px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
margin-left: 200px;
}
.div3 .put1:focus{
border:1px #46BCAF solid;
}
.div3 .put2{
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 40px;
font-size:15px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.div3 .put2:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
</style>
<script type="text/javascript">
function out() {
var flag = confirm("您确定要退出吗?");
if(flag==true){
window.location.href="http://localhost:8080/WebStudent/login.jsp";
}else {
return false;
}
}
</script>
</head>
<body>
<div class="main">
<div class="div1">
<div class="div2">
<a href="/WebStudent/student/add" class="btn" >添加信息</a>
<input type="button" value="退出登录" class="a1" onclick="return out()">
<!-- <a href="#" class="a1">退出登录</a> -->
</div>
<div class="div3">
<form action="/WebStudent/student/findsname" method="post">
<input type="text" placeholder="请您输入查询学员姓名" name="search" class="put1">
<input type="submit" value="搜索" class="put2">
</form>
</div>
</div>
<table>
<tr>
<th>学号</th>
<th>姓名</th>
<th>地址</th>
<th>操作</th>
</tr>
<c:forEach items="${students }" var="student">
<tr>
<td>${student.sno }</td>
<td>${student.sname }</td>
<td>${student.address }</td>
<td>
<a href="findstudent?id=${student.id }" class="btn">修改</a>
<a href="del?id=${student.id }" class="btn">删除</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
10.4、find.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>查询信息</title>
<style>
.main{
margin-top:50px;
width:80%;
height:600px;
margin-left:10%;
border:1px #DFDFDF solid;
text-align: center;
}
.main .put1{
width: 400px;
height: 40px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.main .put1:focus{
border:1px #46BCAF solid;
}
.main .put2{
background-color: #EEEEEE;
color:#000;
width: 60px;
height: 40px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.main .put2:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
table,th,td{
border:1px #46BCAF solid;
}
table{
border-collapse: collapse;
width: 90%;
margin-left: 5%;
}
.main .dow{
width:60px;
height:30px;
margin-top:-325px;
margin-left:89%;
}
.btn{
display: inline-block;
height: 30px;
width:50px;
background-color: #EEEEEE;
text-decoration: none;
line-height: 30px;
color: #000;
border-radius: 5px;
margin-top:200px;
margin-left:89%;
}
.btn:hover{
background-color: #46BCAF;
color: #fff;
}
</style>
</head>
<body>
<div class="main">
<br>
<div>
<form action="/WebStudent/student/findsname" method="post">
<input placeholder="请输入学员姓名" class="put1" name="search">
<input type="submit" value="搜索 " class="put2">
</form>
<br>
<table>
<tr>
<th>学号</th>
<th>姓名</th>
<th>地址</th>
</tr>
<c:forEach items="${students }" var="student">
<tr>
<td>${student.sno }</td>
<td>${student.sname }</td>
<td>${student.address }</td>
</tr>
</c:forEach>
</table>
</div>
<a href="/WebStudent/student/findAll" class="btn" >返回</a>
</div>
</body>
</html>
10.5、addstudent.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>信息录入</title>
<style>
.div{
width: 70%;
margin-left: 15%;
border:1px #DFDFDF solid;
text-align: center;
margin-top: 10%;
padding-top: 5%;
padding-bottom:5%;
}
.div .put1{
width: 200px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.div .put1:focus{
border:1px #46BCAF solid;
}
.div .btn{
background-color: #EEEEEE;
color:#000;
width: 80px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.div .btn:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
.div .span{
margin-left: -5px;
}
.div .btn1{
margin-left: 30px;
}
.div .btn2{
margin-left: 60px;
}
</style>
</head>
<body>
<div class="div">
<form action="/WebStudent/student/doadd" method="post">
学员账号:<input type="text" name="sno" placeholder="请输入账号"/ class="put1">
<br><br>
学员姓名:<input type="text" name="sname" placeholder="请输入姓名" class="put1"/>
<br><br>
地址:<input type="text" name="address" placeholder="请输入地址" class="put1"/>
<br><br>
密码:<input type="password" placeholder="请输入密码" class="put1"/>
<br><br>
确认密码:<input type="password" placeholder="请确认密码" class="put1"/>
<br><br>
<span class="span">性别:</span>
<input type="radio" name="gender" value="男" checked class="btn1">男
<input type="radio" name="gender" value="女" class="btn2">女
<br><br>
<input type="submit" value="确认" class="btn">
<input type="button" value="返回" class="btn" onclick="javascript:window.history.back(-1);">
</form>
</div>
</body>
</html>
10.6、updatestudent.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>信息更新</title>
<style>
.div{
width: 70%;
margin-left: 15%;
border:1px #DFDFDF solid;
text-align: center;
margin-top: 10%;
padding-top: 5%;
padding-bottom:5%;
}
.div .put1{
width: 200px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.div .put1:focus{
border:1px #46BCAF solid;
}
.div .btn{
background-color: #EEEEEE;
color:#000;
width: 80px;
height: 30px;
outline: none;
border:1px #EEEEEE solid;
border-radius: 5px;
}
.div .btn:hover{
background-color: #46BCAF;
color: #fff;
cursor: pointer;
border:1px #46BCAF solid;
}
.div .span{
margin-left: -5px;
}
.div .btn1{
margin-left: 30px;
}
.div .btn2{
margin-left: 60px;
}
</style>
</head>
<body>
<div class="div">
<form action="/WebStudent/student/doupdate" method="post">
学员账号:<input type="text" name="sno1" value="${currStudent.sno }" class="put1"/>
<br><br>
学员姓名:<input type="text" name="sname1" value="${currStudent.sname }" class="put1"/>
<br><br>
地址:<input type="text" name="address1" value="${currStudent.address }" class="put1"/>
<br><br>
密码:<input type="password" placeholder="请输入密码" class="put1"/>
<br><br>
确认密码:<input type="password" placeholder="请确认密码" class="put1"/>
<br><br>
<span class="span">性别:</span>
<input type="radio" name="gender" value="男" checked class="btn1">男
<input type="radio" name="gender" value="女" class="btn1">女
<br><br>
<input type="submit" value="修改" class="btn">
<input type="button" value="返回" class="btn" onclick="javascript:window.history.back(-1);">
</form>
</div>
</body>
</html>
11、创建过滤器
11.1、登录验证
/**
* @author 作者 Tony:
* 类说明
登录验证:没有登录的情况下,不允许进行Student的相关操作
*/
@WebFilter(filterName="loginFilter",urlPatterns="/student/*")
public class LoginFilter implements Filter {
/**
* Default constructor.
*/
public LoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// 登录验证,判断是否登录
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse resp=(HttpServletResponse)response;
HttpSession sesison=req.getSession();
Admin admin=(Admin)sesison.getAttribute("currAdmin");
if(admin!=null) {
//已登录,放行
chain.doFilter(request, response);
}else {
//去登陆
resp.sendRedirect(req.getContextPath()+"/login.jsp?info=2");
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
11.2、设置请求/响应字符集
/**
* @author 作者 Tony:
* 类说明
设置请求/响应字符集
注解配置过滤器参数,字符集tuf-8
*/
@WebFilter(filterName="encodeFilter",urlPatterns="/*",
initParams= {@WebInitParam(name="encode",value="utf-8")})
public class EncodeingFilter implements Filter {
private String DEFAULT_ENCODE="utf-8";
/**
* Default constructor.
*/
public EncodeingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
//设置字符集
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse resp=(HttpServletResponse)response;
req.setCharacterEncoding(DEFAULT_ENCODE);
resp.setContentType("text/html;charset="+DEFAULT_ENCODE);
// 放行
chain.doFilter(req, resp);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
//初始化时读取配置信息,将值赋给属性
DEFAULT_ENCODE=fConfig.getInitParameter("encode");
}
}
12、创建mysql数据库表
12.1、admin表
create table admin(
id int primary key auto_increment,
username varchar(30),
password varchar(30)
);
INSERT INTO admin VALUES (1, 'root', 'root');
INSERT INTO admin VALUES (2, 'admin', '123');
INSERT INTO admin VALUES (3, 'tony', '111');
12.2、student表
create table student(
id int primary key auto_increment,
sno varchar(30),
sname varchar(50),
address varchar(70)
);
insert into student value(1,'s001','张三','江苏');
insert into student value(2,'s002','李四','江西');
insert into student value(3,'s003','王五','浙江');
insert into student value(4,'s004','米六','上海');
insert into student value(5,'s005','二狗','西藏');
insert into student value(6,'s006','tom','广东');
insert into student value(7,'s007','麒麟','台州');
insert into student value(8,'s008','旖旎','福建');
insert into student value(9,'s009','李二','中山');
insert into student value(10,'s010','tony','青岛');
五、项目运行
Service的配置直接略过,自行上网搜索,很多详细的教程。
1、项目放到servers
在控制台的Services中的Tomcat中,鼠标右键单击添加;
鼠标左键单击选择项目后点击中间的添加键,或者直接鼠标左键双击添加项目,然后点击选择完成;
2、启动项目
在控制台鼠标右键Tomcat,点击运行;
运行成功;
六、项目操作展示
1、登录界面
在浏览器的搜索框中输入登录地址;
按下回车键进入到用户登录界面。
2、主界面
点击登录按钮,进入到用户主界面。
3、修改界面
点击【修改】进入修改页面;
输入要修改的内容后,点击【修改】进行确认修改;
这里的密码以及确认密码的输入框内容没用进行校验比对,可以忽略;
修改成功;
4、删除操作
这里是直接进行数据的delete,而我们一般是进行数据的【假删除】,也就是在数据中添加一个状态字段。默认为1或者0;当点击【删除】后,状态字段的数值变为0或者1,之后查出默认状态值的数据就能实现【假删除】了。
点击【删除】按钮后,可以看到【张三】这条数据就被删除掉了。
5、查询操作
这里系统使用的是对【姓名】进行“模糊查询”操作,也就是输入名字中含有的关键字就能被搜索到,这里我们查询名字中带“t”的数据;
可以看到,系统搜索出两条数据,与逻辑是相符的。
6、添加操作
点击【添加信息】按钮,进入到信息添加页面;
输入信息后,点击【确认】按钮,完成添加操作;
可以在主界面上看到新添加的数据渲染成功。
7、退出登录
退出成功后。跳转至登录注册页面。
8、注册操作
先查看数据库的数据;
在注册界面输入账号及密码进行用户注册;
注册成功后跳转至登录界面。
还不快去开动你充满智慧的脑袋去写出一个属于自己的系统~
注:能力有限,目前基本无干货,还请谅解,争取早日能够写出有质量的文章!
我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。