Day27 SSM之CRUD(不包含ajax)超简单的部门增删改查示例(v1)

**源码地址:**https://github.com/BigAnt-cyl/ssm_zhenghe_shili_ajax_bootstrap

项目简介

  • (1)项目的经典模块-CRUD功能

  • (2)什么是CRUD
    CRUD:Create( 创 建 ) Retrieve(查询) Update(更新) Delete(删除)

  • (3)使用什么技术
    ssm:SpringMVC+Spring+MyBatis

一、sql数据库的设计

create database crud;
use crud;

create table department(
	did int primary key auto_increment,
	dname varchar(20)
);
insert into department values(null,'java');
insert into department values(null,'测试');
insert into department values(null,'需求');

create table employee(
	eid int primary key auto_increment,
	ename varchar(20),
	gender varchar(20),
	did int 
);
insert into employee values(null,'jack','1',2);
insert into employee values(null,'rose','1',2);
insert into employee values(null,'tony','1',3);
# 添加外键
alter table employee add foreign key(did) references department(did);

在这里插入图片描述

二、ssm搭建

1、复制模块

  • 在原工程ssm目录下,复制搭建好的ssm01,粘贴为ssm02_crud
  • 修改ssm02_crud 中的pom.xml
  <artifactId>ssm02_crud</artifactId>
  <packaging>war</packaging>

  <name>ssm02_crud Maven Webapp</name>
  • 修改工程ssm中的pom.xml
  <modules>
    <module>ssm01</module>
    <module>ssm02_crud</module>
  </modules>
  • 执行一下以上两个pom.xml
  • 记得修改数据配置信息的数据库名

2、编写实体类 Department

src\main\java\cn\cyl\domain\Department.java

public class Department {
    private Integer did;
    private String dname;

    public Department() {
    }

    public Department(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Department{" +
                "did=" + did +
                ", dname='" + dname + '\'' +
                '}';
    }

    public Integer getDid() {
        return did;
    }
    public void setDid(Integer did) {
        this.did = did;
    }
    public String getDname() {
        return dname;
    }
    public void setDname(String dname) {
        this.dname = dname;
    }
}

3、编写业务层

3.1 业务层接口

src\main\java\cn\cyl\service\IDepartmentService.java

public interface IDepartmentService {

}

3.2 业务层实现类(使用注解配置,并注入dao对象)

src\main\java\cn\cyl\service\impl\DepartmentServiceImpl.java

@Service
public class DepartmentServiceImpl implements IDepartmentService {
	//private可加可不加    
    @Autowired
    private IDepartmentDao dao;
    
}

4、编写持久层

4.1 持久层接口

src\main\java\cn\cyl\dao\IDepartmentDao.java

public interface IDepartmentDao {

}

4.2 持久层接口映射文件

src\main\resources\cn\cyl\dao\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="cn.cyl.dao.IDepartmentDao">
    
</mapper>

5、编写web层 Controller(使用注解配置,并注入service对象)

src\main\java\cn\cyl\controller\DepartmentController.java

@Controller
@RequestMapping("/dept")
public class DepartmentController extends HttpServlet {
    //日志类对象
    private static final Logger log = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private IDepartmentService iDepartmentService;

}

6、编写测试类(使用spring测试,并注入service对象)

src\test\java\cn\cyl\service\TestDepartmentService.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDepartmentService {
    //日志类对象
    private static final Logger log = LoggerFactory.getLogger(TestDepartmentService.class);
    @Autowired
    IDepartmentService service;
    
}

三、查询

1、后台代码

IDepartmentService

//查询所有部门
List<Department> findAllDepartments();

DepartmentServiceImpl

@Override
    public List<Department> findAllDepartments() {
        List<Department> list = dao.findAll();
        return list;
    }

IDepartmentDao

//查询所有
List<Department> findAll();

IDepartmentDao.xml

<select id="findAll" resultType="department">
        select * from department order by did asc
</select>

2、测试

	//查询所有数据
    @Test
    public void test01() {
        List<Department> list = service.findAllDepartments();
        log.info("test01 list=" + list);
    }

运行结果

在这里插入图片描述

3、前台代码

DepartmentController

	@RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model){
        List<Department> depts = iDepartmentService.findAllDepartments();
        log.info("list   depts="+depts);
        //数据添加到页面
        model.addAttribute("depts",depts);
        return "list_depts";
    }

list_depts.jsp
src\main\webapp\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>
</head>
<body>
<a href="">新增</a>
<table border="1px" width="100%">
    <tr>
        <td>编号</td>
        <td>部门名称</td>
        <td>管理</td>
    </tr>

    <c:forEach items="${depts}" var="dept">
         <tr>
             <td>${dept.did}</td>
             <td>${dept.dname}</td>
             <td><a href="">删除</a><a href="">修改</a></td>
         </tr>
    </c:forEach>
</table>
</body>
</html>

运行结果

在这里插入图片描述

四、添加

1、后台代码

IDepartmentService

   //添加一个新的部门
   void saveDepartment(Department dept);

