步骤 1 : 先运行,看到效果,再学习 步骤 2 : 模仿和排错 步骤 3 : 效果 步骤 4 : 页面中的增加分类部分 步骤 5 : 为空判断 步骤 6 : CategoryMapper.xml 步骤 7 : CategoryMapper 步骤 8 : CategoryService 步骤 9 : CategoryServiceImpl 步骤 10 : UploadedImageFile 步骤 11 : ImageUtil工具类 步骤 12 : CategoryController 步骤 13 : 中文问题
老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。 采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。 推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。 这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来 这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
如图所示,新增加的分类,就是有图片的了。
增加分类的代码是整合在listCategory.jsp中的
需要注意几点: 1. method="post" 用于保证中文的正确提交 2. 必须有enctype="multipart/form-data",这样才能上传文件 3. accept="image/*" 这样把上传的文件类型限制在了图片 <div class="panel panel-warning addDiv">
<div class="panel-heading">新增分类</div>
<div class="panel-body">
<form method="post" id="addForm" action="admin_category_add" enctype="multipart/form-data">
<table class="addTable">
<tr>
<td>分类名称</td>
<td><input id="name" name="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">
<button type="submit" class="btn btn-success">提 交</button>
</td>
</tr>
</table>
</form>
</div>
<script>
$(function(){
$("#addForm").submit(function(){
if(!checkEmpty("name","分类名称"))
return false;
if(!checkEmpty("categoryPic","分类图片"))
return false;
return true;
});
});
</script>
<script> $(function(){ $("#addForm").submit(function(){ if(!checkEmpty("name","分类名称")) return false; if(!checkEmpty("categoryPic","分类图片")) return false; return true; }); }); </script>
在CategoryMapper.xml中新增加 插入分类的SQL语句
注: 需要加上2个属性:keyProperty="id" useGeneratedKeys="true" 以确保Category对象通过mybatis增加到数据库之后得到的id增长值会被设置在Category对象上。 因为在保存分类图片的时候需要用到这个id值,所以这一步是必须的。 <?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="com.how2java.tmall.mapper.CategoryMapper">
<select id="list" resultType="Category">
select * from category order by id desc
<if test="start!=null and count!=null">
limit #{start},#{count}
</if>
</select>
<select id="total" resultType="int">
select count(*) from category
</select>
<insert id="add" keyProperty="id" useGeneratedKeys="true" parameterType="Category" >
insert into category ( name ) values (#{name})
</insert>
</mapper>
<?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="com.how2java.tmall.mapper.CategoryMapper"> <select id="list" resultType="Category"> select * from category order by id desc <if test="start!=null and count!=null"> limit #{start},#{count} </if> </select> <select id="total" resultType="int"> select count(*) from category </select> <insert id="add" keyProperty="id" useGeneratedKeys="true" parameterType="Category" > insert into category ( name ) values (#{name}) </insert> </mapper>
新增add方法
package com.how2java.tmall.mapper;
import com.how2java.tmall.util.Page;
import com.how2java.tmall.pojo.Category;
import java.util.List;
public interface CategoryMapper {
List<Category> list(Page page);
int total();
void add(Category category);
}
package com.how2java.tmall.mapper; import com.how2java.tmall.util.Page; import com.how2java.tmall.pojo.Category; import java.util.List; public interface CategoryMapper { List<Category> list(Page page); int total(); void add(Category category); }
新增add方法
package com.how2java.tmall.service;
import com.how2java.tmall.pojo.Category;
import com.how2java.tmall.util.Page;
import java.util.List;
public interface CategoryService{
int total();
List<Category> list(Page page);
void add(Category category);
}
package com.how2java.tmall.service; import com.how2java.tmall.pojo.Category; import com.how2java.tmall.util.Page; import java.util.List; public interface CategoryService{ int total(); List<Category> list(Page page); void add(Category category); }
新增add方法的实现
package com.how2java.tmall.service.impl;
import com.how2java.tmall.util.Page;
import com.how2java.tmall.mapper.CategoryMapper;
import com.how2java.tmall.pojo.Category;
import com.how2java.tmall.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
CategoryMapper categoryMapper;
@Override
public List<Category> list(Page page) {
return categoryMapper.list(page);
}
@Override
public int total() {
return categoryMapper.total();
}
@Override
public void add(Category category) {
categoryMapper.add(category);
}
}
新增UploadedImageFile ,其中有一个MultipartFile 类型的属性,用于接受上传文件的注入。
注: 这里的属性名称image必须和页面中的增加分类部分中的type="file"的name值保持一致。 <input id="categoryPic" accept="image/*" type="file" name="image" /> package com.how2java.tmall.util;
import org.springframework.web.multipart.MultipartFile;
public class UploadedImageFile {
MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
package com.how2java.tmall.util; import org.springframework.web.multipart.MultipartFile; public class UploadedImageFile { MultipartFile image; public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } }
ImageUtil 工具类提供3个方法
1. change2jpg 确保图片文件的二进制格式是jpg。 仅仅通过ImageIO.write(img, "jpg", file);不足以保证转换出来的jpg文件显示正常。这段转换代码,可以确保转换后jpg的图片显示正常,而不会出现暗红色( 有一定几率出现)。 我也是度娘上抄的,哈哈哈~ 不过找了很多代码哦,才找到这一段能真正生效,而且不会发生错误的。 2. 后两种resizeImage用于改变图片大小,在上传产品图片的时候会用到。 这里不展开,到时候再讲 package com.how2java.tmall.util;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.PixelGrabber;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtil {
public static BufferedImage change2jpg(File f) {
try {
Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath());
PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true);
pg.grabPixels();
int width = pg.getWidth(), height = pg.getHeight();
final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null);
return img;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void resizeImage(File srcFile, int width,int height, File destFile) {
try {
if(!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
Image i = ImageIO.read(srcFile);
i = resizeImage(i, width, height);
ImageIO.write((RenderedImage) i, "jpg", destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Image resizeImage(Image srcImage, int width, int height) {
try {
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
return buffImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
CategoryController新增add方法
1. add方法映射路径admin_category_add的访问 1.1 参数 Category c接受页面提交的分类名称 1.2 参数 session 用于在后续获取当前应用的路径 1.3 UploadedImageFile 用于接受上传的图片 2. 通过categoryService保存c对象 3. 通过session获取ControllerContext,再通过getRealPath定位存放分类图片的路径。 如果严格按照本教程的做法,使用idea中的tomcat部署的话,那么图片就会存放在:E:\project\tmall_ssm\target\tmall_ssm\img\category 这里 4. 根据分类id创建文件名 5. 如果/img/category目录不存在,则创建该目录,否则后续保存浏览器传过来图片,会提示无法保存 6. 通过UploadedImageFile 把浏览器传递过来的图片保存在上述指定的位置 7. 通过ImageUtil.change2jpg(file); 确保图片格式一定是jpg,而不仅仅是后缀名是jpg. 8. 客户端跳转到admin_category_list
@RequestMapping("admin_category_add")
public String add(Category c, HttpSession session, UploadedImageFile uploadedImageFile) throws IOException {
categoryService.add(c);
File imageFolder= new File(session.getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,c.getId()+".jpg");
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
uploadedImageFile.getImage().transferTo(file);
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
return "redirect:/admin_category_list";
}
package com.how2java.tmall.controller;
import com.how2java.tmall.pojo.Category;
import com.how2java.tmall.service.CategoryService;
import com.how2java.tmall.util.ImageUtil;
import com.how2java.tmall.util.Page;
import com.how2java.tmall.util.UploadedImageFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
CategoryService categoryService;
@RequestMapping("admin_category_list")
public String list(Model model,Page page){
List<Category> cs= categoryService.list(page);
int total = categoryService.total();
page.setTotal(total);
model.addAttribute("cs", cs);
model.addAttribute("page", page);
return "admin/listCategory";
}
@RequestMapping("admin_category_add")
public String add(Category c, HttpSession session, UploadedImageFile uploadedImageFile) throws IOException {
System.out.println(c.getId());
categoryService.add(c);
System.out.println(c.getId());
File imageFolder= new File(session.getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,c.getId()+".jpg");
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
System.out.println(uploadedImageFile);
System.out.println(uploadedImageFile.getImage());
System.out.println(file);
uploadedImageFile.getImage().transferTo(file);
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
return "redirect:/admin_category_list";
}
}
中文问题,统一交由web.xml 中定义的org.springframework.web.filter.CharacterEncodingFilter来进行处理
其他的配合动作 1. 在jsp中要加上 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> 其中contentType="text/html; charset=UTF-8"的作用是告诉浏览器提交数据的时候,使用UTF-8编码 2. 在form里method="post" 才能正确提交中文 参考: 使用Filter处理中文问题
HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。
![]() |