留言板项目笔记
servlet接收网页提交的文件
在网页中使用jquery.ajax提交文件
<input type="file" name="file" id="file">
<button onclick="submitFile()">
<script>
function submitFile() {
const fd = new FormData();
const file = document.getElementById('file').files[0];
if (!file) return;
fd.append('file', file);
$.ajax('/getfile', {
method: 'post',
data: fd,
success(res) {
console.log('提交成功');
},
processData: false,
contentType: false,
dataType: 'json',
});
}
</script>
在要接收文件的<servlet>
标签下中添加
<multipart-config>
<!-- 文件大小限制 -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
从HttpServletRequest中获取文件并保存
public boolean getFile(HttpServletRequest req) {
try {
// 获取file部分
Part part = req.getParts().stream()
.map(e -> (ApplicationPart) e)
.filter(e -> "file".equals(e.getName()))
.findFirst().orElse(null);
if (part == null) return false;
// 获取提交的文件名
String fileName = part.getSubmittedFileName();
// 保存文件
FileOutputStream fos = new FileOutputStream(fileName);
part.getInputStream().transferTo(fos);
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Spring 通过注解从properties文件中注入参数
db.properties文件
db.url=jdbc:mysql://127.0.0.1/jredu
db.driver=com.mysql.jdbc.Driver
db.userName=root
db.passWord=root
在要注入的类上方添加注解
@Repository("testClass")
@PropertySource("classpath:db.properties");
在要注入的参数前添加注解
TestClass(@Value("\${db.userName}") String userName,
@Value("\${db.passWord}") String passWord,
@Value("\${db.driver}") String driver,
@Value("\${db.url}") String url) {
// ...
}
在applicationContext.xml中添加
<!-- TestClass所在包 -->
<context:component-scan base-package="com.jredu.test"/>
获取对象
ClassPathXmlApplicationContext ctx = ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestClass testClass = ctx.getBean("testClass");