Spring MVC与jdbc整合

Spring MVC与jdbc整合_第1张图片

1.搭建开发环境

---引入ioc、aop、dao、webmvc、mysql驱动包、dbcp包

---在src下添加applicationContext.xml

2.编写entity包下的实体类,dao包下的操作数据库的类,以及mapper包下的查询时封装成对象的类

Spring MVC与jdbc整合_第2张图片

①entity下的Emp类

package entity;
import java.io.Serializable;
public class Emp implements Serializable{
private Integer id;
private String name;
private Double salary;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

}

②dao下的EmpDao类

@Repository
public class EmpDao {
@Resource
private JdbcTemplate template;
public List findAll(){
String sql = "select * from emp";
EmpRowMapper rowMapper = new EmpRowMapper();
List list = template.query(sql, rowMapper);
return list;
}

}

③mapper下的EmpRowMapper类

public class EmpRowMapper implements RowMapper{
@Override
public Object mapRow(ResultSet rs, int index) throws SQLException {
Emp emp = new Emp();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setSalary(rs.getDouble("salary"));
emp.setAge(rs.getInt("age"));
return emp;
}

}

3.配置文件

①web.xml


    springmvc
    org.springframework.web.servlet.DispatcherServlet
   
      contextConfigLocation
      classpath:applicationContext.xml
   

    1
 

 
    springmvc
    *.do

 

②applicationContext.xml

 

 
   
 

 
   
   
   
   
 

    
 
 
 
   
   
 

4.编写ListController和jsp界面

①ListController

@Controller
public class ListController {
@RequestMapping("/list.do")
public ModelAndView execute(){
ModelAndView mav = new ModelAndView();
//获取dao的对象不能通过new新建来获取,要通过配置来获取
String conf = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
EmpDao empDao = ac.getBean("empDao",EmpDao.class);

List list = empDao.findAll();
mav.getModel().put("list1", list);
mav.setViewName("list");
return mav;
}

}

②list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="dao.*,entity.*,java.util.*" %>


 
 
 
   


     
       
       
     
      <%
        List list = (List)request.getAttribute("list1");
        for(int i=0;i          Emp e = list.get(i);
       %>
       

         
         
       
       <%
       }
        %>
   
IDname
<%=e.getId() %><%=e.getName() %>

 

5.效果

Spring MVC与jdbc整合_第3张图片

你可能感兴趣的:(spring技术)