三层架构
表现层:负责数据展示
业务层:负责业务处理
数据层:负责数据操作
概念
Spring MVC 是Spring提供的一个实现了Web MVC设计模式的轻量级Web框架。
MVC(Model View Controller),一种用于设计创建Web应用程序表现层的模式
Model(模型):数据模型,用于封装数据
View(视图):页面视图,用于展示数据
Controller(Handle 处理器):处理用户交互的调度器,用于根据用户需求处理程序逻辑
<span style="background-color:#f8f8f8"><span style="color:#333333"><dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
?
<!-- servlet3.1规范的坐标 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!--spring的坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring web的坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--springmvc的坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency></span></span>
<span style="background-color:#f8f8f8"><span style="color:#333333"><span style="color:#555555">@Controller</span>
<span style="color:#770088">public</span> <span style="color:#770088">class</span> <span style="color:#0000ff">UserController</span> {
? ?<span style="color:#555555">@RequestMapping</span>(<span style="color:#aa1111">"/save"</span>)
? ?<span style="color:#770088">public</span> <span style="color:#008855">String</span> <span style="color:#000000">say</span>(){
? ? ? ?<span style="color:#000000">System</span>.<span style="color:#000000">out</span>.<span style="color:#000000">println</span>(<span style="color:#aa1111">"你好"</span>);
? ? ? ?<span style="color:#770088">return</span> <span style="color:#aa1111">"a.jsp"</span>;
? }
}</span></span>
<span style="background-color:#f8f8f8"><span style="color:#333333"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
? ? ? 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/context
? ? ? http://www.springframework.org/schema/context/spring-context.xsd
? ">
?
? <context:component-scan base-package="com.xinzhi"/>
</beans></span></span>
<span style="background-color:#f8f8f8"><span style="color:#333333"><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*:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping></span></span>
注意如果报找不到包: mvn idea:module
服务器启动
加载web.xml中DispatcherServlet
读取spring-mvc.xml中的配置,加载所有com.xinzhi包中所有标记为bean的类
读取bean中方法上方标注@RequestMapping的内容
处理请求
DispatcherServlet配置拦截所有请求 /
使用请求路径与所有加载的@RequestMapping的内容进行比对
执行对应的方法
根据方法的返回值在webapp目录中查找对应的页面并展示
web三大组件有 处理器映射,处理器适配器, 视图解析器
1 dispatcherServlet 前置控制器,负责接收并处理所有的web请求,根据handlerMapping(处理器映射)找到具体的Controller(处理器),由controller完成具体的处理逻辑。
2 HandlerMapping(处理器映射器):负责处理web请求和具体的Controller之间的映射关系匹配。
3HandlerAdapter(处理器适配器) 通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。 主要处理方法参数、相关注解、数据绑定、消息转换、返回值、调用视图解析器等等。
4.Controller(处理器):DispatherServlet的次级控制器,web请求的具体处理者。DispatherServlet获得handlerMapping的返回结果后,调用controller的处理方法处理当前的业务请求,处理完成后返回ModelAndView对象。
5 ViewResolver( 视图解析器):用来处理视图名与具体的view实例之间的映射对应关系。根据ModelAndView中的视图名查找相应的View实现类,然后将查找的结果返回给DispatcherServlet,DispatcherServlet最终会将ModelAndView中的模型数据交给返回的View处理最终的视图渲染工作。
Springmvc架构原理解析 第一步:发起请求到前端控制器(DispatcherServlet) 第二步:前端控制器请求HandlerMapping查找 Handler,可以根据xml配置、注解进行查找 第三步:处理器映射器HandlerMapping向前端控制器返回Handler 第四步:前端控制器调用处理器适配器去执行Handler 第五步:处理器适配器去执行Handler 第六步:Handler执行完成给适配器返回ModelAndView 第七步:处理器适配器向前端控制器返回ModelAndView ModelAndView是springmvc框架的一个底层对象,包括 Model和view 第八步:前端控制器请求视图解析器去进行视图解析 根据逻辑视图名解析成真正的视图(jsp) 第九步:视图解析器向前端控制器返回View 第十步:前端控制器进行视图渲染 视图渲染将模型数据(在ModelAndView对象中)填充到request域 第十一步:前端控制器向用户响应结果
1 默认类型:
直接放在参数上就可以使用的数据,HttpServletRequest
2 简单类型:
直接将简单类型的数据放在方法里,如果前端参数和后端参数名字一样,自动匹配;
名字不一样:@RequsetParam(“前端的值”) 就可以将前传的值和后端参数映射
3 对象 :
前端的参数要和对象的属性名称必须一致,会自动封装。
4 对象嵌套:
参数和对象的属性名称一致,前端参数对象子属性必须(子对象.属性)
5 自定义数据的绑定
5.1 编写转换器类,作用是将前端的数据类型转换成后端的数据类型,继承converter
5.2 配置文件中,添加转化器驱动
6 数组
前端数组中是简单类型的数据,那么前端数组中的name要和后端数组名称一致
7 集合
后端接受的对象是含有List<对象>属性的,那么前端的name值格式要和后端list属性名称一致,而且用索引的格式 list[0].属性(list集合里对象的属性名称)
<span style="background-color:#f8f8f8"><span style="color:#333333"><strong><span style="color:#0000ff"># 1 默认类型:</span></strong>
@RequestMapping("/m1")
? ?<span style="color:#aa5500">public ModelAndView say(HttpServletRequest request, ModelAndView modelAndView){</span>
? ? ? ?<span style="color:#aa5500">String name = request.getParameter("name");</span>
? ? ? ?<span style="color:#aa5500">System.out.println(name);</span>
? ? ? ?<span style="color:#aa5500">modelAndView.setViewName("a.jsp");</span>
? ? ? ?<span style="color:#aa5500">modelAndView.addObject("name", name);</span>
? ? ? ?<span style="color:#aa5500">return modelAndView;</span>
}
?
jsp页面中要引入
<u><span style="color:#0000cc"><%@ page isELIgnored="false"%></span></u>
<u><span style="color:#0000cc"><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%></span></u>
?
<span style="color:#117700"><</span><span style="color:#117700">body</span><span style="color:#117700">></span>
? ${name}
<span style="color:#117700"></</span><span style="color:#117700">body</span><span style="color:#117700">></span>
?
<strong><span style="color:#0000ff"># 简单类型:</span></strong> ?
@RequestMapping("/m2")
? ?<span style="color:#aa5500">public String say2(@RequestParam("username") String name, String age){</span>
? ? ? ?<span style="color:#aa5500">System.out.println(name);</span>
? ? ? ?<span style="color:#aa5500">System.out.println(age);</span>
? ? ? ?<span style="color:#aa5500">return "a.jsp";</span>
}
?
<strong><span style="color:#0000ff"># 对象类型</span></strong>
@RequestMapping("/m3")
? ?<span style="color:#aa5500">public String say3(Student student){</span>
? ? ? ?<span style="color:#aa5500">System.out.println(student);</span>
? ? ? ?<span style="color:#aa5500">return "b.jsp";</span>
}
访问路径: http://localhost:8080/webdemo_war/m4?id=1&num=111122223333&user.age=11&user.username=%E9%9F%A9%E5%93%A5%E5%93%A5
?
<strong><span style="color:#0000ff"># 数组</span></strong>
@RequestMapping("/m5")
? ?<span style="color:#aa5500">public String say5(Integer[] ids){</span>
? ? ? ?<span style="color:#aa5500">if(ids!=null){</span>
? ? ? ? ? ?<span style="color:#aa5500">for (Integer id : ids) {</span>
? ? ? ? ? ? ? ?<span style="color:#aa5500">System.out.println(id);</span>
? ? ? ? ? ?<span style="color:#aa5500">}</span>
? ? ? ?<span style="color:#aa5500">}</span>
? ? ? ?<span style="color:#aa5500">return "b.jsp";</span>
? ?<span style="color:#aa5500">}</span>
访问路径:http://localhost:8080/webdemo_war/m5?ids=1&ids=2
?
<strong><span style="color:#0000ff"># list类型</span></strong>
@RequestMapping("/m6")
? ?<span style="color:#aa5500">public String say6(@RequestParam("hobby")List<String> hobby){</span>
? ? ? ?<span style="color:#aa5500">System.out.println(hobby);</span>
? ? ? ?<span style="color:#aa5500">return "b.jsp";</span>
}
http://localhost:8080/webdemo_war/m6?hobby=%E6%B8%B8%E6%B3%B3&hobby=%E6%B3%A1%E5%A6%9E
注意: SpringMVC默认将List作为对象处理,赋值前先创建对象,然后将hobby作为对象的属性进行处理。由于
List是接口,无法创建对象,报无法找到构造方法异常;修复类型为可创建对象的ArrayList类型后,对象可
以创建,但没有hobby属性,因此数据为空。此时需要告知SpringMVC的处理器hobby是一组数据,而不是一个单
一数据。通过@RequestParam注解,将数量大于1个names参数打包成参数数组后, SpringMVC才能识别该数
据格式,并判定形参类型是否为数组或集合,并按数组或集合对象的形式操作数据。
?
?
?
RequestParam 当前端传过来的参数和后端的参数名称不一样的时候,可以让他们映射起来</span></span>
自定义数据绑定
定义转换器
<span style="background-color:#f8f8f8">public class MyDateConverter implements Converter<String, Date> {
?
? @Override
? public Date convert(String s) {
? ? ? DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
? ? ? Date date = null;
? ? ? try {
? ? ? ? ? date = df.parse(s);
? ? ? } catch (ParseException e) {
? ? ? ? ? e.printStackTrace();
? ? ? }
? ? ? return date;
? }
}</span>
注解驱动,使转换器起作用
<span style="background-color:#f8f8f8"><!--1.将自定义Converter注册为Bean,受SpringMVC管理-->
<bean id="myDateConverter" class="com.xinzhi.converter.MyDateConverter"/>
<!--2.设定自定义Converter服务bean-->
<bean id="conversionService"
? ? class="org.springframework.context.support.ConversionServiceFactoryBean">
? <!--3.注入所有的自定义Converter,该设定使用的是同类型覆盖的思想-->
? <property name="converters">
? ? ? <!--4.set保障同类型转换器仅保留一个,去重规则以Converter<S,T>的泛型为准-->
? ? ? <set>
? ? ? ? ? <!--5.具体的类型转换器-->
? ? ? ? ? <ref bean="myDateConverter"/>
? ? ? </set>
? </property>
</bean>
<!--开启注解驱动,加载自定义格式化转换器对应的类型转换服务-->
<mvc:annotation-driven conversion-service="conversionService"/></span>
controller返回值是String return "forward:page.jsp";
controller返回值是String return "redirect:page.jsp";
<span style="background-color:#f8f8f8"><span style="color:#333333"><strong><span style="color:#0000ff"># 展示页面的保存位置通常固定,且结构相似,可以设定通用的访问路径,简化页面配置格式</span></strong>
<span style="color:#117700"><</span><span style="color:#117700">bean</span> <span style="color:#0000cc">class</span>=<span style="color:#aa1111">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span><span style="color:#117700">></span>
? ?<span style="color:#117700"><</span><span style="color:#117700">property</span> <span style="color:#0000cc">name</span>=<span style="color:#aa1111">"prefix"</span> <span style="color:#0000cc">value</span>=<span style="color:#aa1111">"/WEB-INF/page/"</span><span style="color:#117700">/></span>
? ?<span style="color:#117700"><</span><span style="color:#117700">property</span> <span style="color:#0000cc">name</span>=<span style="color:#aa1111">"suffix"</span> <span style="color:#0000cc">value</span>=<span style="color:#aa1111">".jsp"</span><span style="color:#117700">/></span>
<span style="color:#117700"></</span><span style="color:#117700">bean</span><span style="color:#117700">></span></span></span>
是一种动态拦截方法调用的机制
<span style="background-color:#f8f8f8"><span style="color:#333333"># 作用:
1. 在指定的方法调用前后执行预先设定后的的代码
2. 阻止原始方法的执行
# 核心原理:
AOP思想
# 拦截器链:
多个拦截器按照一定的顺序,对原始被调用功能进行增强 </span></span>
?
<span style="background-color:#f8f8f8"><span style="color:#333333">/**
* 三个方法的运行顺序为 preHandle -> postHandle -> afterCompletion
* 如果preHandle返回值为false,三个方法仅运行preHandle
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("前置运行----a1");
//返回值为false将拦截原始处理器的运行
//如果配置多拦截器,返回值为false将终止当前拦截器后面配置的拦截器的运行
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("后置运行----b1");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("完成运行----c1");
}
}</span></span>
<span style="background-color:#f8f8f8"><span style="color:#333333"> <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/m8"/>
<bean class="com.xinzhi.intercepter.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors></span></span>
<span style="background-color:#f8f8f8"><span style="color:#333333"><mvc:interceptors>
<!--开启具体的拦截器的使用,可以配置多个-->
<mvc:interceptor>
<!--设置拦截器的拦截路径,支持*通配-->
<!--/** 表示拦截所有映射-->
<!--/* 表示拦截所有/开头的映射-->
<!--/user/* 表示拦截所有/user/开头的映射-->
<!--/user/add* 表示拦截所有/user/开头,且具体映射名称以add开头的映射-->
<!--/user/*All 表示拦截所有/user/开头,且具体映射名称以All结尾的映射-->
<mvc:mapping path="/*"/>
<mvc:mapping path="/**"/>
<mvc:mapping path="/handleRun*"/>
<!--设置拦截排除的路径,配置/**或/*,达到快速配置的目的-->
<mvc:exclude-mapping path="/b*"/>
<!--指定具体的拦截器类-->
<bean class="MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors></span></span>
1)日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。
2)权限检查:如登录检测,进入处理器检测是否登录,如果没有直接返回到登录页面;
3)性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);
<span style="background-color:#f8f8f8"><span style="color:#333333">@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String uri = request.getRequestURI();
if(uri.equal("/login")){
return true;
}
HttpSession session = request.getSession();
Object user = session.getAttribute("USER_SESSION");
if(user!=null){
return true;
}
request.setAttribute("msg","未登陆状态");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.soft.interceptor.LoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors> </span></span>
1 导入maven依赖
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
2 前端页面
<span style="background-color:#f8f8f8"><span style="color:#333333"><form action="/fileupload" method="post" enctype="multipart/form-data">
上传LOGO: <input type="file" name="file"/><br/>
<input type="submit" value="上传"/>
</form></span></span>
3 配置多媒体解析器
<span style="background-color:#f8f8f8"><span style="color:#333333"><bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean></span></span>
4 后台代码
<span style="background-color:#f8f8f8"><span style="color:#333333"><span style="color:#770088">package</span> <span style="color:#0000ff">com</span>.<span style="color:#000000">xinzhi</span>.<span style="color:#000000">controller</span>;
?
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">apache</span>.<span style="color:#000000">commons</span>.<span style="color:#000000">io</span>.<span style="color:#000000">FileUtils</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">http</span>.<span style="color:#000000">HttpHeaders</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">http</span>.<span style="color:#000000">HttpStatus</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">http</span>.<span style="color:#000000">MediaType</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">http</span>.<span style="color:#000000">ResponseEntity</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">stereotype</span>.<span style="color:#000000">Controller</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">ui</span>.<span style="color:#000000">Model</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">web</span>.<span style="color:#000000">bind</span>.<span style="color:#000000">annotation</span>.<span style="color:#000000">RequestMapping</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">web</span>.<span style="color:#000000">bind</span>.<span style="color:#000000">annotation</span>.<span style="color:#000000">RequestMethod</span>;
<span style="color:#770088">import</span> <span style="color:#000000">org</span>.<span style="color:#000000">springframework</span>.<span style="color:#000000">web</span>.<span style="color:#000000">multipart</span>.<span style="color:#000000">MultipartFile</span>;
?
<span style="color:#770088">import</span> <span style="color:#000000">javax</span>.<span style="color:#000000">servlet</span>.<span style="color:#000000">http</span>.<span style="color:#000000">HttpServletRequest</span>;
<span style="color:#770088">import</span> <span style="color:#000000">java</span>.<span style="color:#000000">io</span>.<span style="color:#000000">File</span>;
<span style="color:#770088">import</span> <span style="color:#000000">java</span>.<span style="color:#000000">io</span>.<span style="color:#000000">IOException</span>;
<span style="color:#770088">import</span> <span style="color:#000000">java</span>.<span style="color:#000000">io</span>.<span style="color:#000000">UnsupportedEncodingException</span>;
<span style="color:#770088">import</span> <span style="color:#000000">java</span>.<span style="color:#000000">net</span>.<span style="color:#000000">URLEncoder</span>;
<span style="color:#770088">import</span> <span style="color:#000000">java</span>.<span style="color:#000000">util</span>.<span style="color:#000000">UUID</span>;
?
<span style="color:#555555">@Controller</span>
<span style="color:#770088">public</span> <span style="color:#770088">class</span> <span style="color:#0000ff">FileUploadController</span> {
?
? ?<span style="color:#aa5500">/**</span>
? ? <span style="color:#aa5500">* 上传页面跳转</span>
? ? <span style="color:#aa5500">* @return</span>
? ? <span style="color:#aa5500">*/</span>
? ?<span style="color:#555555">@RequestMapping</span>(<span style="color:#000000">value</span> <span style="color:#981a1a">=</span> <span style="color:#aa1111">"/upload"</span>,<span style="color:#000000">method</span> <span style="color:#981a1a">=</span> <span style="color:#000000">RequestMethod</span>.<span style="color:#000000">GET</span>)
? ?<span style="color:#770088">public</span> <span style="color:#008855">String</span> <span style="color:#000000">upload</span>(){
? ? ? ?<span style="color:#770088">return</span> <span style="color:#aa1111">"fileUpload"</span>;
? }
?
? ?<span style="color:#aa5500">/**</span>
? ? <span style="color:#aa5500">* 下载页面跳转</span>
? ? <span style="color:#aa5500">* @return</span>
? ? <span style="color:#aa5500">*/</span>
? ?<span style="color:#555555">@RequestMapping</span>(<span style="color:#000000">value</span> <span style="color:#981a1a">=</span> <span style="color:#aa1111">"/down"</span>,<span style="color:#000000">method</span> <span style="color:#981a1a">=</span> <span style="color:#000000">RequestMethod</span>.<span style="color:#000000">GET</span>)
? ?<span style="color:#770088">public</span> <span style="color:#008855">String</span> <span style="color:#000000">down</span>(){
? ? ? ?<span style="color:#770088">return</span> <span style="color:#aa1111">"download"</span>;
? }
?
? ?<span style="color:#aa5500">/**</span>
? ? <span style="color:#aa5500">* 上传逻辑</span>
? ? <span style="color:#aa5500">* @param uploadfile 上传的文件数组</span>
? ? <span style="color:#aa5500">* @return</span>
? ? <span style="color:#aa5500">*/</span>
? ?<span style="color:#555555">@RequestMapping</span>(<span style="color:#000000">value</span> <span style="color:#981a1a">=</span> <span style="color:#aa1111">"/fileUpload"</span>,<span style="color:#000000">method</span> <span style="color:#981a1a">=</span> <span style="color:#000000">RequestMethod</span>.<span style="color:#000000">POST</span>)
? ?<span style="color:#770088">public</span> <span style="color:#008855">String</span> <span style="color:#000000">uploadFile</span>(<span style="color:#000000">MultipartFile</span>[] <span style="color:#000000">uploadfile</span>){
? ? ? ?<span style="color:#770088">for</span> (<span style="color:#000000">MultipartFile</span> <span style="color:#000000">file</span> : <span style="color:#000000">uploadfile</span>) {
? ? ? ? ? ?<span style="color:#aa5500">//获取文件名称</span>
? ? ? ? ? ?<span style="color:#008855">String</span> <span style="color:#000000">filename</span> <span style="color:#981a1a">=</span> <span style="color:#000000">file</span>.<span style="color:#000000">getOriginalFilename</span>();
? ? ? ? ? ?<span style="color:#aa5500">//存在服务器上名称的修改</span>
? ? ? ? ? ?<span style="color:#000000">filename</span> <span style="color:#981a1a">=</span> <span style="color:#000000">UUID</span>.<span style="color:#000000">randomUUID</span>()<span style="color:#981a1a">+</span><span style="color:#aa1111">"_"</span><span style="color:#981a1a">+</span><span style="color:#000000">filename</span>;
? ? ? ? ? ?<span style="color:#aa5500">// 定义服务器上的存储路径</span>
? ? ? ? ? ?<span style="color:#008855">String</span> <span style="color:#000000">dirPath</span> <span style="color:#981a1a">=</span> <span style="color:#aa1111">"C:/file/"</span>;
? ? ? ? ? ?<span style="color:#000000">File</span> <span style="color:#000000">filePath</span> <span style="color:#981a1a">=</span> <span style="color:#770088">new</span> <span style="color:#000000">File</span>(<span style="color:#000000">dirPath</span>);
? ? ? ? ? ?<span style="color:#aa5500">// 判断路径是否存在,不存在就创建</span>
? ? ? ? ? ?<span style="color:#770088">if</span>(<span style="color:#981a1a">!</span><span style="color:#000000">filePath</span>.<span style="color:#000000">exists</span>()){
? ? ? ? ? ? ? ?<span style="color:#000000">filePath</span>.<span style="color:#000000">mkdir</span>();
? ? ? ? ? }
? ? ? ? ? ?<span style="color:#770088">try</span> {
? ? ? ? ? ? ? ?<span style="color:#aa5500">// 文件上传的核心</span>
? ? ? ? ? ? ? ?<span style="color:#000000">file</span>.<span style="color:#000000">transferTo</span>(<span style="color:#770088">new</span> <span style="color:#000000">File</span>(<span style="color:#000000">dirPath</span><span style="color:#981a1a">+</span><span style="color:#000000">filename</span>));
? ? ? ? ? } <span style="color:#770088">catch</span> (<span style="color:#000000">IOException</span> <span style="color:#000000">e</span>) {
? ? ? ? ? ? ? ?<span style="color:#000000">e</span>.<span style="color:#000000">printStackTrace</span>();
? ? ? ? ? ? ? ?<span style="color:#770088">return</span> <span style="color:#aa1111">"error"</span>;
? ? ? ? ? }
? ? ? }
? ? ? ?<span style="color:#770088">return</span> <span style="color:#aa1111">"success"</span>;
? }
?
?
? ?<span style="color:#555555">@RequestMapping</span>(<span style="color:#aa1111">"/download"</span>)
? ?<span style="color:#770088">public</span> <span style="color:#000000">ResponseEntity</span><span style="color:#981a1a"><</span><span style="color:#008855">byte</span>[]<span style="color:#981a1a">></span> <span style="color:#000000">fileDownload</span>(<span style="color:#000000">HttpServletRequest</span> <span style="color:#000000">request</span>,<span style="color:#008855">String</span> <span style="color:#000000">filename</span>) <span style="color:#770088">throws</span> <span style="color:#000000">UnsupportedEncodingException</span> {
? ? ? ?<span style="color:#aa5500">//指定文件下载地址的目录 ? filename -> 美女.jpg</span>
? ? ? ?<span style="color:#008855">String</span> <span style="color:#000000">dirPath</span> <span style="color:#981a1a">=</span> <span style="color:#aa1111">"F:/file"</span>;
? ? ? ?<span style="color:#aa5500">// 指定下载的文件名称</span>
? ? ? ?<span style="color:#000000">File</span> <span style="color:#000000">file</span> <span style="color:#981a1a">=</span> <span style="color:#770088">new</span> <span style="color:#000000">File</span>(<span style="color:#000000">dirPath</span> <span style="color:#981a1a">+</span> <span style="color:#000000">File</span>.<span style="color:#000000">separator</span> <span style="color:#981a1a">+</span> <span style="color:#000000">filename</span>);
? ? ? ?<span style="color:#000000">HttpHeaders</span> <span style="color:#000000">headers</span> <span style="color:#981a1a">=</span> <span style="color:#770088">new</span> <span style="color:#000000">HttpHeaders</span>();
? ? ? ?<span style="color:#aa5500">// 解决不同浏览器之间乱码问题</span>
? ? ? ?<span style="color:#000000">filename</span> <span style="color:#981a1a">=</span> <span style="color:#000000">getFilename</span>(<span style="color:#000000">request</span>, <span style="color:#000000">filename</span>);
? ? ? ?<span style="color:#aa5500">//告诉浏览器,打开方式(附件)</span>
? ? ? ?<span style="color:#000000">headers</span>.<span style="color:#000000">setContentDispositionFormData</span>(<span style="color:#aa1111">"attachment"</span>,<span style="color:#000000">filename</span>);
? ? ? ?<span style="color:#aa5500">//以二进制字节流的方式下载</span>
? ? ? ?<span style="color:#000000">headers</span>.<span style="color:#000000">setContentType</span>(<span style="color:#000000">MediaType</span>.<span style="color:#000000">APPLICATION_OCTET_STREAM</span>);
? ? ? ?<span style="color:#770088">try</span> {
? ? ? ? ? ?<span style="color:#770088">return</span> <span style="color:#770088">new</span> <span style="color:#000000">ResponseEntity</span><span style="color:#981a1a"><></span>(<span style="color:#000000">FileUtils</span>.<span style="color:#000000">readFileToByteArray</span>(<span style="color:#000000">file</span>),<span style="color:#000000">headers</span>, <span style="color:#000000">HttpStatus</span>.<span style="color:#000000">OK</span>);
? ? ? } <span style="color:#770088">catch</span> (<span style="color:#000000">IOException</span> <span style="color:#000000">e</span>) {
? ? ? ? ? ?<span style="color:#000000">e</span>.<span style="color:#000000">printStackTrace</span>();
? ? ? ? ? ?<span style="color:#770088">return</span> <span style="color:#770088">new</span> <span style="color:#000000">ResponseEntity</span><span style="color:#981a1a"><></span>(<span style="color:#000000">e</span>.<span style="color:#000000">getMessage</span>().<span style="color:#000000">getBytes</span>(), <span style="color:#000000">HttpStatus</span>.<span style="color:#000000">EXPECTATION_FAILED</span>);
? ? ? }
? }
?
? ?<span style="color:#aa5500">/**</span>
? ? <span style="color:#aa5500">* 不同浏览器的版本兼容</span>
? ? <span style="color:#aa5500">* @param request</span>
? ? <span style="color:#aa5500">* @param filename</span>
? ? <span style="color:#aa5500">* @return</span>
? ? <span style="color:#aa5500">* @throws UnsupportedEncodingException</span>
? ? <span style="color:#aa5500">*/</span>
? ?<span style="color:#770088">private</span> <span style="color:#008855">String</span> <span style="color:#000000">getFilename</span>(<span style="color:#000000">HttpServletRequest</span> <span style="color:#000000">request</span>,<span style="color:#008855">String</span> <span style="color:#000000">filename</span>) <span style="color:#770088">throws</span> <span style="color:#000000">UnsupportedEncodingException</span> {
? ? ? ?<span style="color:#aa5500">//判断是不是IE内核的关键字</span>
? ? ? ?<span style="color:#008855">String</span>[] <span style="color:#000000">IEBrowerKeyWords</span> <span style="color:#981a1a">=</span> {<span style="color:#aa1111">"MSIE"</span>,<span style="color:#aa1111">"Trident"</span>,<span style="color:#aa1111">"Edge"</span>};
? ? ? ?<span style="color:#008855">String</span> <span style="color:#000000">keywords</span> <span style="color:#981a1a">=</span> <span style="color:#000000">request</span>.<span style="color:#000000">getHeader</span>(<span style="color:#aa1111">"User-Agent"</span>);
? ? ? ?<span style="color:#770088">for</span> (<span style="color:#008855">String</span> <span style="color:#000000">keyWord</span> : <span style="color:#000000">IEBrowerKeyWords</span>) {
? ? ? ? ? ?<span style="color:#770088">if</span>(<span style="color:#000000">keywords</span>.<span style="color:#000000">contains</span>(<span style="color:#000000">keyWord</span>)){ ?<span style="color:#aa5500">//判断是否为IE浏览器</span>
? ? ? ? ? ? ? ?<span style="color:#770088">return</span> <span style="color:#000000">URLEncoder</span>.<span style="color:#000000">encode</span>(<span style="color:#000000">filename</span>,<span style="color:#aa1111">"UTF-8"</span>);
? ? ? ? ? }
? ? ? }
? ? ? ?<span style="color:#aa5500">// 其他浏览器编码格式ISO-8859-1</span>
? ? ? ?<span style="color:#770088">return</span> <span style="color:#770088">new</span> <span style="color:#008855">String</span>(<span style="color:#000000">filename</span>.<span style="color:#000000">getBytes</span>(<span style="color:#aa1111">"UTF-8"</span>),<span style="color:#aa1111">"ISO-8859-1"</span>);
? }
}
?</span></span>
5 前端代码使用现成的。如果jquery不能用了,可以引用网络地址
<span style="background-color:#f8f8f8"><span style="color:#333333"><script src="http://code.jquery.com/jquery-latest.js"></script></span></span>