文件上传
传统文件上传
index.jsp
<body>
<h3>传统文件上传</h3>
<form action="user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
<body>
接收文件的类
@RequestMapping("/fileupload1")
public String fileuoload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传...");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
// 判断,该路径是否存在
File file = new File(path);
if(!file.exists()){
// 创建该文件夹
file.mkdirs();
}
// 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
// 遍历
for(FileItem item:items){
// 进行判断,当前item对象是否是上传文件项
if(item.isFormField()){
// 说明普通表单向
}else{
// 说明上传文件项
// 获取上传文件的名称
String filename = item.getName();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成文件上传
item.write(new File(path,filename));
// 删除临时文件
item.delete();
}
}
return "success";
}
使用Spring配置上传
- 这里面的name,要和 public String fileuoload2(HttpServletRequest request, MultipartFile upload)的upload对应
<h3>Springmvc文件上传</h3>
<form action="/user/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
文件上传类
@RequestMapping("/fileupload2")
public String fileuoload2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("springmvc文件上传...");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
// 判断,该路径是否存在
File file = new File(path);
if(!file.exists()){
// 创建该文件夹
file.mkdirs();
}
// 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成文件上传
upload.transferTo(new File(path,filename));
return "success";
}
跨服务器方式的文件
- 优点:实现不同的功能,速度更加快,常见的有应用服务器,数据库服务器,缓存和消息处理服务器,文件服务器
- 不是往自己服务器上的文件夹写文件
@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
// 定义上传,另一个服务器路径
String path = "http://localhost:9090/untitled_war/uploads/";
// 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
// 上传文件
webResource.put(upload.getBytes());
return "success";
}
异常处理
- 出错时,利用异常处理器,用户可以看到提示
bean文件
- throw对象的时候调用SysExceptionResolver方法
<!--异常处理器-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/>
控制器的类
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws Exception{
System.out.println("testException");
try {
int a=10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查询所有用户出现了错误...");
}
return "success";
}
}
SysException类
public class SysException extends Exception {
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
调用SysExceptionResolver 方法
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
SysException e=null;
//判断异常对象的类型
if(ex instanceof SysException){
e=(SysException)ex;
}
else{
e=new SysException("系统正在维护");
}
//创建视图页面
ModelAndView mv=new ModelAndView();
//id为errorMsg, mv.addObject存储到了session域里面
mv.addObject("errorMsg",e.getMessage());
//跳转的页面
mv.setViewName("error");
return mv;
}
}
用户层显示错误的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
拦截器
- 先执行拦截器的方法,放行以后,再执行controller的方法
- true放行,false不放行
拦截器的bean配置
<!--异常处理器-->
<mvc:interceptors>
<mvc:interceptor>
<!--拦截器路径-->
<mvc:mapping path="/user/*"/>
<!--拦截器对象,执行拦截器对象里的方法-->
<bean class="cn.itcast.inter.Inter"/>
</mvc:interceptor>
</mvc:interceptors>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>拦截器</h3>
<a href="user/Inter">异拦截器</a>
</body>
</html>
拦截器调用的方法
public class Inter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor1执行了");
return true;
}
}