1.文件上传的必要前提

(1)form 表单的 enctype 取值必须是:multipart/form-data
(默认值是:application/x-www-form-urlencoded) enctype:是表单请求正文的类型
(2)method 属性取值必须是 Post
(3)提供一个文件选择域<input type=”file” />

2.文件上传环境搭建

(1)项目结构

(2)部分重要代码

<1>web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置前端控制器,让前端控制器去加载resources包下的springmvc.xml配置文件-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--全局的初始化参数-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!--配置解决中文乱码的过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

<2>spirngmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 -->
<context:component-scan base-package="lucky"/> <!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置控制器方法中return返回的字符串对应的同名文件所在目录-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--配置文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean> <!-- 开启SpringMVC框架注解的支持 -->
<mvc:annotation-driven/> </beans>

<3>index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<form action="/day19_fileupload/user/fileUploadTest01" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>

3.传统方式上传文件

package lucky.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID; @Controller
@RequestMapping(path = "/user")
public class UserController {
//传统方式上传文件
@RequestMapping(path = "/fileUploadTest01")
public String fileUploadTest01(HttpServletRequest request, HttpServletResponse response) throws Exception{
System.out.println("文件上传");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path); //查看文件上传的路径
// 判断,该路径是否存在
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";
}
}

 4.Springmvc方式文件上传

原理分析图:

package lucky.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID; @Controller
@RequestMapping(path = "/user")
public class UserController { /**
* springmvc方式上传文件
* 注意:请求参数MultipartFile upload 的名称upload必须与index.jsp中input标签的属性名一致,否则会造成空指针异常
* @return
*/
@RequestMapping(path = "/fileUploadTest02")
public String fileUploadTest02(HttpServletRequest request, MultipartFile upload) throws Exception{
System.out.println("springmvc文件上传");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path); //查看文件上传的路径
// 判断,该路径是否存在
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";
}
}

5.Springmvc异常处理

原理分析图:

(1)项目结构

(2)部分重要代码

<1>控制器类:UserController.java

package lucky.controller;

import lucky.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping(path = "/user")
public class UserController {
@RequestMapping(path = "/testException")
public String testException() throws CustomException {
System.out.println("testException执行了");
try {
//模拟异常
int a=10/0;
} catch (Exception e) {
//抛出自定义异常
throw new CustomException("被除数有问题");
}
return "success";
}
}

<2>自定义异常类

package lucky.exception;

/**
* 自定义异常类
*/
public class CustomException extends Exception{
//存储提示信息
private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public CustomException(String message) {
this.message = message;
}
}

<3>异常处理器:CustomExceptionResolver.java

