Web实验
1)
新建一个数据库表。
2) 在表中增加若干记录,作为初始数据。
3) 打开Eclipse软件,新建一个名为Lab03的Web项目,并设置其部署程序为Tomcat。
4) 在Lab03中添加文件,编写代码。
5) Index.jsp文件代码:
<%@page import="Bean.Student"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<style type="text/css">
table {
width: 90%;
background: #ccc;
margin: 10px auto;
border-collapse: collapse;/*border-collapse:collapse合并内外边距(去除表格单元格默认的2个像素内外边距*/
}
th{
height: 25px;
line-height: 25px;
text-align: center;
border: 1px solid #ccc;
}
th {
background: #eee;
font-weight: normal;
}
tr {
background: #fff;
}
tr:hover {
background: #cc0;
}
</style>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
List<Student> students = (List<Student>)request.getAttribute("students");
%>
<table>
<tr>
<th>Sno</th>
<th>Sname</th>
<th>Sage</th>
<th>Sbirthday</th>
<th>Delete</th>
<th>Update</th>
<tr>
<%
for(Student student:students){
%>
<tr>
<th><%=student.getSno() %></th>
<th><%=student.getSname() %></th>
<th><%=student.getSage() %></th>
<th><%=student.getSbirthday() %></th>
<th><a href="DeleteStudentServlet?sno=<%=student.getSno()%>">Delete</a></th>
<th><a href="update.jsp?sno=<%=student.getSno()%>">Update</a></th>
</tr>
<%
}
%>
</table>
<a href="add.jsp" style="display: block; text-align: center;">Add Student</a>
</body>
</html>
6) Add.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 action="AddStudentServlet" method="post" align = "center">
学号:<input type="text" name="sno"><br/>
姓名:<input type="text" name="sname"><br/>
年龄:<input type="text" name="sage"><br/>
生日:<input type="text" name="sbirthday"><br/>
<input type="submit" value="add"><br/>
</form>
</body>
</html>
7) Update.jsp文件代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Update Student Information</title>
</head>
<body>
<%
int sno = Integer.parseInt(request.getParameter("sno"));
%>
<form action="UpdateStudentServlet" method="post" align = "center">
Please enter the student number of the student to be modified:<input type="text" name="sno" value=<%=sno %> readonly="readonly"><br/>
Please enter the modified Name:<input type="text" name="sname"><br/>
Please enter the modified age:<input type="text" name="sage"><br/>
Please enter the modified address:<input type="text" name="saddress"><br/>
<input type="submit" value="修改"><br/>
</form>
</body>
</html>
8) Student实体类代码:
package Bean;
public class Student {
private String sno;
private String sname;
private String sage;
private String sbirthday;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSage() {
return sage;
}
public void setSage(String sage) {
this.sage = sage;
}
public String getSbirthday() {
return sbirthday;
}
public void setSbirthday(String sbirthday) {
this.sbirthday = sbirthday;
}
public String toString() {
return this.getSno()+"--"+this.getSname()+"--"+this.getSage()+"--"+this.getSbirthday();
}
public Student(String sno, String sname, String sage, String sbirthday) {
super();
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.sbirthday = sbirthday;
}
public Student(String sname,String sage, String sbirthday) {
this.sname = sname;
this.sage = sage;
this.sbirthday = sbirthday;
}
}
9) StudentDao类:
package Daos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import Bean.Student;
//数据访问层——》数据库
public class StudentDao{//原子性的:增删改查 无法拆分
private final String URL = "jdbc:mysql://localhost:3306/db";
private final String USERNAME = "root";
private final String PASSWORD = "123456";
//根据学号判断是否存在该学生
public boolean isExist(String sno) {
return queryStudentBySno(sno)==null?false:true;
}
//删除学生
public boolean deleteStudentBySno(String sno) {
Connection connection = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "delete from student where sno=?";
pstmt = (PreparedStatement) connection.prepareStatement(sql);
pstmt.setString(1, sno);
int count = pstmt.executeUpdate();
if(count > 0)
return true;
else
return false;
}catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
try {
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//增加学生
public boolean addStudent(Student student){
Connection connection = null;
PreparedStatement pstmt = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver" );
connection = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "insert into student(sno,sname,sage,sbirthday) values(?,?,?,?)";
pstmt = (PreparedStatement) connection.prepareStatement(sql);
pstmt.setString(1, student.getSno());
pstmt.setString(2, student.getSname());
pstmt.setString(3, student.getSage());
pstmt.setString(4, student.getSbirthday());
int count = pstmt.executeUpdate();
if(count > 0)
return true;
else
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
try {
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//根据学号查找学生
public Student queryStudentBySno(String sno) {
Student student = null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver" );
connection = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "select * from student where sno = ?";
pstmt = (PreparedStatement) connection.prepareStatement(sql);
pstmt.setString(1, sno);
rs = pstmt.executeQuery();
if(rs.next()) {
String no = rs.getString("sno");
String name = rs.getString("sname");
String age = rs.getString("sage");
String birthday = rs.getString("sbirthday");
// System.out.println(no+name+age+address);
student = new Student(no,name,age,birthday);
}
return student;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//查询全部学生
public List<Student> queryAllStudent() {
List<Student> students = new ArrayList<>();
Student student = null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver" );
connection = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "select * from student";
pstmt = (PreparedStatement) connection.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
String no = rs.getString("sno");
String name = rs.getString("sname");
String age = rs.getString("sage");
String birthday = rs.getString("sbirthday");
student = new Student(no,name,age,birthday);
students.add(student);
}
return students;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//根据学号修改学生信息
public boolean updateStudentBySno(String sno,Student student) {
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver" );
connection = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "update student set sname=?,sage=?,sbirthday=? where sno=?";
pstmt = (PreparedStatement) connection.prepareStatement(sql);
pstmt.setString(1, student.getSname());
pstmt.setString(2, student.getSage());
pstmt.setString(3, student.getSbirthday());
pstmt.setString(4, sno);
int count = pstmt.executeUpdate();
if(count > 0)
return true;
else
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
10) 在service包下创建impl包
public class StudentServiceImpl implements StudentService {
private StudentDaoImpl studentDao = new StudentDaoImpl();
@Override
public List<Student> getAll() {
return studentDao.getAll();
}
public boolean deleteStudentBySno(String sno);
public boolean addStudent(Student student);
public Student queryStudentBySno(String sno);
public List<Student> queryAllStudent();
public boolean updateStudentBySno(String sno,Student student);
}
11) StudentService类:
package Service;
import java.util.List;
import Bean.Student;
import Daos.StudentDao;
//业务逻辑层 可拆分
public class StudentService {
StudentDao studentDao = new StudentDao();
//增加学生,先判断是否存在学生,在增加学生
public boolean addStudent(Student student) {
if(!studentDao.isExist(student.getSno())) {
studentDao.addStudent(student);
return true;
}else {
System.out.println(student.getSno()+ student.getSname()+student.getSage() +student.getSbirthday());
System.out.println("此人已存在!增加失败!");
return false;
}
}
//删除学生,先判断是否存在学生,在删除学生
public boolean deleteStudentBySno(String sno) {
if(studentDao.isExist(sno)) {
return studentDao.deleteStudentBySno(sno);
}else {
System.out.println("此人不存在!删除失败!");
return false;
}
}
//根据学号修改学生信息,先判断学生是否存在,在修改
public boolean updateStudentBySno(String sno,Student student) {
if(studentDao.isExist(sno)) {
return studentDao.updateStudentBySno(sno, student);
}else {
System.out.println("此人不存在!修改失败!");
return false;
}
}
//根据学号查询学生
public Student queryStudentBySno(String sno) {
return studentDao.queryStudentBySno(sno);
}
//查询全部学生
public List<Student> queryAllStudent(){
return studentDao.queryAllStudent();
}
12) AddStudentServlet:
package Servlets;
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 Bean.Student;
import Service.StudentService;
@WebServlet("/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddStudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("utf-8");
String no = request.getParameter("sno");
String name = request.getParameter("sname");
String age = request.getParameter("sage");
String birthday = request.getParameter("sbirthday");
Student student = new Student(no,name,age,birthday);
StudentService studentService = new StudentService();
boolean rs = studentService.addStudent(student);
if(rs) {
response.sendRedirect("QueryAllStudentServlet");
}else {
out.println("增加失败!");
}
//
// StudentDao studentDao = new StudentDao();
// Student student1 = studentDao.queryStudentBySno(no);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
13) DeleteStudentServlet:
package Servlets;
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 Service.StudentService;
@WebServlet("/DeleteStudentServlet")
public class DeleteStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteStudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
String no = request.getParameter("sno");;
StudentService studentService = new StudentService();
studentService.deleteStudentBySno(no);
response.sendRedirect("QueryAllStudentServlet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
14) QueryAllStudentServlet:
package Servlets;
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 Service.StudentService;
@WebServlet("/DeleteStudentServlet")
public class DeleteStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteStudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
String no = request.getParameter("sno");;
StudentService studentService = new StudentService();
studentService.deleteStudentBySno(no);
response.sendRedirect("QueryAllStudentServlet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
15) QueryStudentBySnoServlet:
package Servlets;
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 Bean.Student;
import Service.StudentService;
@WebServlet("/QueryStudentBySnoServlet")
public class QueryStudentBySnoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public QueryStudentBySnoServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
String no = request.getParameter("sno");
StudentService studentService = new StudentService();
Student student = studentService.queryStudentBySno(no);
System.out.println(student);
request.setAttribute("student", student);
request.getRequestDispatcher("detailsPage.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
16) UpdateStudentServlet:
package Servlets;
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 Bean.Student;
import Service.StudentService;
@WebServlet("/UpdateStudentServlet")
public class UpdateStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateStudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
String no = request.getParameter("sno");
String name = request.getParameter("sname");
String age = request.getParameter("sage");
String address = request.getParameter("saddress");
Student student = new Student(name,age,address);
StudentService studentService = new StudentService();
studentService.updateStudentBySno(no, student);
response.sendRedirect("QueryAllStudentServlet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
17) 程序截图
所有学生的信息显示:
添加功能:
修改学号为20200001学生的年龄为18
点击学号为20200004的delete链接后完成删除功能: