我正在學習DAO和服務,並試圖爲一些測試(JSP)製作一個非常簡單的Web應用程序。我創建了DAO和服務類,但我怎樣才能讓它們彼此合作?我希望爲了在textfield中輸入的值將被保存在我的數據庫中。下面是一個代碼:Spring MVC - 如何將控制器與服務類和DAO連接起來?
StudentDAO:
public void create(Student student);
StudentDAOImpl:
private JdbcTemplate jdbcTemplate;
DataSource dataSource;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void create(Student student) {
String query = "insert into studentdb.student (`name`, `age`) values (?,?)";
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, student.getName());
ps.setString(2, student.getAge());
int out = ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
StudentService長相酷似StudentDAO一樣,這裏是StudentServiceImpl:
StudentDAO studentDAO;
public void createStudent(Student student) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("studentconfig.xml");
studentDAO = ctx.getBean("studentDAO", StudentDAO.class);
student.setName(//value entered in webapp);
student.setAge(//value entered in webapp);
studentDAO.create(student);
}
,這裏是MainController :
@RequestMapping(value="/home.html", method = RequestMethod.POST)
public ModelAndView homePagePost(Model model, @ModelAttribute("student") Student student1){
model.addAttribute("student", student1);
studentService.createStudent(student1);
ModelAndView home = new ModelAndView("index");
return home;
}
的index.jsp:
<html>
<body>
<h2>Hello World!</h2>
<form action="/webapplication/home.html" method="post">
<input type="text" name="${student.name}"/>
<input type="text" name="${student.age} }"/>
<input type="submit" value="confirm!"/>
</form>
</body>
</html>
它對你有幫助嗎? –