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. 洛谷 P2577 [ZJOI2005]午餐 题解

    每日一题 day56 打卡 Analysis 算法:贪心+dp 容易想到贪心:吃饭慢的先打饭节约时间, 所以先将人按吃饭时间从大到小排序. 然后就是dp了: 首先,应该想到f[i][j][k]:前i个 ...

  2. 使用jpillora/dnsmasq 提供可视化管理的dns server

    实际开发中dns 是一个比较重要的组件,一般大家可能会选择使用dnsmasq 但是缺少UI可视化,有些人可能会选择powerdns jpillora/dnsmasq 是一个对于dnsmasq 的包装, ...

  3. json-server模拟服务器API

    一.npm安装 npm install --global json-server 二.使用:创建一个json数据文件,比如: { "students": [{ "id&q ...

  4. ABP 04 用户的创建

    有这样一个问题,我忘记了密码,查了一下数据那张表,是加密了的,然后就有了这篇文章了. 往后台传的时候,还是传的明文. 请求的地址:/api/services/app/User/Create 用户还是挺 ...

  5. Python 检查代码占用内存 工具和模块

    只介绍简单的使用, 更多使用方法请查看官方文档 tracemalloc 官方文档 tracemalloc文档地址 使用 import tracemalloc tracemalloc.start() # ...

  6. [Java] Spring boot 的maven设置阿里云仓库

    Spring boot 的maven设置阿里云仓库 打开根目录下的 pom.xml 文件,在对应为止出加入如下 红色 代码: <build> <plugins> <plu ...

  7. Linux 系统管理——Linux文件系统与日志

    1.inode 包含文件的元信息(1)inode 内容:文件的字节数.拥有者的 UID.GID.文件的读写执行权限.时间戳等,但不包含文件名.文件名是储存在目录的目录项中.(2)查看文件的 inode ...

  8. 第04组alpha冲刺(3/4)

    队名:斗地组 组长博客:地址 作业博客:Alpha冲刺(3/4) 各组员情况 林涛(组长) 过去两天完成了哪些任务: 1.收集各个组员的进度 2.写博客 展示GitHub当日代码/文档签入记录: 接下 ...

  9. nginx.conf 配置解析之文件结构

    nginx.conf配置文件结构如下: ...... #主要定义nginx的全局配置 events{ #events(事件)块:主要配置网络连接相关 } http{ #http块:代理缓存和日志定义绝 ...

  10. mysql优化查找执行慢的sql

    想要进行sql优化,肯定得先找出来需要优化的sql语句 一.mysql有一个自带的sql执行慢记录日志文件,所记录的日志取决于参数long_query_time控制,默认情况下long_query_t ...