本文进行对象的编辑和提交功能
对分类对象进行编辑和提交
操作思路
在CategoryMapper中增加sql语句
1
2
3
4
5
6
7
8
9<!-- 通过id获取Category对象 -->
<select id="get" resultType="Category">
select * from category where id = #{id}
</select>
<!-- 提交数据 -->
<update id="update" parameterType="Category">
update category set name = #{name} where id = #{id}
</update>在CategoryMapper/CategoryService/CategoryServiceImpl中增加get和update方法,代码略
在listCategory.jsp中增加edit的超链接。效果:网页上点击图标,进入admin_category_edit链接,并传入id
1
2
3
4
5
6<td>
<a href="admin_category_edit?id=${c.id}">
<span class="glyphicon glyphicon-edit"/>
</a>
</td>
更新CategoryController,新增get和update方法。
get方法中,由注入的id值获得对应的Category对象c,将c注入model后跳转admin/editCategory.jsp。
update方法解释见步骤6。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22//触发编辑,不包含提交操作
@RequestMapping("admin_category_edit")
public String get(int id,Model model) throws IOException {
Category c=categoryService.get(id);
model.addAttribute("c",c);
return "admin/editCategory";
}
//编辑后的提交操作
@RequestMapping("admin_category_update")
public String update(Category c,HttpSession session,UploadedImageFile uploadedImageFile)throws IOException {
categoryService.update(c);
MultipartFile image=uploadedImageFile.getImage();
if(null!=image && !image.isEmpty()) {
File imageFolder=new File(session.getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,c.getId()+".jpg");
image.transferTo(file);
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
}
return "redirect:/admin_category_list";
}新增editCategory.jsp。CategoryController的get方法会跳转到此jsp文件,同时浏览器上弹出编辑页面。此时id和name已被注入,但 id为隐藏字段,不会被修改。浏览器上点击提交后,URL被CategoryController的update方法捕获
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33<div class="workingArea">
<ol class="breadcrumb">
<li><a href="admin_category_list">所有分类</a></li>
<li class="active">编辑分类</li>
</ol>
<div class="panel panel-warning editDiv">
<div class="panel-heading">编辑分类</div>
<div class="panel-body">
<form method="post" id="editForm" action="admin_category_update" enctype="multipart/form-data">
<table class="editTable">
<tr>
<td>分类名称</td>
<td><input id="name" name="name" value="${c.name}" type="text" class="form-control"></td>
</tr>
<tr>
<td>分类圖片</td>
<td>
<input id="categoryPic" accept="image/*" type="file" name="image" />
</td>
</tr>
<tr class="submitTR">
<td colspan="2" align="center">
<input type="hidden" name="id" value="${c.id}">
<button type="submit" class="btn btn-success">提 交</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>此时Category对象c和HttpSession对象session以及工具类UploadedImageFile对象被注入,调用CategoryService.update()方法将c内的name更新入数据库中。
然后获取MultipartFile对象image。若image引用存在且内容不为空,则将上传的图片改为jpg格式存入文件系统。最后重定向到admin_category_list.jsp
