Spring引入C3P0连接池
导入c3p0依赖
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
Spring文件中配置
<!-- 加载外部配置文件properties 读取配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
mybatis配置log4j实现
导入依赖资源包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
mybatis配置
<setting name="logImpl" value="LOG4J"/>
log4j.properties配置文件
# 将等级为DEBUG的日志信息输出到控制台(console)、文件(file)两个目的地
log4j.rootLogger=DEBUG,console,file
# 输出到控制台的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.Encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss} %l - %m%n
# 输出到文件的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/test.log
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%c]-%m%n
# 设置日志的输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
spring数据源替换alibaba.druid
导入依赖资源包
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
druid.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sqltest?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
spring文件中配置
<!-- 引入druid连接池配置文件 -->
<context:property-placeholder location="druid.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
替换继承SqlSessionDaoSupport
我们不再需要将dao层接口创建实现类,并继承SqlSessionDaoSupport,然后调用getsqlSession方法去执行,而是可以直接动态的将接口注册进入spring容器当中去,如下配置
<!-- 配置dao层接口扫描 动态实现将dao接口注入到spring容器中 -->
<!-- 将所有接口注册到映容器中 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.yuqu.dao"/>
</bean>
然后直接获取业务层的Bean即可。理解的话就是,我们将接口注册进容器,那么就不再依赖于实现类执行。并且在配置dao层接口扫描时,将sqlSessionFactory或者SqlSessionTemplate注入进去即可
<!-- 上述配置完成之后 -->
<!-- service层的spring配置 -->
<bean id="bookService" class="com.yuqu.service.BookServiceImpl">
<!-- 或者将注入bookMapper替换为注解实现 @AutoWired -->
<property name="bookMapper" ref="bookMapper"/>
</bean>
如此以来就剩下了创建dao层接口实现类的步骤,建议这样做。接口太多的话都创建实现类并实现方法会产生大量代码冗余,没有必要
spring文件上传
文件上传导包:
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
jsp:
<form method="post" action="${pageContext.request.contextPath}/file/upload2" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传">
</form>
spring配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限 -->
<property name="maxInMemorySize" value="40960"/>
<property name="maxUploadSize" value="10485760"/>
</bean>
方式一:
FileController
// 文件上传
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws IOException {
// 获取文件名
String filename = file.getOriginalFilename();
// 文件名为空
if ("".equals(filename)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名称="+filename);
// 上传路径保存
String path = req.getServletContext().getRealPath("/upload");
File realPath = new File(path);
// 路径不存在就创建一个
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址"+realPath);
InputStream inputStream = file.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File(realPath,filename));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
return "redirect:/index.jsp";
}
方式二
@RequestMapping("/upload2")
public String upload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req) throws IOException {
// 保存上传路径
String path = req.getServletContext().getRealPath("/upload2");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件地址="+ realPath);
//写文件
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:/index.jsp";
}
文件下载
@RequestMapping("/download")
public String download(@RequestParam("filename") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("文件名="+ fileName);
// 1. 根据下载相对目录获取下载目录在服务器部署之后绝对目录
String realPath = request.getSession().getServletContext().getRealPath("/down");
// 2. 通过文件输入流读取文件
FileInputStream is = new FileInputStream(new File(realPath, fileName));
// 3. 获取响应输出流
response.setContentType("text/plain;charset=UTF-8");
// 4. 附件下载 attachment 附件 inline 在线打开(默认值)
response.setHeader("content-disposition", "attachment;fileName=" + fileName);
// 5. 处理下载流复制
ServletOutputStream os = response.getOutputStream();
int len;
byte[] b = new byte[1024];
while(true){
len = is.read(b);
if(len == -1) break;
os.write(b, 0, len);
}
// 释放资源
os.close();
is.close();
return "redirect:/index.jsp";
}
jsp
<a href="${pageContext.request.contextPath}/file/download?filename=pp.jpg">点击下载</a>