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";
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

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

友情链接更多精彩内容