package lucky.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 异常处理器
*/
public class CustomExceptionResolver implements HandlerExceptionResolver { /**
*处理异常的业务逻辑
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//获取异常对象
CustomException customException=null;
if(e instanceof CustomException){
customException= (CustomException) e;
}else {
customException=new CustomException("系统正在维护。。。");
}
//创建ModelAndView
ModelAndView mv=new ModelAndView();
mv.addObject("errormsg",e.getMessage());
mv.setViewName("error");
return mv;
}
}

<4>springmvc.xml文件中配置异常处理器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 -->
<context:component-scan base-package="lucky"/> <!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置控制器方法中return返回的字符串对应的同名文件所在目录-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--配置文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean> <!--配置异常处理器-->
<bean id="customExceptionResolver" class="lucky.exception.CustomExceptionResolver"/> <!-- 开启SpringMVC框架注解的支持 -->
<mvc:annotation-driven/> </beans>

<6>相关jsp页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="/day19_exception/user/testException">异常处理</a>
</body>
</html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>error.jsp</h3>
${errormsg}
</body>
</html>

(3)执行效果图

18 SpringMVC 文件上传和异常处理的更多相关文章

  1. 05 SpringMVC:02.参数绑定及自定义类型转换&&04.SpringMVC返回值类型及响应数据类型&&05.文件上传&&06.异常处理及拦截器

    springMVC共三天 第一天: 01.SpringMVC概述及入门案例 02.参数绑定及自定义类型转换 03.SpringMVC常用注解 第二天: 04.SpringMVC返回值类型及响应数据类型 ...

  2. SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库

    SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库  /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...

  3. springMVC文件上传大小超过限制的问题

    [转自]https://my.oschina.net/ironwill/blog/646762 springMVC是一个非常方便的web层框架,我们使用它的文件上传也非常的方便. 我们通过下面的配置来 ...

  4. springmvc文件上传AND jwt身份验证

    SpringMVC文件上传 思路:1.首先定义页面,定义多功能表单(enctype=“multipart/form-data”)2.在Controller里面定义一个方法,用参数(MultipartF ...

  5. springmvc文件上传下载简单实现案例(ssm框架使用)

    springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...

  6. 解决springMVC文件上传报错: The current request is not a multipart request

    转自:https://blog.csdn.net/HaHa_Sir/article/details/79131607 解决springMVC文件上传报错: The current request is ...

  7. TZ_06_SpringMVC_传统文件上传和SpringMVC文件上传方式

    1.传统文件上传方式 <!-- 文件上传需要的jar --> <dependency> <groupId>commons-fileupload</groupI ...

  8. SpringMVC文件上传下载(单文件、多文件)

    前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...

  9. SpringMVC 文件上传&拦截器&异常处理

    文件上传 Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的.Spring 用 Jakarta Commons FileUpload ...

随机推荐

  1. Implementing the Singleton Pattern in C#

    Table of contents (for linking purposes...) Introduction Non-thread-safe version Simple thread safet ...

  2. C++ auto 完成类型自动推导与使用

    c++11 允许声明一个变量或对象(object)而不需要指明其类型,只需说明它是auto. 1.如: auto i = 42: //i是整型 double   f(); auto d=f(); // ...

  3. vue使用插件的流程

    1.引入vue 2.引入插件 3.通过vue.use()调用 例子:使用router插件 import Vue from "vue"; import VueRouter from ...

  4. .NET 爬虫总结

    前言 技术本身并无罪,罪恶本质在于人心,好比厨师手中的菜刀用来创造美味佳肴,而杀手手上的刀却用来创造无限的罪恶. 环境 win7 IIS 6.0  SQLserver2012 .NET 4.0 win ...

  5. 小数据池 is和== 再谈编码

    昨日回顾 上节课内容回顾 1. 字典 {key:value, key:value.....} 成对的保存数据 字典没有索引. 不能切片, 字典的key必须是可哈希的.不可变的 1. 增加: dic[新 ...

  6. nginx return配置说明

    该指令一般用于对请求的客户端直接返回响应状态码.在该作用域内return后面的所有nginx配置都是无效的. 可以使用在server.location以及if配置中. 除了支持跟状态码,还可以跟字符串 ...

  7. 一种SpaceClaim抽取流道的方法——利用缺失的面功能

    针对不干净的几何,内部存在诸多碎面小缝隙,采用此方法可能会有较好的效果,不过需要耐心. 测试几何需要SpaceClaim19.0以上软件可以打开,下载链接: https://pan.baidu.com ...

  8. ubuntu之路——day17.4 卷积神经网络示例

    以上是一个识别手写数字的示例 在这个示例中使用了两个卷积-池化层,三个全连接层和最后的softmax输出层 一般而言,CNN的构成就是由数个卷积层紧跟池化层再加上数个全连接层和输出层来构建网络. 在上 ...

  9. 冰多多团队-第九次Scrum例会

    冰多多团队-第九次Scrum会议 工作情况 团队成员 已完成任务 待完成任务 zpj debug, IAT debug, IAT 牛雅哲 debug, IAT 接通新的语音识别接口和termux,完成 ...

  10. java 注解,动态代理

    秒懂,Java 注解 (Annotation)你可以这样学 深入理解Java注解类型(@Annotation) 注解可以理解为标签. 当开发者使用了Annotation 修饰了类.方法.Field 等 ...