4_5.springboot2.x之Web开发RestfulCRUD操作

1)、RestfulCRUD:CRUD满足Rest风格

URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作

普通CRUD(uri来区分操作)RestfulCRUD
查询getEmpemp—GET
添加addEmp?xxxemp—POST
修改updateEmp?id=xxx&xxx=xxemp/{id}—PUT
删除deleteEmp?id=1emp/{id}—DELETE

2)、实验的请求架构

实验功能请求URI请求方式
查询所有员工empsGET
查询某个员工(来到修改页面)emp/1GET
来到添加页面empGET
添加员工empPOST
来到修改页面(查出员工进行信息回显)emp/1GET
修改员工empPUT
删除员工emp/1DELETE

1、CRUD-员工列表

thymeleaf公共页面元素抽取

1、抽取公共片段
<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名

3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];

三种引入公共片段的th属性:

th:insert:将公共片段整个插入到声明引入的元素中

th:replace:将声明引入的元素替换为公共片段

th:include:将被引入的片段的内容包含进这个标签中

引入片段的时候传入参数:

<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">
    <div class="sidebar-sticky">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link active"
                   th:class="${activeUri=='main.html'?'nav-link active':'nav-link'}"
                   href="#" th:href="@{/main.html}">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                        <polyline points="9 22 9 12 15 12 15 22"></polyline>
                    </svg>
                    Dashboard <span class="sr-only">(current)</span>
                </a>
            </li>

<!--引入侧边栏;传入参数-->
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

员工列表:

<tr th:each="emp:${emps}">
								<td th:text="${emp.id}"></td>
								<td>[[${emp.lastName}]]</td>
								<td th:text="${emp.email}"></td>
								<td th:text="${emp.gender}==0?'':''"></td>
								<td th:text="${emp.department.departmentName}"></td>
								<td th:text="${#dates.format(emp.birth , 'yyyy-MM-dd HH:mm')}"></td>
								<td>
									<a th:href="@{/emp/}+${emp.id}" class="btn btn-sm btn-primary">编辑</a>
									<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
								</td>
							</tr>

controller

@Controller
public class EmpController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    /*
     * @Author: jiatp
     * Description:查询员工返回列表页面
    */
    @GetMapping("/emps")
    public String list(Model model){

        Collection<Employee> employees = employeeDao.getAll();
        //放在作用域中
        model.addAttribute("emps",employees);

        //thymeleaf默认就会拼接串 classpath:/templates/  xxx.html
        return "emp/list";
    }

2、CRUD-员工添加

添加页面的展示:

    /*
     * @Author: jiatp
     * Description:员工添加页面的显示
    */
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //来到添加页面
      return "emp/add";
    }

添加的页面:

<form>
    <div class="form-group">
        <label>LastName</label>
        <input type="text" class="form-control" placeholder="zhangsan">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" placeholder="zhangsan@atguigu.com">
    </div>
    <div class="form-group">
        <label>Gender</label><br/>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender"  value="1">
            <label class="form-check-label"></label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender"  value="0">
            <label class="form-check-label"></label>
        </div>
    </div>
    <div class="form-group">
        <label>department</label>
        <select class="form-control">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select>
    </div>
    <div class="form-group">
        <label>Birth</label>
        <input type="text" class="form-control" placeholder="zhangsan">
    </div>
    <button type="submit" class="btn btn-primary">添加</button>
</form>

注意:提交的数据格式不对:生日:日期;

2017-12-12;2017/12/12;2017.12.12;

日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;

2017-12-12—Date; 类型转换,格式化;

默认日期是按照/的方式;

可以在springmvc配置类中添加实现日期格式化方法:

@Configuration//扩展springmvc功能
public class MyMvcConfig implements WebMvcConfigurer {
 @Override
    public void addFormatters(FormatterRegistry registry) {

        registry.addFormatter(new DateFormatter("yyyy-MM-dd"));
    }
}

