一个基于SSM(Spring MVC, Spring, MyBatis)框架的简单学生成绩管理系统的代码示例如下:
// StudentController.java
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) {
List<Student> students = studentService.findAllStudents();
model.addAttribute("students", students);
return "studentList";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addForm(Model model) {
Student student = new Student();
model.addAttribute("student", student);
return "addStudentForm";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute Student student, RedirectAttributes redirectAttributes) {
studentService.saveStudent(student);
redirectAttributes.addFlashAttribute("message", "Student added successfully!");
return "redirect:/student/list";
}
// ... 其他方法(如删除、更新等)
}
// StudentService.java
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public List<Student> findAllStudents() {
return studentMapper.findAll();
}
public void saveStudent(Student student) {
studentMapper.insert(student);
}
// ... 其他方法
}
// StudentMapper.java
@Mapper
public interface StudentMapper {
@Select("SELECT * FROM students")
List<Student> findAll();
@Insert("INSERT INTO students(name, grade) VALUES(#{name}, #{grade})")
void insert(Student student);
// ... 其他方法
}
在这个例子中,我们定义了一个StudentController
来处理和学生相关的请求,包括展示学生列表、添加学生的表单以及添加操作。StudentService
和StudentMapper
分别用于定义业务逻辑和数据库操作。这个例子展示了如何使用Spring MVC和MyBatis进行简单的CRUD操作,并且如何通过Spring进行依赖注入。