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. IDEA连接数据库之后,无法自动找到表

    在用IDEA连接数据库之后,在查询的时候无法自动关联出表,就如下图的提示所示: 这样看着很不舒服,按照如下设置就可以联想出表了: 点击第一个勾,关联所有: 然后就可以关联到表了

  2. http响应消息

    1. 请求消息:客户端发送给服务器端的数据 * 数据格式: 1. 请求行 2. 请求头 3. 请求空行 4. 请求体 2. 响应消息:服务器端发送给客户端的数据 * 数据格式: 1. 响应行 1. 组 ...

  3. 前端零基础入门:页面结构层HTML(3)

    搭建网页HTML结构 标签 标签 块级标签 和 行内标签 标签嵌套规则 和 div css 标签是一个区块容器标记, 之间是一个容器,可以包含段落,表格,图片等各种HTML元素. 标签没有实际意义,为 ...

  4. MyBatis试题

    在使用MyBatis的时候,除了可以使用@Param注解来实现多参数入参,还可以用()传递多个参数值. (选择一项) A.用Map对象可以实现传递多参数值 B.用List对象可以实现传递多参数值 C. ...

  5. Navicat自动断开连接处理方式

    问题描述 使用Navicat连接mysql后,如果一段时间不操作,那么会再次操作时会提示无响应,每次都这样确实折磨人,大大降低了工作效率! 问题解决 关闭连接→右键连接→连接属性 将上述心跳时间设置为 ...

  6. kubernetes --- weave

    #wget 'https://cloud.weave.works/launch/k8s/weavescope.yaml?k8s-service-type=NodePort&k8s-versio ...

  7. 【Beta】Scrum meeting 9

    目录 写在前面 进度情况 任务进度表 Beta-1阶段燃尽图 遇到的困难 照片 commit记录截图 文档集合仓库 后端代码仓库 技术博客 写在前面 例会时间:5.13 22:30-22:45 例会地 ...

  8. [Beta阶段]第十一次Scrum Meeting

    Scrum Meeting博客目录 [Beta阶段]第十一次Scrum Meeting 基本信息 名称 时间 地点 时长 第十一次Scrum Meeting 19/05/20 大运村寝室6楼 15mi ...

  9. leetcode:124. 二叉树中的最大路径和

    题目描述: 给定一个非空二叉树,返回其最大路径和. 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列.该路径至少包含一个节点,且不一定经过根节点. 示例 1: 输入: [1,2,3] 1 ...

  10. Java Thread dump 日志分析

    jstack Dump 日志文件中的线程状态 dump 文件里,值得关注的线程状态有: 死锁,Deadlock(重点关注)  执行中,Runnable 等待资源,Waiting on conditio ...