该笔记包含以下内容:SpringBoot整合Servlet&Filter&Listener、SpringBoot文件上传
最近在做一个小的单体CRUD Demo,所以没有太多的东西去整理
SpringBoot整合Servlet&Filter&Listener
SpringBoot整合Servlet
准备一个Servlet1
2
3
4
5
6
7
8
9"myServlet",urlPatterns = "/srv",loadOnStartup = 1) (name =
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("111");
}
}
在启动类中添加注解1
2
3
4
5
6
7
8
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
SpringBoot整合Filter
准备一个Filter
这里copy了一个过滤url的Filter,用来判断用户访问的url是否需要做权限校验
1 | /** |
同样在启动类中添加注解1
2
3
4
5
6
7
8
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
SpringBoot整合Listener
准备一个Listener1
2
3
4
5
6
7
8
9
10
11
public class FirstListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce) {
System.out.println("init .. ");
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("desroyed .. ");
}
}
同样在启动类中添加注解1
2
3
4
5
6
7
8
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
SpringBoot文件上传
相关配置
application.properties1
2
3
4
5
6
7
8
9
10
11# Spring Boot 1.4.x and 1.5.x
# 配置单个文件最大限制
spring.http.multipart.maxFileSize=200MB
# 配置请求总数据大小限制
spring.http.multipart.maxRequestSize=200MB
# Spring Boot 2.x
# 配置单个文件最大限制
spring.servlet.multipart.max-file-size = 200MB
# 配置请求总数据大小限制
spring.servlet.multipart.max-request-size = 200MB
html示例
1 | <form action="fileUploadController" method="post" enctype="multipart/form-data"> |
Controller示例
1 | "/fileUploadController") ( |
通常在使用SpringBoot时,我们会将工程打包为jar文件部署,此时上传文件可能会出现路径问题
有一种解决方案就是我们在application配置文件中设置好静态文件的目录,并将上传后的文件保存到该目录中1
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:c:/upload/
1 | /** |