SpringMVC笔记(4)上传下载及国际化

文件的上传

首选导入与文件上传相关jar包

22.PNG

form表单中要添加
enctype="multipart/form-data"
用post请求提交
表单代码如下:



    <form action="<%=path%>/fff/aaa.do" method="post" enctype="multipart/form-data">
    	1.<input name="u1"/><br/>
    	2.<input name="a1"/><br/><br/>
    	3.<input type="file" name="mf"/><br/>
    	4.<input type="file" name="mf"/><br/><br/>
    	
    	<input type="submit"/>
    </form>

对应方法中参数为MultipartFile[] f
参数前面可以加上注解@RequestParam(name=“mf”,required=false)
表示用户可以不上传文件程序也不会报错
参数中也要有HttpServletRequest来获得项目路径
1.在WebRoot下新建一个imgs/kind的文件夹来存放上传的图片
2.得到项目路径+"/imgs/kind/"
req.getSession().getServletContext().getRealPath("")+"/imgs/kind/";
3.判断f是否为空,遍历f这个数组
4.判断上传的每个文件大小是否>0
5.是的话
File iof = new File('图片存放路径'+f[i].getOriginalFilename());
6.把Spring的MultipartFile保存成java.io.File
f[i].transferTo(iof);
完整代码如下:



	@RequestMapping("/aaa")
	public String f1(String u1,String a1,@RequestParam(name="mf",required=false) MultipartFile[] f,HttpServletRequest req) throws IOException{
		//解析后 获取 表单数据
		System.out.println(this.getClass()+"日志1...u1="+u1+"\ta1="+a1+"\t上传:"+(null!=f?f.length:-1));
		
		String directory = req.getSession().getServletContext().getRealPath("")+"/imgs/kind/";
		
		//保存
		if(null != f && f.length>0){
			for (int i = 0; i < f.length; i++) {
				if( f[i].getSize() > 0){
					System.out.println("日志2...."+f[i].getOriginalFilename());
					File iof = new File(directory+f[i].getOriginalFilename());
					f[i].transferTo(iof);	//spring的MultipartFile 保存成 java.io.File
				}
			}
		}
		
		return "test2";
	}//f1()

文件的下载

返回值要为ResponseEntity<byte[]>
参数为HttpServletRequest也是用来获得项目路径
步骤:
1.得到下载的文件路径

//从数据库查询出对象 的资源名称 ,假如是个图片
String fileName="jia.png";
String directory = req.getSession().getServletContext().getRealPath("")+"/imgs/kind/" + fileName;

2.设置头信息

//设置下载头信息
HttpHeaders hders = new HttpHeaders();
hders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
hders.setContentDispositionFormData("attchment", fileName);

3.读取文件变成字节数组

return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(directory)), hders, HttpStatus.CREATED) ;

国际化

写语言的配置文件

abc_en.properties
abc_ja.properties
abc_zh.properties
文件放在src下,键一样值写自己对应的语言

跳转链接

?后加上locale=代表的语言

<a href="<%=path%>/fff/bbb.do?locale=zh">中文</a>
<a href="<%=path%>/fff/bbb.do?locale=en">english</a>
<a href="<%=path%>/fff/bbb.do?locale=ja">さつ</a>

对应的方法跳到test2.jsp页面



	@RequestMapping("/bbb")
	public String f2(){
		System.out.println(this.getClass() + "执行... f2()");
		return "test2";
	}

页面上要加
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>配置
abc_en.properties等配置文件中的语言调用通过<spring:messagecode=“键” />



	<h1><spring:message code="a.a.c.d"  >
   			<spring:argument value="5"/>
   		</spring:message>
   	
   	</h1>
  	<br/>
  	<spring:message code="k.ind.info" />
  	<br/>
  	<spring:message code="a.b.c.u1" />:<input name="u1"/><br/>
  	<spring:message code="a.b.c.u2" />:<input name="u2"/><br/><br/>
  	
  	<input type="submit" value="<spring:message code="k.ind.btn"/>"/><br/>

配置

在spring-mvc.xml中配置
023.PNG

还要配置绑定国际化资源文件前缀
国际化解析器
国际化拦截器
整个配置文件代码:



	<?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:p="http://www.springframework.org/schema/p"
	    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.xsd
	        http://www.springframework.org/schema/mvc
	        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	
	    <context:component-scan base-package="com.senchen.controller"/>
		
	    <!-- 试图解析器  springMVC管理的jsp文件位置应该在 /WEB-INF/meto/  -->
	    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		    <property name="prefix" value="/WEB-INF/meto/"/>
		    <property name="suffix" value=".jsp"/>
		</bean>
		
		<!-- 绑定国际化资源文件前缀 -->
		<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
			<property name="basename" value="abc"/>
			<property name="useCodeAsDefaultMessage" value="true"/>
		</bean> 
	
		<!-- 国际化解析器 -->
		<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
			
		<!-- 国际化拦截器 --> 	
		<mvc:interceptors>
			<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
		</mvc:interceptors>
		
	</beans>

自定义类型转化器

继承PropertyEditorSupport类
代码如下:



	package com.senchen.controller.util;
	
	import java.beans.PropertyEditorSupport;
	import java.text.ParseException;
	import java.text.SimpleDateFormat;
	import java.util.Date;
	
	
	public class YourConvert extends PropertyEditorSupport {
		//默认支持  2010-10-10
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			// text 接收到的 要转换的 字符串
			System.out.println("YourConvert : 现在要转换 " + text );
			
			Date ret = null;
			
			try {
				ret = fmt.parse( text );
			} catch (ParseException e) {
				
				fmt = new SimpleDateFormat("yyyy年MM月dd日");	//否则尝试 2010年10月10日
				try {
					ret = fmt.parse( text );
				} catch (ParseException e1) {
					fmt = new SimpleDateFormat("yyyy/MM/dd");	//否则尝试 2010/10/10
					try {
						ret = fmt.parse( text );
					} catch (ParseException e2) {
						System.out.println("以上格式都不支持");
					}
				}
			}
	
			super.setValue( ret );
		}//setAsText()
	}

加载要使用的转换器,在该方法上加注解:@InitBinder
Date.class表示碰见此类型就使用该转化器
代码如下:



	@InitBinder
	public void f1( WebDataBinder bind ){
		System.out.println("注册类型转换器");
		//注册要使用的转换器
		bind.registerCustomEditor(Date.class,  new YourConvert());
	}

当有方法中有Date类型时会自动转换



	@RequestMapping("/aaa")
	public String f1(String u1 ,Date u2){
		System.out.println(this.getClass()+"日志1...u1:"+u1+"\t u2:" + u2);
		return "test2";
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值