DepartmentServiceImpl

	@Override
    public void saveDepartment(Department dept) {
        dao.save(dept);
    }

IDepartmentDao

	//添加一个
    void save(Department dept);

IDepartmentDao.xml

    <insert id="save" parameterType="department">
        insert into department values(null,#{dname});
    </insert>

2、测试

	//添加一行数据
    @Test
    public void test02() {//
        Department dept = new Department("UI设计部门");
        service.saveDepartment(dept);
    }

运行结果

在这里插入图片描述

3、前台代码

DepartmentController

	@RequestMapping(path ="/save",method = {RequestMethod.POST,RequestMethod.GET})
    public String save(Department dept,Model model){
        if (dept.getDname() != null && !"".equals(dept.getDname())) {
            iDepartmentService.saveDepartment(dept);
            log.info("save dept="+dept);
            return "redirect:/dept/list";
        }else{
            model.addAttribute("error_msg","部门名称不能为空");
            return "forward:/add_dept.jsp";
        }
    }

add_dept.jsp
src\main\webapp\add_dept.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<span style="color: red">${error_msg}</span>
<form method="post" action="${pageContext.request.contextPath}/dept/save">
    <input type="text" name="dname"/><br/>
    <input type="submit" value="保存"/><br/>
</form>
</body>
</html>

运行结果

添加失败

在这里插入图片描述

添加成功

在这里插入图片描述
在这里插入图片描述

五、删除

1、后台代码

IDepartmentService

     //删除指定id的部门数据
    void deleteDepartmentById(int i);

DepartmentServiceImpl

 @Override
    public void deleteDepartmentById(int id) {
        dao.deleteById(id);
    }

IDepartmentDao

//根据id删除
    void deleteById(int id);

IDepartmentDao.xml

    <delete id="deleteById" parameterType="int">
        delete from department where did =#{id};
    </delete>

2、测试

	//根据id删除
    @Test
    public void test03() {
        service.deleteDepartmentById(1);
    }

运行结果

在这里插入图片描述

3、前台代码

DepartmentController

    @RequestMapping(path = "/delete",method = RequestMethod.GET)
    public String delete(Integer did){
        l.info("delete  did = "+did);
        iDepartmentService.deleteDepartmentById(did);
        return "redirect:/dept/list";
    }

list_depts.jsp

<a href="${pageContext.request.contextPath}/dept/delete?did=${dept.did}">删除</a>

运行结果

在这里插入图片描述
在这里插入图片描述

六、修改

  • 修改功能,需要在打开页面的同时,查询一下数据,把数据带到页面进行同赋值,这操作叫做回显。

1、后台代码

IDepartmentService

	//根据指定id修改部门名称
    void updateDepartmentById(Department dept);
    //查找指定id的部门数据
    Department findDepartmentById(int did);

DepartmentServiceImpl

	@Override
    public void updateDepartmentById(Department dept) {
        dao.update(dept);
    }

    @Override
    public Department findDepartmentById(int did) {
        return dao.findById(did);
    }

IDepartmentDao

	//传入对象后,根据id修改
    void update(Department department);
    //根据id查询
    Department findById(int i);

IDepartmentDao.xml

	<update id="update" parameterType="department">
        update department set dname = #{dname} where did = #{did};
    </update>

    <select id="findById" parameterType="int" resultType="department">
        select * from department where did = #{did};
    </select>

2、测试

	//通过id修改
    @Test
    public void test04(){
        Department department = new Department();
        department.setDid(3);
        department.setDname("最牛部门");
        service.updateDepartmentById(department);
    }

    //通过id查询
    @Test
    public void test05(){
        Department department = service.findDepartmentById(2);
        log.info("test05   department="+department);
    }

运行结果

在这里插入图片描述
在这里插入图片描述

3、前台代码

DepartmentController

	@RequestMapping(path = "/updateUI",method = RequestMethod.GET)
    public String updateUI(Integer did,Model model){
        log.info("updateUI id="+did);
        Department department = iDepartmentService.findDepartmentById(did);
        model.addAttribute("dept",department);
        return "update_dept";
    };

    @RequestMapping(path = "update",method = RequestMethod.POST)
    public String update(Department department){
        log.info("update   dept="+department);
        iDepartmentService.updateDepartmentById(department);
        //跳到查询页面
        return "redirect:/dept/list";
    }

list_depts.jsp

<a href="${pageContext.request.contextPath}/dept/updateUI?did=${dept.did}">修改</a>

update_dept.jsp

  • form表单不会将标记为disabled="disabled"作为参数提交到后台
  • 所以,必须增加一个type="hidden"的input标签来提交数据

src\main\webapp\WEB-INF\pages\update_dept.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form method="post" action="${pageContext.request.contextPath}/dept/update">
    <input type="hidden" name="did" value="${dept.did}" >
    <input type="text"  value="${dept.did}" disabled="disabled"/><br/>
    <input type="text" name="dname" value="${dept.dname}"/><br/>
    <input type="submit" value="保存修改"/><br/>
</form>

</body>
</html>

运行结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值