week 6.22-6.28
- | Study-update |
---|---|
-Mon | 复习mvc |
-Tue | mvc文件上传 |
-Wes | Study-update |
-Thu | 端午快乐。 |
-Fri | spring配置druid |
-Sat | - |
-Sun | Study-update |
- | - |
6.23 Tuesday
文件上传
1.导包commons-fileupload
2.编写前端表单
注意
enctype=“multipart/form-data” type=“file”
<form action="${pageContext.request.contextPath}/book/upload2" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file">
<input type="submit" name="提交">
</form>
3.配置bean:multipartResolver
id为multipartResolver 否则会报错
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
4.Controller
普通IO保存文件
重点
//获取
String path = request.getSession().getServletContext().getRealPath("/upload");
//上传
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名
String originalFilename = file.getOriginalFilename();
//如果文件名为空
if ("".equals(originalFilename)) {
return "redirect:/book/allbook";
}
System.out.println("上传文件名为:" + originalFilename);
//保存地址
String path = request.getSession().getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("文件保存位置为:" + realPath);
//保存文件
InputStream inputStream = file.getInputStream();
OutputStream outputStream = new FileOutputStream(new File(realPath, originalFilename));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return "redirect:/book/allbook";
}
Transto方法
//transto方法
@RequestMapping("/upload2")
public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
String path = request.getSession().getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
//文件上传地址
System.out.println("上传保存地址为:" + path);
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
return "redirect:/book/allbook";
}
下载文件
@RequestMapping("/download")
public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
//要下载的文件地址
String path = request.getSession().getServletContext().getRealPath("/upload");
String fileName = "新建文本文档.txt";
//设置response响应头
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path, fileName);
//2、 读取文件--输入流
InputStream input = new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff = new byte[1024];
int index = 0;
//4、执行 写出操作
while ((index = input.read(buff)) != -1) {
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
6.26 Friday
配置druid
1.导入德鲁伊的依赖
2.在application.yaml配置数据源
spring:
datasource:
username: root
password: root
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/webtest?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
注意 这里的
专有配置得放在druid: 层级中,不然不识别。
3.导入log4j
4.配置专有数据源
package com.kuang.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
参考狂神文章学习
链接