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

一,SpringMVC文件上传下载

1.1 同步

1.1.1 文件上传

第一步:定义上传表单

用户名:
图片:

第二步:引入文件上传的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;
	}

第五步:获取图片的视图



1.1.2文件下载

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

下载文件

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

/**
	 * 文件下载
	 * @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

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

图片:

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

//获取表单对象,然后调用ajaxForm方法初始化表单
	$("#uploadForm").ajaxForm({
		url:"${pageContext.request.contextPath}/day26/upload2.do",
		type:"post",
		success:function(data){
			var imgUrl = "${pageContext.request.contextPath}" + data;
			$("").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对象

第二步:连接服务器

第三步:发送请求

第四步:接收相应数据


2.2 jquery实现异步请求

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

举例:


2.3异步提交表单

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

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

例如:

用户名:
大头照:

后台处理表单数据:

@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


<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">
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>*.dourl-pattern>
    servlet-mapping>
web-app>

3.2.2 mvc.xml


<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


<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>
    

    
    <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>

你可能感兴趣的:(SpringMVC——文件上传下载,异步请求和SSM整合)