1.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- 前端控制器
/=默认的url-pattern
/a/b/c /a /a/d/c
/a/d
/a
/
*注意:此控制器默认加载/WEB-INF下的xxx-servlet.xml文件
:其中xxx等于【DispatcherServlet的配置名】
-->
<servlet>
<servlet-name>mvc62</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc62.xml</param-value>
</init-param>
<!-- 随项目启动而启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc62</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 专治Post请求参数乱码 -->
<filter>
<filter-name>encoding62</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 将请求的编码方式设置为utf-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding62</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.配置SpringMVC.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- xmlns:xml name space 是每一个schema唯一标识 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 扫描所有控制器中的注解 -->
<context:component-scan base-package="com.c61.controller"></context:component-scan>
<!--
MVC中基于注解开发,导入注解驱动
<mvc:annotation-driven/>
-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 支持的格式:application/json -->
<value>application/json</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 视图解析器:解析视图
控制器方法的返回值,会被视图解析器捕获。"abc"
根据捕获的内容,解析出一个视图地址:/abc.jsp
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--
静态资源:html,js,css,jpg
访问404 解决
-->
<mvc:default-servlet-handler/> <!-- 声明异常处理器 -->
<bean class="com.c61.ex.resolver.MyExceptionResolver"></bean> <!-- 拦截器配置 -->
<!--
/a/b
inter1
inter2
拦截顺序:先配置先拦截
具体顺序:pre1==pre2==contorller==post2==post1==after2==after1
-->
<mvc:interceptors>
<mvc:interceptor>
<!-- 定义要拦截的路径
/inter/* 匹配 /inter/a /inter/b inter/cssdafasfsafs
不能匹配/inter/a/b
/inter/** 匹配 /inter/a /inter/xxsjaflsajf /inter/a/b/c/e/d/xxxcvx
*注意:exclude-mapping不能单独使用。要配合mapping使用
:在mapping匹配的范围中排除一些个。
-->
<mvc:mapping path="/inter/**"/>
<mvc:mapping path="/a/b"/>
<mvc:mapping path="/c/**"/>
<mvc:exclude-mapping path="/inter/test/*"/>
<mvc:exclude-mapping path="/c/b/**"/>
<!-- 声明拦截器 -->
<bean class="com.c61.interceptor.MyInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!-- 定义要拦截的路径 -->
<mvc:mapping path="/inter/test"/>
<!-- 声明拦截器 -->
<bean class="com.c61.interceptor.MyInterceptor2"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 声明文件上传解析器
注意:此解析器,id必须为:multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大允许的上传大小 byte -->
<property name="MaxUploadSize" value="2097152"></property>
</bean>
<!--
注册,验证码生成器
-->
<bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend">
<constructor-arg>
<props>
<!-- 是否有边框 边框颜色 边框粗细 -->
<prop key="kaptcha.border">no</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.border.thickness">20</prop>
<prop key="kaptcha.textproducer.font.color">black</prop>
<prop key="kaptcha.image.width">200</prop>
<prop key="kaptcha.image.height">50</prop>
<prop key="kaptcha.textproducer.font.size">40</prop>
<prop key="kaptcha.session.key">code61</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">Arial,Courier</prop>
<!-- <prop key="kaptcha.background.clear.from">black</prop>
<prop key="kaptcha.background.clear.to">255,0,0</prop> -->
</props>
</constructor-arg>
</bean>
</beans>
3.配置控制器
Class : UpLoadController
package com.c61.controller; import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID; import javax.servlet.http.HttpSession; import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; @Controller
@RequestMapping("/up")
public class UpLoadController {
//通过MultipartFile接收文件
@RequestMapping("/test")
public String testUP(MultipartFile file61,HttpSession s,Map m) throws IllegalStateException, IOException{
//file61.transferTo(new File("d:/abc/abc.txt"));
//获取虚拟路径:/up61 对应部署到服务器后的具体的磁盘路径
String realPath=s.getServletContext().getRealPath("/up61");
System.out.println("real:"+realPath);
//获取文件的后缀名
String extension=FilenameUtils.getExtension(file61.getOriginalFilename());//返回: jpg png pdf doc
//获取文件名 xxx.txt xxx.png
//String fileName=file61.getOriginalFilename();
String fileName=UUID.randomUUID()+"."+extension;
//拼接写出路径
String path=realPath+File.separator+fileName;
System.out.println("File.separator:"+File.separator);
file61.transferTo(new File(path));
//将图片名称存储在Map中(Request)
m.put("name",fileName);
return "forward:/index.jsp";
}
public static void main(String[] args) {
//32长度 由16进制字符组成的全球唯一的字符串
UUID uuid=UUID.randomUUID();
System.out.println(uuid);
}
}
4.配置视图
View : upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<div style="text-align: center;">
<form target="c61" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test">
<input type="file" name="file61"/>
<input type="submit" value="上传"/>
</form>
<iframe name="c61" width="200px" height="200px" frameborder="0"></iframe>
</div>
</body>
</html>
View : index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<img height="100px" width="100px" src="${pageContext.request.contextPath}/up61/${requestScope.name}"/>
</body>
</html>
Client :
上传
1 定制上传表单
1>method="post"
2>enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test">
<input type="file" name="file61"/>
<input type="submit" value="上传"/>
</form>
2 定制接收文件的Controller
public String testUP(MultipartFile file61,HttpSession s) throws IllegalStateException, IOException{
//file61.transferTo(new File("d:/abc/abc.txt"));
//获取虚拟路径:/up61 对应部署到服务器后的具体的磁盘路径
String realPath=s.getServletContext().getRealPath("/up61");
//获取文件名 xxx.txt xxx.png
String fileName=file61.getOriginalFilename();
//拼接写出路径
String path=realPath+File.separator+fileName;
//将文件写出到指定目录位置
file61.transferTo(new File(path));
return "forward:/index.jsp";
}
3 在springMVC容器中注册文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大允许的上传大小 byte -->
<property name="MaxUploadSize" value="2097152"></property>
</bean>
*ID必须为:multipartResolver
4 导包:commons-fileupload-1.3.jar commons-io-2.0.1.jar
5 生成唯一的文件名
//32长度 由16进制字符组成的全球唯一的字符串
UUID uuid=UUID.randomUUID();
System.out.println(uuid);
//uuid.toString()可以作为文件名使用,注意要拼接后缀
6 回显上传的图片
<!-- target="c61" 将响应展示在名为c61的iframe中(不再用一张新页面承载响应) -->
<form target="c61" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test">
<input type="file" name="file61"/>
<input type="submit" value="上传"/>
</form>
<iframe name="c61" width="200px" height="200px" frameborder="0"></iframe>
啦啦啦