• SpringMVC国际化与文件上传


    点击阅读上一章

    其实SpringMVC中的页面国际化与上一章的验证国际化基本一致。

    1.对页面进行国际化

    1)首先我们对Spring配置文件中添加国际化bean配置

    <!-- 注册国际化信息,必须有id,指定资源文件名称,资源文件在src目录下 -->
        <bean id="messageSource"
            class="org.springframework.context.support.ResourceBundleMessageSource">
            <property name="basename" value="i18n"></property>
        </bean>
        <!-- 配置LocalResolver用来获取本地化语言 -->
        <bean id="localeResolver"
            class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
        <!-- 配置LocaleChanceInterceptor拦截器 -->
        <mvc:interceptors>
            <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
        </mvc:interceptors>

    2)然后添加我们的资源文件,这个资源文件的前缀要与我们上面配置的bean的value相同。

    我们在资源文件写入我们需要国际化的内容

    然后我们在跳转页面的时候需要加载国际化资源

    @RequestMapping(value="login",method=RequestMethod.GET)
        public String login(Locale locale,Map<String ,Object> map){
            String name = messageSource.getMessage("name", null, locale);
            String pass = messageSource.getMessage("pass", null, locale);
            String title = messageSource.getMessage("title", null, locale);
            String submit = messageSource.getMessage("submit", null, locale);
            map.put("title", title);
            map.put("pass", pass);
            map.put("name", name);
            map.put("submit", submit);
            map.put("user", new User());
            return "login";
        }

    我们在页面中可以使用jstl或者spring标签数据国际化信息,spring中的form标签是用来输入spring验证错误之后的提示信息(上章有提过)

    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
    <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

    然后我们页面中的国际化信息可以可这显示出来

    <form:form action="login" method="post" commandName="user">
            <fmt:message key="name"/>
            <form:input path="username"/>
            <form:errors path="username"/>
            <br>
            <fmt:message key="pass"/>
            <form:input path="userpass"/>
            <input type="submit" value="<spring:message code="submit"/>">
     </form:form>

    我们还可以完成一个语言切换功能,我们在页面上加入两个超链接,当接收到请求,SpringMVC会在上下文中查找一个本地解析器,找到后使用它获取请求所对应的本地化类型信息,SpringMVC还允许还允许装配一个动态更改本地化类型的拦截器,这样通过指定一个请求参数就可以控制单个请求的本地化类型。

    <a href="login?locale=zh_CN">中文</a>
    <a href="login?locale=en_US">英文</a>

    SpringMVC接到请求后首先会判断有没有这个参数,如果有这个参数就添加到session里面,如果没这个参数会到session里面去找,session里面没有找到会默认读取浏览器的语言。

    2.文件上传

    SpringMVC的文件上传非常的简单,它直接提供了直接的支持,这种支持是通过即插即用的MultipartResolver接口实现的。Spring用它的实现类CommonsMultipartResolver来实现。SpringMVC上下文中没有自动装配所以需要我们手动来配置。我们这里就直接实现一个多文件上传,多文件上传会了害怕单文件上传不会?

    配置之前我们首先来导入文件上传的jar包,这些包在我们spring中是没有的。

    然后我们手动配置下Bean

    <!-- 配置文件上传 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 指定默认的编码格式 -->
            <property name="defaultEncoding" value="UTF-8" />
            <!-- 指定允许上传的文件大小,单位Byte -->
            <property name="maxUploadSize" value="512000" />
        </bean>

    这个bean里还可以设置类型啊什么什么的,有需要的可以阅读源码。

    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file"/><br>
            <input type="file" name="file"/><br>
            <input type="file" name="file"/><br>
            <input type="submit" value="submit">
        </form>

    enctype="multipart/form-data" 注意文件上传必须加上这个,而且必须是post请求。
    然后我们来看下我们服务器是怎么接收到文件的,多文件上传使用 MultipartFile[] 并且一定要在参数前加上注解 @RequestParam("file")否则会报错。单文件上传我们只需要使用一个MultipartFile对象,并且无需加注解。

    /**
         *    单文件上传 :  MultipartFile file
         *    多文件上传 :  @RequestParam("file") MultipartFile[] file
         *    多文件上传必须加上 @RequestParam("file")注解否则会报错
         *  @author:MiYa.
         *  @time:2018-9-28 11:50
         */
        @RequestMapping(value="upload",method=RequestMethod.POST)
        public String testFileUpload(HttpServletRequest request , @RequestParam("file") MultipartFile[] file){
            for (int i = 0; i < file.length; i++) {
                MultipartFile multipartFile = file[i];
                System.out.println(" ContentType: " + multipartFile.getContentType());
                System.out.println(" Name: " + multipartFile.getName());
                System.out.println(" OriginalFilename: " + multipartFile.getOriginalFilename());
                System.out.println(" Size: " + multipartFile.getSize());
                //判断是否提交文件,如果没有那么跳过上传
                if(multipartFile.isEmpty()){
                    continue;
                }
                // 获取文件的上传路径
                String uploadpath = request.getServletContext().getRealPath("uploads");
                //获取文件名称
                String filename = multipartFile.getOriginalFilename();
                //截取文件后缀
                String fileext = filename.substring(filename.lastIndexOf("."));
                //生成新的随机文件名称
                String newfileName = UUID.randomUUID() + fileext;    
                //文件保存路径
                File savepath = new File(uploadpath + "/" + newfileName);
                //上传文件
                try {
                    multipartFile.transferTo(savepath);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
            return "welcome";
        }

    整理下MultipartFile经常使用的方法:

    isEmpty():判断是否提交文件上来 

    getContextType():获取文件类型

    getName():获取表单元素名称

    getOriginalFilename():获取文件名

    getSize():获取文件大小

    getBytes():获取字节数组

  • 相关阅读:
    Android Studio基本使用
    convlstm学习资料
    Java重写与重载
    Java继承的缺点
    long转int
    解决RubyMine中puts中文显示乱码的问题
    Ruby入门1
    Ruby学习笔记
    matplotlib绘制饼状图
    python强大的绘图模块matplotlib示例讲解
  • 原文地址:https://www.cnblogs.com/SimpleWu/p/9717853.html
Copyright © 2020-2023  润新知