Javaweb简单的学生管理系统(增删改)
以下是一个简单的Java Web学生管理系统的代码示例,包括增加、删除和修改学生信息的功能。
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
private List<Student> students = new ArrayList<>();
@Override
public void init() {
// 初始化学生数据
students.add(new Student("1", "张三"));
students.add(new Student("2", "李四"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("add".equals(action)) {
addStudent(request, response);
} else if ("delete".equals(action)) {
deleteStudent(request, response);
} else if ("edit".equals(action)) {
editStudent(request, response);
} else {
listStudents(request, response);
}
}
private void addStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
Student student = new Student(id, name);
students.add(student);
response.sendRedirect("student?action=list");
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
String id = request.getParameter("id");
students.removeIf(student -> student.getId().equals(id));
response.sendRedirect("student?action=list");
}
private void editStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
Student student = new Student(id, name);
students.removeIf(stu -> stu.getId().equals(id));
students.add(student);
response.sendRedirect("student?action=list");
}
private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("students", students);
RequestDispatcher dispatcher = request.getRequestDispatcher("students.jsp");
dispatcher.forward(request, response);
}
}
class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
评论已关闭