Spring学习笔记 - 第009天
2017-03-27 本文已影响0人
迷茫o
Spring Web MVC
上传图片
1.方法参数
MultipartFile photo
2.根据servlet上下文获得存放图片的真实路径
ServletContext context = req.getServletContext();
String path = context.getRealPath("/images");
3.根据自定义工具类生产UUID格式的字符串图片文件名
String filename = CommonUtil.getRandomFileName(photo.getOriginalFilename());
4.根据photo的方法上传图片
photo.transferTo(new File(path + "/" + filename));
配置spring自带的编码过滤器
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
CharacterEncodingFilter这个类有encoding的属性来设置编码格式
解决延迟加载和会话关闭的矛盾
方法一:配置OpenSessionInViewFilter过滤器延迟会话的生命周期
<filter>
<filter-name>osiv</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>osiv</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
方法二:在业务层需要解决的方法里直接初始化数据
if (!Hibernate.isInitialized(user)) {
Hibernate.initialize(user);
}