1.使用eclipse创建maven项目,引入依赖包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- 添加jstl依赖 Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
<build>
<finalName>epoint03</finalName>
<defaultGoal>compile</defaultGoal>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
2.定义实体类:
//学生实体类
public class Student {
private int sid;
private String sname;
private int sage;
private String stel;
private String sadrres;
public Student() {
super();
}
public Student(int sid, String sname, int sage, String stel, String sadrres) {
super();
this.sid = sid;
this.sname = sname;
this.sage = sage;
this.stel = stel;
this.sadrres = sadrres;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getStel() {
return stel;
}
public void setStel(String stel) {
this.stel = stel;
}
public String getSadrres() {
return sadrres;
}
public void setSadrres(String sadrres) {
this.sadrres = sadrres;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", sage=" + sage + ", stel=" + stel + ", sadrres=" + sadrres
+ "]";
}
}
3,封装一个连接数据库的jdbcutils工具类
//用于连接数据库的方法类
public class JDBCUtil {
// 连接数据库
public static Connection conData(Connection connection) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/epoint01?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
String user = "root";
String password = "1234";
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
return connection;
}
}
//关闭方法
public static void closeRes(Connection connection, PreparedStatement pst, ResultSet rs) {
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4,写dao接口方法实现:
public interface StuDao {
// 查找所有学生
public List<Student> Findall();
// 根据学生姓名跟电话查找学生
public Student Findone(Student stu);
// 增加学生
public int Addone(Student stu);
// 删除指定id的学生
public int Delbyid(int sid);
// 修改指定id的学生信息
public int Updatebyid(Student stu);
//根据id查找学生
public Student Findbyid(int sid);
}
//方法实现类,用于连接数据库操作数据
public class StuDaoImp implements StuDao {
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
// 查找所有学生
public List<Student> Findall() {
List<Student> list = new ArrayList<Student>();
// 获取连接
connection = JDBCUtil.conData(connection);
String sql = "select * from student;";
try {
pst = connection.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
// 将读取的数据存入集合
list.add(new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
// System.out.println("查询结果:" + list);
return list;
}
}
// 根据学生姓名跟电话查找学生
public Student Findone(Student stu) {
connection = JDBCUtil.conData(connection);
Student student = null;
String sql = "select * from student where sname=? and stel=?";
try {
pst = connection.prepareStatement(sql);
pst.setString(1, stu.getSname());
pst.setString(2, stu.getStel());
rs = pst.executeQuery();
// 如果rs有值,代表查询成功,此时默认只能查出一个值
if (rs.next()) {
student = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5));
System.out.println(student);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
return student;
}
}
// 增加学生
public int Addone(Student stu) {
connection = JDBCUtil.conData(connection);
String sql = "insert into Student(sname,sage,stel,sadrres) VALUES (?,?,?,?);";
int i = 0;
try {
pst = connection.prepareStatement(sql);
pst.setString(1, stu.getSname());
pst.setInt(2, stu.getSage());
pst.setString(3, stu.getStel());
pst.setString(4, stu.getSadrres());
i = pst.executeUpdate();
//System.out.println("受影响的行" + i);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
return i;
}
}
// 删除指定id的学生
public int Delbyid(int sid) {
connection = JDBCUtil.conData(connection);
String sql = "DELETE from student where sid=?";
int i = 0;
try {
pst = connection.prepareStatement(sql);
pst.setInt(1, sid);
i = pst.executeUpdate();
//System.out.println("受影响的行为:" + i);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
return i;
}
}
// 修改指定id的学生信息
public int Updatebyid(Student stu) {
connection = JDBCUtil.conData(connection);
String sql = "UPDATE student set sname=?,sage=?,stel=?,sadrres=? where sid=?";
int i = 0;
try {
pst = connection.prepareStatement(sql);
pst.setString(1, stu.getSname());
pst.setInt(2, stu.getSage());
pst.setString(3, stu.getStel());
pst.setString(4, stu.getSadrres());
pst.setInt(5, stu.getSid());
i = pst.executeUpdate();
System.out.println("受影响的行为:" + i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
return i;
}
}
//根据学生的id获取该学生信息
@Override
public Student Findbyid(int sid) {
Student student=null;
connection = JDBCUtil.conData(connection);
String sql = "select * from student where sid=?;";
try {
pst = connection.prepareStatement(sql);
pst.setInt(1, sid);
rs = pst.executeQuery();
while (rs.next()) {
// 将读取的数据存入集合
student= new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5)) ;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeRes(connection, pst, rs);
//System.out.println("id查询结果:" + student);
return student;
}
}
}
5,逻辑层代码接口实现:
//逻辑层的处理
public interface StuService {
//登陆功能,即查找学生是否存在
public Student Login(Student stu);
//展示列表
public List<Student> Listall();
//增加学生
public int addone(Student stu);
//根据id修改学生信息
public int Changebyid(Student stu);
//根据id删除学生
public int delbyid(int sid);
//根据id查找学生信息
public Student findbyid(int sid) ;
}
//逻辑层实现
public class StuServiceImp implements StuService{
StuDaoImp stuDao=new StuDaoImp();
//登录功能,及查询该学生是否存在,并将查询的学生返回
public Student Login(Student stu) {
Student student= stuDao.Findone(stu);
return student;
}
//获取学生列表
public List<Student> Listall() {
return stuDao.Findall();
}
//添加一位学生,添加之前判断该学生是否存在,以学生姓名与电话为判断条件
public int addone(Student stu) {
if(stuDao.Findone(stu)==null) {//如果不存在则添加
int i= stuDao.Addone(stu);
return i;}
else {
return 0;
}
}
//根据学生id修改学生信息
public int Changebyid(Student stu) {
int i = stuDao.Updatebyid(stu);
return i;
}
//删除一个学生
public int delbyid(int sid) {
int i=0;
i=stuDao.Delbyid(sid);
return i;
}
@Override
public Student findbyid(int sid) {
return stuDao.Findbyid(sid) ;
}
}
6.可以先写jsp页面也可以先写servlet控制器,我先写的界面,由界面思考给个接口要实现的功能:
1.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>学生管理登陆页面</title>
</head>
<body>
<form class="form-horizontal" action="${pageContext.request.contextPath}/Login" method="post">
<table>
<tr>
<td>*昵称</td><td><input type="text" name="sname"/></td>
</tr>
<tr>
<td>*密码</td><td><input type="password" name="stel"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/> </td><td>
<input type="reset"value="重置"/></td></tr>
</table>
<div >${msg}</div>
</form>
</body>
</html>
2.listall.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息展示</title>
</head>
<body>
<table >
<tr>
<th>学生姓名</th>
<th>年龄</th>
<th>电话</th>
<th>地址</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="item" >
<tr >
<td>${item.sname}</td>
<td>${item.sage}</td>
<td>${item.stel}</td>
<td>${item.sadrres}</td>
<td>
<a href="${pageContext.request.contextPath}/Delteone?sid=${item.sid}" >删除</a>
<a href="${pageContext.request.contextPath}/Updateone?sid=${item.sid}" >修改</a>
</td>
</tr>
</c:forEach>
</table>
<a href="addOne.jsp" >添加</a>
</body>
</html>
3.changeone.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改信息界面</title>
</head>
<body>
<form class="form-horizontal" action="${pageContext.request.contextPath}/changeOne?sid=${stu.sid}" method="post">
<table>
<tr>
<td>*姓名</td><td><input type="text" name="sname" value="${stu.sname}"/></td>
</tr>
<tr>
<td>*年龄</td><td><input type="text" name="sage" value="${stu.sage}"/></td>
</tr>
<tr>
<td>*电话</td><td><input type="text" name="stel" value="${stu.stel}"/></td>
</tr>
<tr>
<td>*地址</td><td><input type="text" name="sadrres" value="${stu.sadrres}"/></td>
</tr>
<tr>
<input type="submit" value="提交"/> </tr>
</table>
</form>
</body>
</html>
4.addone.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加学生界面</title>
</head>
<body>
<form class="form-horizontal" action="${pageContext.request.contextPath}/Addone" method="post">
<table>
<tr>
<td>*姓名</td><td><input type="text" name="sname"/></td>
</tr>
<tr>
<td>*年龄</td><td><input type="text" name="sage"/></td>
</tr>
<tr>
<td>*电话</td><td><input type="text" name="stel"/></td>
</tr>
<tr>
<td>*地址</td><td><input type="text" name="sadrres"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/> </td><td>
<input type="reset"value="重置"/></td></tr>
</table>
</form>
</body>
</html>
5.error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示</title>
</head>
<body>
这是错误页面。。。。
你怎么进来呢。。。。。
</body>
</html>
7.servlet控制器的实现
1.登陆
@WebServlet({ "/loginServlet", "/Login" })
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一请求的编码,解决post请求乱码
request.setCharacterEncoding("utf-8");
StuServiceImp stuService=new StuServiceImp();
String name=request.getParameter("sname");
String stel = request.getParameter("stel");
Student stu=new Student();
stu.setSname(name);
stu.setStel(stel);
System.out.println("登录请求任务:==>"+stu);
HttpSession session = request.getSession();
Student login = stuService.Login(stu);
if(login==null) {//登录失败
session.setAttribute("msg", "用户名或密码错误!!");
System.out.println("登录失败====!");
response.sendRedirect("login.jsp");
}else {
//登陆成功,获取学生列表并跳转到展示页面
List<Student> listall = stuService.Listall();
request.setAttribute("list", listall);
session.setAttribute("msg", " ");
System.out.println("登陆成功");
request.getRequestDispatcher("Listall.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2.修改
@WebServlet({ "/updateOne", "/Updateone" })
public class updateOne extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一请求的编码,解决post请求乱码
request.setCharacterEncoding("utf-8");
//根据sid修改用户,首先根据该sid查找学学生信息返回到修改页面
StuService stuService=new StuServiceImp();
int sid=Integer.parseInt(request.getParameter("sid"));
Student student=stuService.findbyid(sid);
if(student!=null) {
request.setAttribute("stu",student);
request.getRequestDispatcher("changeOne.jsp").forward(request, response);
}else {
System.out.println("修改所传入的id不存在");
response.sendRedirect("error.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
@WebServlet("/changeOne")
public class changeOne extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//统一请求的编码,解决post请求乱码
request.setCharacterEncoding("utf-8");
// 根据sid修改用户
StuService stuService = new StuServiceImp();
String sname = request.getParameter("sname");
int sage = Integer.parseInt(request.getParameter("sage"));
int sid = Integer.parseInt(request.getParameter("sid"));
String stel = request.getParameter("stel");
String sadrres = request.getParameter("sadrres");
int i = stuService.Changebyid(new Student(sid, sname, sage, stel, sadrres));
if (i > 0) {
System.out.println("修改成功");
// 修改成功,跳到展示页面方法
List<Student> listall = stuService.Listall();
request.setAttribute("list", listall);
request.getRequestDispatcher("Listall.jsp").forward(request, response);
} else {
// 失败
System.out.println("修改失败");
response.sendRedirect("error.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3.删除
@WebServlet({ "/delteoneServlet", "/Delteone" })
public class delteoneServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一请求的编码,解决post请求乱码
request.setCharacterEncoding("utf-8");
StuServiceImp stuService=new StuServiceImp();
int sid=Integer.parseInt(request.getParameter("sid"));
int delbyid = stuService.delbyid(sid);
if(delbyid>0) {
//删除成功,跳回到展示页面的方法
System.out.println("删除完毕!");
List<Student> listall = stuService.Listall();
request.setAttribute("list", listall);
request.getRequestDispatcher("Listall.jsp").forward(request, response);
}else {
//删除失败
System.out.println("删除失败");
response.sendRedirect("error.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4.添加
@WebServlet({ "/addoneServlet", "/Addone" })
public class addoneServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一请求的编码,解决post请求乱码
request.setCharacterEncoding("utf-8");
// 添加
StuService stuService = new StuServiceImp();
String sname = request.getParameter("sname");
int sage = Integer.parseInt(request.getParameter("sage"));
int sid=0;
String stel = request.getParameter("stel");
String sadrres = request.getParameter("sadrres");
int i = stuService.addone(new Student(sid, sname, sage, stel, sadrres));
if (i > 0) {
System.out.println("添加成功");
// 成功,跳到展示页面方法
List<Student> listall = stuService.Listall();
request.setAttribute("list", listall);
request.getRequestDispatcher("Listall.jsp").forward(request, response);
} else {
// 失败
System.out.println("添加失败");
response.sendRedirect("error.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
项目结构如下:
项目如果遇到找不到mysql驱动类,可能需要单独将mysql驱动jar包复制一份到tomcat的lib目录下,
数据库结构:
项目运行界面:
登陆:
登陆成功:
修改:
添加: