【发布时间】:2019-11-14 04:04:19
【问题描述】:
我有一个 spring mvc 项目,我想转换 spring rest api 项目。
这是我的示例代码;
我的控制器
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private SchoolService schoolService;
@GetMapping("/list")
public String ListStudents(Model model) {
List<Student> theStudent = studentService.getStudents();
model.addAttribute("students", theStudent);
return "List-student";
}
@GetMapping("/addNewStudent")
public String addNewStudent(Model model) {
Student theStudent = new Student();
model.addAttribute("student", theStudent);
List<School> theSchool = schoolService.getSchools();
model.addAttribute("schools", theSchool);
return "student-form";
}
@PostMapping("/saveStudent")
public String saveStudent(@ModelAttribute("student") Student theStudent) {
studentService.saveStudent(theStudent);
return "redirect:/student/list";
}
@GetMapping("/showFormforUpdate")
public String showFormForUpdate(@RequestParam("studentID") int theId, Model model) {
Student theStudent = studentService.getStudent(theId);
model.addAttribute(theStudent);
List<School> theSchool = schoolService.getSchools();
model.addAttribute("schools", theSchool);
return "student-form";
}
@GetMapping("/deleteStudent")
public String deleteStudent(@RequestParam("studentID") int theId, Model model) {
studentService.deleteStudent(theId);
return "redirect:/student/list";
}
}
我的 DAOImpl 类
@Repository
public class StudenDAOImpl implements StudentDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List<Student> getStudents() {
Session currentSession=sessionFactory.getCurrentSession();
Query<Student> theQuery = currentSession.createQuery("from Student", Student.class);
List<Student> students=theQuery.getResultList();
return students;
}
@Override
public void saveStudent(Student theStudent) {
Session currentSession=sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theStudent);
}
@Override
public Student getStudent(int theId) {
Session currentSession=sessionFactory.getCurrentSession();
Student theStudent=currentSession.get(Student.class, theId);
return theStudent;
}
@Override
public void deleteStudent(int theId) {
Session currentSession=sessionFactory.getCurrentSession();
Query theQuery=currentSession.createQuery("delete from Student where id=:studentID");
theQuery.setParameter("studentID", theId);
theQuery.executeUpdate();
}
}
其实我知道我需要改变的地方。但我不太了解spring Rest Api。在我的代码中,我在视图(jsp 文件)中发送了许多属性,并在此处捕获了这些属性。但是 RestApi 没有视图。我需要删除属性函数。但是我可以添加什么来代替属性函数?我是新的 RestApi 请帮助我该怎么办?
【问题讨论】:
-
如果你想有详细的指南,请看我的书infoq.com/minibooks/spring-boot-building-api-backend(免责声明:我是作者)
标签: java spring-boot spring-mvc jpa