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";
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容

  • 16. Web MVC 框架 16.1 Spring Web MVC 框架介绍 Spring Web 模型-视图-...
    此鱼不得水阅读 1,046评论 0 4
  • 对于java中的思考的方向,1必须要看前端的页面,对于前端的页面基本的逻辑,如果能理解最好,不理解也要知道几点。 ...
    神尤鲁道夫阅读 815评论 0 0
  • 我的心里住着一位公主,它非常完美,它没有缺点。 这句话是我同学问我说:你见过没有缺点的人吗?我回答:"我虽然没有见...
    Andi苏苏阅读 161评论 0 3
  • 和煦的春风已经散去,酷暑的聒噪悄然响起 不觉间,和六月撞个满怀 六月真是个值得品味的月份 ...
    微风付晓阅读 318评论 4 14
  • 一、题目描述: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元...
    wangzaiplus阅读 193评论 0 1