1、导入相关包
2、配置xml文件
<!-- 配置上传组件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
3、新建对象,提供get和set方法
4、Mapper文件中的映射关系及sql语句
映射关系
<resultMap type="Book" id="bookMap">
<result column="isbn" property="isbn"/>
<result column="book_name" property="bookName"/>
<result column="price" property="price"/>
<result column="publish_date" property="publishDate"/>
<result column="book_image" property="bookImage"/>
<result column="publisher" property="publisher"/>
<!-- <result column="category_id" property="category.id"/> -->
<association property="category" column="category_id"
javaType="Category" select="selectCategoryBook">
</association>
</resultMap>
insert语句
<insert id="addBook" parameterType="Book">
insert into book
values(#{isbn},#{bookName},#{price},#{bookImage},#{publishDate},#{publisher},#{category.id})
</insert>
查询语句(分页查询,具体看分页查询博客)
<select id="countForPager" parameterType="Pager" resultType="int">
select count(isbn) from book
<where>
<if test="param !=null and param.bookName !=null">
book_name like concat(concat("%",#{param.bookName}),"%")
</if>
<!-- 查询条件中的小于号或者大于号可以使用转义符号进行编写:小于 (<) ; 大于 (>)
或者使用cdata标号进行标志
-->
<if test="param !=null and param.price !=0.0">
price <= param.price
<!-- <![CDATA[price <= param.price]]> -->
<!-- price<![CDATA[<]]>= param.price -->
</if>
</where>
</select>
5、controller部分
@RequestMapping("/doadd")
//spring mvc可以把表单或url参数封装到一个对象中
//spring mvc可以把参数转换成基本数据类型,并封装到对象中
public String addBook(Model model,@Validated Book book,BindingResult result,MultipartFile file1,HttpServletRequest request) throws IllegalStateException, IOException {
//(网页)客户端提交数据到spring mvc后,会先进行数据的封装与转换,数据校验,完成后再进行控制器类进行处理
//可以使用校验框架进行数据的集中校验,并获取校验结果,根据校验结果,进行跳转控制
if (result.hasErrors()) {
//去除所有的校验错误或字段校验错误
List<ObjectError> errors = result.getAllErrors();
for(ObjectError error :errors) {
logger.debug(error.getObjectName());
}
//把异常信息传回页面进行显示
model.addAttribute("errors", errors);
return "addbook";
}
//通过表单验证后,执行上传
//如果文件不位空,写入上传路径
if(!file1.isEmpty()) {
//上传文件路径
String path = request.getServletContext().getRealPath("/uploads/");
//上传文件名
String filename = file1.getOriginalFilename();
String fileExt = filename.substring(filename.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();//随机UUID文件名
String newFile = uuid + fileExt;
File filepath = new File(path,newFile);
logger.info(newFile);
logger.info(filepath.getAbsolutePath());
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file1.transferTo(new File(path + File.separator + newFile));
//上传成功,保存上传后的文件路径到book对象中,在调用业务类保存到数据库中
book.setBookImage("uploads/"+ newFile);
}
// boolean r = new Random().nextInt(10)%2==1?true:false;
// if (r)
// throw new NullPointerException("模拟空指针异常");
boolean ret = IBookService.addBook(book);
//接收表单处理后,如果使用请求转发进行跳转会产生表单重复提交问题(刷新页面会重复提交)
//为了解决表单重复提交,在处理更新操作后,一般会执行重定向跳转
if (ret) {
// return "forward:/book/list.action";
return "redirect:/book/list.action";
}else {
// return "forward:/book/add.action";
return "redirect:/book/list.action";
}
}
6、页面部分
上传部分
<tr>
<td>封面图片:</td>
<!-- 文件上传时,文件域的名称不要与对象名一致,因为它们的类型不一致 ,spring mvc无法完成-->
<td><input name="file1" type="file" /></td>
</tr>
显示部分
<td><img height="60" alt="封面图片" src="${book.bookImage }"></td>
注意:照片上传到云服务器,本地路径为
D:\lsworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\BookStoreWeb\uploads