拦截器
拦截器的作用就是拦截某些请求,进行特殊处理(例如业务判断等),根据处理结果来决定是否放行该请求。
在xml文件中配置mvc的拦截器
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截所有请求 -->
<mvc:mapping path="/**"/>
<bean class="com.xxx.interceptor.CommonInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
自定义的拦截器类继承了HandleInterceptor接口,但不必实现其中的方法,主要是覆写preHandle方法:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().contains("xxx")) {
return true;
}
if (request.getSession().getAttribute("username") != null) {
return true;
}
request.getRequestDispatcher("WEB-INF/jsp/xxx.jsp").forward(request, response);
return false;
}
以上拦截器表示对于包含xxx的请求以及请求的session中属性username不为空时,请求可以放行,否则跳转到xxx页面。
文件传输
配置pom依赖:
<!-- 文件上传依赖的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
</dependency>
文件上传,需要对表单中的enctype属性赋值为multipart/form-data,输入框的类型为file:
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
相应的Controller的方法为:
// 上传文件
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
String path = request.getServletContext().getRealPath("upload");
System.out.println("path is: " + path);
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
return "forward:/toMainPage";
}
这里直接用了Spring的CommonsMultipartFile类,在此之前需要导入相应的bean:
<!-- 配置文件上传的bean -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 编码必须与jsp的pageEncoding属性一致,默认并不是utf-8 -->
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
上述bean的id一般固定为multipartResolver,不要随意修改,否则影响上传功能,另外还配置了上传文件的最大size。上传的文件最终会出现在out/artifacts/项目名/upload/文件夹中。
下载文件的Controller方法为:
// 下载文件
@RequestMapping("/download")
@ResponseBody
public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getServletContext().getRealPath("download");
String fileName = "jquery-3.6.0.js";
// 设置response响应头
response.reset();
response.setCharacterEncoding("UTF-8");
// 传输数据
response.setContentType("multipart/form-data");
// 这里的UTF-8一定要大写,否则报错
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path, fileName);
System.out.println(file.getAbsolutePath());
try (InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
byte[] buff = new byte[1024];
int index = 0;
while ((index = inputStream.read(buff)) != -1 ) {
outputStream.write(buff, 0, index);
outputStream.flush();
}
}
return "forward:/toMainPage";
}
注意URLEncoder.encode方法中的第二个参数UTF-8必须大写,否则报错。要下载的原始文件所在的目录为web/download/,打包后在out/artifacts/项目名/download/下。
注意@RequestMapping注解了的方法返回值是jsp文件的名字,如果返回值加了forward:/或者redirect:/来转发或者重定向,那么表示返回请求,由相应的Controller类中的方法来处理。
上述的方法中用到了HttpServletRequest类,该类是javax.setvlet-api jar包中的类,而不是tomcat jar包中的类,注意不要导错包,否则会找不到getServletContext()方法。