SpringMVC——文件上传下载,异步请求和SSM整合

一,SpringMVC文件上传下载

1.1 同步

1.1.1 文件上传

第一步:定义上传表单

<form action="${pageContext.request.contextPath }/day26/upload.do" enctype="multipart/form-data" method="post" >
		用户名:<input type="text" name="username"><br>
		图片:<input type="file" name="pic"><br>
		<input type="submit" value="提交">
	</form>

第二步:引入文件上传的jar包

commons-fileupload-1.4.jar
commons-io-2.4.jar
standard.jar

第三步:在SpringMVC配置文件上传解析器

<!-- 配置文件上传解析器 -->
	<bean id="multipartResolver" 
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置文件上传的大小 -->
	   	<property name="maxUploadSize" value="102400"/>
	</bean>

第四步:后台实现

/**
	 * 文件上传
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("upload")
	public ModelAndView upload(String username,@RequestParam(value="pic",required = true) MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
		//获取保存文件的真实路径
		String savePath = request.getServletContext().getRealPath("/uploads");
		//获取上传文件名
		String fileName = file.getOriginalFilename();
		//创建file对象
		File targetFile = new File(savePath, fileName);
		//保存文件
		file.transferTo(targetFile);
		ModelAndView mv = new ModelAndView("upload");
		mv.addObject("picUrl", "/uploads/"+fileName);
		return mv;
	}

第五步:获取图片的视图

<img alt="" src="${pageContext.request.contextPath }${picUrl}">

1.1.2文件下载

第一步:创建文件下载页面

<a href="${pageContext.request.contextPath }/day26/download.do?fileName=中文.txt">下载文件</a>

第二步:定义一个控制器类,实现文件下载

/**
	 * 文件下载
	 * @param fileName 下载文件名
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("download")
	public void download(String fileName, HttpServletRequest request,HttpServletResponse response) throws IOException{
		//设置响应头
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachement;filename="+fileName);
		//获取文件上传路径
		String path = request.getServletContext().getRealPath("/uploads");
		//创建file对象
		File file = new File(path, fileName);
		//读取文件
		FileInputStream fis = new FileInputStream(file);
		//创建文件输出流对象
		OutputStream os = response.getOutputStream();
		int len = -1;
		byte[] buf = new byte[1024];
		while((len = fis.read(buf)) != -1){
			os.write(buf, 0, len);
		}
		fis.close();
	}

1.2异步

1.2.1 文件上传

第一步:导入包

jquery-2.0.0.min.js
jquery.form.min.js

第二步:定义文件上传表单

<form id="uploadForm" enctype="multipart/form-data"  >
		图片:<input type="file" name="pic"><br>
		<input type="submit" value="提交">
	</form>
	<div id="img"></div>

第三步:获取表单参数,然后调用ajaxForm方法初始化表单

//获取表单对象,然后调用ajaxForm方法初始化表单
	$("#uploadForm").ajaxForm({
		url:"${pageContext.request.contextPath}/day26/upload2.do",
		type:"post",
		success:function(data){
			var imgUrl = "${pageContext.request.contextPath}" + data;
			$("<img />").attr("src", imgUrl).width(200).height(200).appendTo("#img");
		},
		error:function(){
			alert("加载失败");
		}
	})

第四步:后台实现

/**
	 * 文件上传(异步)
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value="upload2")
	@ResponseBody
	public String upload2(@RequestParam(value="pic") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
		//获取保存文件的真实路径
		String savePath = request.getServletContext().getRealPath("/uploads");
		//获取上传文件名
		String fileName = file.getOriginalFilename();
		//创建file对象
		File targetFile = new File(savePath, fileName);
		//保存文件
		file.transferTo(targetFile);
		return "/uploads/" + fileName;
	}

二,SpringMVC异步请求

同步请求: 用户发起请求 -》 Servlet (获取数据)-》 JSP(显示数据)

异步请求:用户发起请求 -》JSP(显示页面元素) -》 后台程序(获取数据) -》填充数据

2.1 原生ajax请求

第一步:创建XMLHttpRequest对象

第二步:连接服务器

第三步:发送请求

第四步:接收相应数据

<script>
	//第一步:创建XMLHttpRequest对象;
	var xhr = new XMLHttpRequest();
	//第二步:连接服务器;
	xhr.open('GET', "${pageContext.request.contextPath}/getText.do");
	//第三步:发送请求;
	xhr.send();
	//第四步:接收响应数据;
	xhr.onreadystatechange = function() {
		//readyState:xhr对象的状态,4代表已经完成了HTTP响应的接收
		//status:响应状态,200代表响应成功
		if (xhr.readyState == 4 && xhr.status == 200) {
			alert(xhr.responseText);
		}
	}
</script>

2.2 jquery实现异步请求

格式作用
$.get()发送get异步请求
$.post()发送post异步请求
$.getJson()发送get请求,但是指定返回格式是json
$.ajax()发送异步请求

举例:

<script>
	$.post("${pageContext.request.contextPath}/getImg.do", function(responseText) {
    //document.getElementById("imgUrl").src = imgUrl;
    $("#imgUrl").prop("src", responseText);
});
</script>

2.3异步提交表单

异步提交表单需要使用jquery.form插件。引入插件之后,需要对表单进行初始化。

$("表单").ajaxForm({
    参数...    
})

例如:

<form id="registForm" enctype="multipart/form-data">
    用户名:<input type="text" name="userName"/><br/>
    大头照:<input type="file" name="pic"/><br/>
    <input type="submit" value="提交"/>
</form>
<img src=""/>

<script>
    $("#registForm").ajaxForm({
        url: "${pageContext.request.contextPath}/registAsync.do", // 请求URL
        type: "post", // 请求方式
        dataType: "text", // 响应回来的数据类型
        async: true, // 异步
        success: function(data){ // 请求成功
            $("img").prop("src", data);
        },
        error: function(){ // 请求失败
            alert("数据加载失败!");
        }
    });

</script>

后台处理表单数据:

@RequestMapping("/registAsync.do")
@ResponseBody
public String registAsync(HttpServletRequest reqeust, String userName
			, MultipartFile pic) throws Exception {
		String fileName = pic.getOriginalFilename();
		// 目标文件
		String uploadPath = reqeust.getServletContext().getRealPath("/uploads");
		File targetFile = new File(uploadPath + "/" + fileName);
		// 把上传文件数据保存在targetFile中
		pic.transferTo(targetFile);

		// 图片地址
		String imgUrl = reqeust.getContextPath() + "/uploads/" + fileName;
		return imgUrl;
}

三,SSM整合

3.1 导入相关jar包

aopalliance-1.0.jar
druid-1.0.9.jar
spring-jdbc-4.1.3.RELEASE.jar
spring-tx-4.1.3.RELEASE.jar
spring-core-4.1.3.RELEASE.jar
commons-pool-1.3.jar
mybatis-3.2.7.jar
commons-fileupload-1.2.2.jar
mybatis-spring-1.2.2.jar
aspectjweaver-1.6.11.jar
spring-web-4.1.3.RELEASE.jar
log4j-core-2.0-rc1.jar
servlet-api.jar
spring-beans-4.1.3.RELEASE.jar
commons-logging-1.1.1.jar
jstl-1.2.jar
commons-io-2.4.jar
spring-jms-4.1.3.RELEASE.jar
log4j-1.2.17.jar
slf4j-log4j12-1.7.5.jar
cglib-2.2.2.jar
spring-webmvc-4.1.3.RELEASE.jar
jackson-core-2.4.2.jar
jackson-annotations-2.4.0.jar
jackson-databind-2.4.2.jar
commons-dbcp-1.2.2.jar
asm-3.3.1.jar
mysql-connector-java-5.1.7-bin.jar
javassist-3.17.1-GA.jar
spring-aop-4.1.3.RELEASE.jar
slf4j-api-1.7.5.jar
spring-expression-4.1.3.RELEASE.jar
junit-4.9.jar
jackson-databind-2.4.2.jar
jackson-annotations-2.4.0.jar
log4j-api-2.0-rc1.jar
spring-context-support-4.1.3.RELEASE.jar
spring-messaging-4.1.3.RELEASE.jar
spring-context-4.1.3.RELEASE.jar
spring-aspects-4.1.3.RELEASE.jar

3.2编写配置文件

3.2.1 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--springmvc配置文件-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

3.2.2 mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        ">
    <mvc:annotation-driven/>

	<!--配置渲染器 视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!--配置视图地址的前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!--配置视图地址的后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
	<!--扫描该包下的注解 -->
	<context:component-scan base-package="com.lmc.controller" />
	
	<!-- 配置文件上传解析器 -->
	<bean id="multipartResolver" 
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置文件上传的大小 -->
	   	<property name="maxUploadSize" value="1024000"/>
	   	<property name="defaultEncoding" value="utf-8"></property>
	</bean>
    
    

</beans>

3.2.3 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/p
        http://www.springframework.org/schema/p/spring-p.xsd">

    <!--读取属性文件-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" abstract="true">
        <property name="Location" value="classpath:db.properties"/>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/lmc"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--声明式事务配置开始-->
    <!--配置事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        
    </tx:advice>
    <aop:config proxy-target-class="true">
        <aop:pointcut id="pointcut" expression="execution(* com.lmc.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
    <!--声明式事务配置结束-->

    <!--配置工厂SQLSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--自动扫描 所配置包下的所有注解-->
    <context:component-scan base-package="com.lmc"/>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	<property name="basePackage" value="com.lmc.mapper"></property>
</bean>
 
</beans>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值