或者properties中添加:

application.properties中添加
spring.jackson.date-format=yyyy-MM-dd

controller添加的方法:

 /*
     * @Author: jiatp
     * Description:员工添加
    */
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //打印一下员工信息
        System.out.println(employee);
        employeeDao.save(employee);
        //这里不能用/emps,thymeleaf默认会将该值进行模板引擎下查找,
        //redirect 重定向到一个地址,/带边当前项目路径    forward:表示转发到一个地址

        return "redirect:/emps";
    }

3、CRUD-员工修改

修改员工页面:查出当前员工并且进行回显

 /*
     * @Author: jiatp
     * Description:来到修改页面,查出当前员工在页面进行回显
    */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);

        //页面要显示部门列表
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //回到修改页面,add页面修改添加二合一
        return "emp/add";
    }

重用add.html(修改和添加页面展示)

				<main role="main" th:href="@{/emp}" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<form th:action="@{/emp}" method="post">
						<!--请求方式:post:请求员工添加  put:员工的修改-->
						<!--
                        1.配置请求方式:springmvc中配置hiddenHttpMethodFilter;将请求转换成指定的方式
                        2.创建一个post页面表单
                        3.创建一个input项,name=_method,值就是指定的方式
                        -->
						<input type="hidden" name="_method" value="put" th:if="${emp!=null}">
						<input type="hidden" th:value="${emp.id}" name="id" th:if="${emp!=null}">
						<div class="form-group">
							<label>LastName</label>
							<input type="text" name="lastName" class="form-control" th:value="${emp!=null}?${emp.lastName}" placeholder="zhangsan">
						</div>
						<div class="form-group">
							<label>Email</label>
							<input type="email" name="email" class="form-control" th:value="${emp!=null}?${emp.email}" placeholder="zhangsan@atguigu.com">
						</div>
						<div class="form-group">
							<label>Gender</label><br/>
							<div class="form-check form-check-inline">
								<input class="form-check-input" type="radio" name="gender" th:checked="${emp!=null}?${emp.gender==1}" value="1">
								<label class="form-check-label"></label>
							</div>
							<div class="form-check form-check-inline">
								<input class="form-check-input" type="radio" name="gender" th:checked="${emp!=null}?${emp.gender==0}" value="0">
								<label class="form-check-label"></label>
							</div>
						</div>
						<div class="form-group">
							<label>department</label>
							<select class="form-control" name="department.id">
								<option th:value="${dept.id}" th:selected="${emp!=null}?${emp.department.id==dept.id}" th:each="dept:${depts}">[[${dept.departmentName}]]</option>

							</select>
						</div>
						<div class="form-group">
							<label>Birth</label>
							<input type="text" name="birth" class="form-control" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd')}" placeholder="zhangsan">
						</div>
						<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
					</form>

注意:<请求方式:post:请求员工添加 put:员工的修改

springmvc中:

1.配置请求方式:springmvc中配置hiddenHttpMethodFilter;将请求转换成指定的方式(springboot已配置好)
2.创建一个post页面表单
3.创建一个input项,name=_method,值就是指定的方式

<input type="hidden" name="_method" value="put" th:if="${emp!=null}">
<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>

区分修改和添加功能:如果emp是null则是添加,反之为修改;修改和添加按钮:

员工修改的controller:

 /*
     * @Author: jiatp
     * Description:员工的修改
    */
    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
        System.out.println("修改的员工数据"+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

4、CRUD-员工删除

删除按钮:

<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>

<form id="deleteEmpForm"  method="post">
		<input type="hidden" name="_method" value="delete"/>
</form>

<script>
			$(".deleteBtn").click(function(){
				//删除当前员工的
				$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
				return false;
			});
		</script>


点删除按钮时 每一行添加自定义属性attr="del_uri=@{/emp/}+${emp.id},用js提交表单,将自定义的属性添加到form表单action属性中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值