天天看點

springMvc國際化和檔案上傳

國際化

國際化(internationalization) 簡稱i18n,是一種讓軟體在開發階段就支援多種語言的技術

 springmvc實作動态國際化(中英雙語)

1. 提供中英雙語資源檔案( i18n_en_US.properties、 i18n_zh_CN.properties)

2. 通過ResourceBundleMessageSource加載資源檔案(basenames屬性)

 <!--1) 配置國際化資源檔案 -->
      <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list> 
                            <value>i18n</value>
            </list>
        </property>
       </bean>
           

      注:1、必須叫messageSource

             2、可在開發階段使用ReloadableResourceBundleMessageSource它能自動重新加載資源檔案

  3. 指定springmvc的語言區域解析器,由它來确定使用哪個語言

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
           
4.配置國際化操作攔截器,如果采用基于(Session/Cookie)則必需配置
      
<mvc:interceptors>  
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
      </mvc:interceptors> 
           

  5.5 通過标簽輸出内容,而非直接輸出内容

配置國際化操作攔截器,如果采用基于(Session/Cookie)則必需配置

    5.5 springmvc的message标簽輸出

        <%@ taglib prefix="t" uri="http://www.springframework.org/tags" %>

        <t:message code="title"/>

    5.5 jstl的fmt标簽庫的标簽輸出

        <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

        <t:message code="title"/>

    注:1、為什麼在index.jsp使用<t:message code="user_name"/>會報錯

        原因是在web.xml中配置的DispatcherServlet的url-pattern為“/”,不會比對通路.jsp的url,

        是以直接通路首頁并不會經過DispatcherServlet,導緻無法讀取到資源檔案

        解決方案:首頁轉發到/WEB-INF/jsp/login.jsp即可

           2、切換語言的關鍵代碼(系統必須使用SessionLocaleResolver解析器)

         session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,Locale.CHINA)

  5.6 背景代碼擷取國際化資訊

@RequestMapping("/i18n")
    public String i18n(String state, HttpSession session){
        if("English".equals(state)){
            session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.US);
        }else{
            session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.CHINA);
        }
        return "i18n";
    }
           

   注:需修改pom.xml将國際化資源檔案輸出到target檔案夾

   <resource>

       <directory>src/main/resources</directory>

        <includes>

                <!--<include>jdbc.properties</include>-->

                <include>*.properties</include>

                <include>*.xml</include>

        </includes>

   </resource>

springmvc的檔案上傳

簡單步驟及代碼

1.添加檔案上傳相關依賴

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.3</version>
</dependency>
           

2. 配置檔案上傳解析器(CommonsMultipartResolver)

     在 springmvc-servlet.xml 中配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必須和使用者JSP 的pageEncoding屬性一緻,以便正确解析表單的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 檔案最大大小(位元組) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily屬性啟用是為了推遲檔案解析,以便捕獲檔案大小異常-->
        <property name="resolveLazily" value="true"/>
    </bean>
           

3 表單送出方式為method="post" enctype="multipart/form-data"

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

4. 檔案項用spring提供的MultipartFile進行接收

5. IO流讀寫檔案

@RequestMapping("/upload/{sid}")
    public String upload(MultipartFile file,HttpServletRequest request,@PathVariable("sid") Integer sid){
        String fileName = file.getOriginalFilename();
        String realPath = request.getServletContext().getRealPath(serverDir + fileName);

        Student student = new Student();
        student.setSid(sid);
        student.setPhotoname(fileName);
        //圖檔的類型
        student.setPhototype(file.getContentType());
        studentService.updateByPrimaryKeySelective(student);

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/student/list";
    }
           

另附下載下傳

@RequestMapping("/download/{photoname}")
    public String success(MultipartFile file, HttpServletRequest request, HttpServletResponse response, @PathVariable("photoname") String photoname){
        System.out.println(photoname);
        String name = photoname+".jpg";
        String type = "image/jpeg";
        String realPath = request.getServletContext().getRealPath(serverDir + name);

        response.setContentType(type);
        response.setHeader("Content-Disposition","attachment;filename=" + name);//檔案名
        /*
         * 從伺服器拿圖檔到本地
         * 	源:伺服器
         * 	目的:jsp輸出圖檔
         */
        File serverFile = new File(realPath);

        try {
//下載下傳效率低
//			FileUtils.copyFile(serverFile, response.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(serverFile));
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            copyBufferedStream(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 提高下載下傳效率
     * @param in
     * @param out
     */
    private void copyBufferedStream(BufferedInputStream in, BufferedOutputStream out) {
        byte[] bbuf = new byte[1024];
        int len = 0;
        try {
            while((len = in.read(bbuf))!=-1) {
                out.write(bbuf, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
           

繼續閱讀