【发布时间】:2016-01-21 01:27:21
【问题描述】:
我正在学习 DAO 和服务,并尝试为一些测试 (JSP) 制作一个非常简单的 Web 应用程序。我创建了 DAO 和 Service 类,但是我怎样才能让它们相互协作呢?我想为了在文本字段中输入的值将保存在我的数据库中。这是一个代码:
学生道:
public void create(Student student);
学生DAOImpl:
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>
【问题讨论】:
标签: java spring spring-mvc