准备
数据库准备:
USE `crud`;
/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`did` int(11) NOT NULL auto_increment,
`dname` varchar(20) default NULL,
PRIMARY KEY (`did`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;
搭建模块:
复制前面模块。
修改父工程pom.xml。modules中添加ssm_env_crud
修改当前工程pom.xml。
- artifactId:ssm_env_crud
- name:ssm_env_crud Maven Webapp
修改applicationContext.xml中数据库名配置为crud
问题:
(1)如果出现(没有引入jdk)
解决:
显示所有数据:
思路:
步骤:
(1)Department
(2)TestDepartmentService
(3)DepartmentService
(4)IDepartmentDao
(5)IDepartmentDao.xml
(6)DepartmentController
(7)list_depts.jsp
(1)Department
public class Department {
private Integer did;
private String dname;
...
(2)TestDepartmentService
TestDepartmentService:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDepartmentService {
@Autowired
private IDepartmentService departmentService;
//查找
@Test
public void test01(){
List<Department> list = departmentService.findAllDepartments();
System.out.println(list);
}
}
(3)DepartmentService
DepartmentService:
@Service
public class DepartmentServiceImpl implements IDepartmentService {
@Autowired
private IDepartmentDao departmentDao;
@Override
public List<Department> findAllDepartments() {
return departmentDao.findAll();
}
}
(4)IDepartmentDao
IDepartmentDao:
public interface IDepartmentDao {
//select * from department order by did asc;
List<Department> findAll();
}
(5)IDepartmentDao.xml
IDepartmentDao.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="jsu.lcw.dao.IDepartmentDao">
<select id="findAll" resultType="department">
select * from department order by did asc;
</select>
</mapper>
数据测试:(成功)
(6)DepartmentController
DepartmentController:
@Controller
@RequestMapping("/dept")
public class DepartmentController {
private static final Logger l = LoggerFactory.getLogger(DepartmentController.class);
@Autowired
IDepartmentService departmentService;
@RequestMapping(path = "/list",method = RequestMethod.GET)
public String listDepts(Model model){
List<Department> list = departmentService.findAllDepartments();
l.info("listDepts list:"+list);
model.addAttribute("depts",list);
return "list_depts";
}
}
(7)list_depts.jsp
WEB-INF/pages/list_depts.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<%
request.setAttribute("path",request.getContextPath());
%>
</head>
<body>
<table border="1px" width="100%">
<tr>
<td>编号</td>
<td>部门名称</td>
</tr>
<c:forEach items="${depts}" var="dept">
<tr>
<td>${dept.did}</td>
<td>${dept.dname}</td>
</tr>
</c:forEach>
</table>
</body>
页面测试:(成功)
添加数据:
思路:
删除数据:
思路:
修改数据:
思路:
gitee项目地址: https://gitee.com/liang-chengwei/ssm_env_crudversion.git