Spring MVC国际化语言与文件上传

    技术2022-07-14  87

    Spring MVC国际化语言与文件上传

    一. 国际化(internationalization)实例结果: 二. springmvc的文件上传

    一. 国际化(internationalization)

    简称i18n,是一种让软件在开发阶段就支持多种语言的技术

    java.util.Locale 语言代码_国家代码 注:国家代码可省略 匿名为: zh_CN

    springmvc实现动态国际化(中英双语) 2.1 提供中英双语资源文件 例如: i18n_en_US.properties i18n_zh_CN.properties 资源下载 2.2 如果解压出来是乱码的需要在IDEA或者别的编程软件改代码格式 IDEA:---->file---->settings---->Editor---->File Encodings 点击OK就行了

    2.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、必须叫messageSource、必须叫messageSource 注2:可在开发阶段使用ReloadableResourceBundleMessageSource它能自动重新加载资源文件

    2.3 指定springmvc的语言区域解析器,由它来确定使用哪个语言 2.3.1 配置语言区域解析器

    <!--2) 指定语言区域解析器,由它来确定使用哪个语言 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>

    注1:必须叫localeResolver、必须叫localeResolver、必须叫localeResolver

    2.3.2 语言解析器的类型

    AcceptHeaderLocaleResolveraccept-language头部来解析区域由用户的web浏览器根据底层操作系统的区域设置进行设定。请注意,这个区域解析器无法改变用户的区域,因为它无法修改用户操作系统的区域设置SessionLocaleResolver(基于会话)它通过检验用户会话中预置的属性来解析区域。如果该会话属性不存在,它会根据accept-language HTTP头部确定默认区域CookieLocaleResolver(基于Cookie)这个区域解析器所采用的Cookie可以通过cookieName和cookieMaxAge属性进行定制。defaultLocale默认的语言区域cookieName设置cookieName名称cookieMaxAge设置cookieName有效时间,单位秒cookiePath设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见

    2.4 配置国际化操作拦截器,如果采用基于(Session/Cookie)则必需配置

    <!--3) 配置国际化操作拦截器--> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors>

    2.5 通过标签输出内容,而非直接输出内容

    2.5.1 springmvc的message标签输出 <%@ taglib prefix="t" uri="http://www.springframework.org/tags" %> <t:message code="title"/> 2.5.2 jstl的fmt标签库的标签输出 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <t:message code="title"/>

    head.jsp: 减去多次调用标签问题

    <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> <%@taglib prefix="f" uri="http://www.springframework.org/tags/form" %> <%@taglib prefix="t" uri="http://www.springframework.org/tags" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% request.setAttribute("ctx",request.getContextPath()); %> <base href="<%=request.getContextPath()+"/"%>"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">

    注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)

    2.6 后台代码获取国际化信息 2.6.1 后台通过springmvc的消息机制显示消息 2.6.2 通过RequestContext获得国际化的消息 RequestContext requestContext = new RequestContext(request); String errorMsg = requestContext.getMessage(“login.error.label”); System.out.println(“errorMsg:” + errorMsg);

    index.jsp:

    <%-- Created by IntelliJ IDEA. User: zjjt Date: 2020/6/29 Time: 19:21 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>springmvc(国际语言)</title> <%@include file="/common/head.jsp" %> </head> <body> <h1>你好<%=System.currentTimeMillis()%></h1> <div> <a href="${ctx}/i18n/us">English</a> <a href="${ctx}/i18n/cn">中文</a> </div> <div> <p> <t:message code="yhzh.label"></t:message> </p> <p> <t:message code="yhmm.label"></t:message> </p> </div> </body> </html>

    i18nController :

    package com.zking.ssm.controller; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.servlet.http.HttpSession; import java.util.Locale; @Controller @RequestMapping("/i18n") public class i18nController { @RequestMapping("/{langes}") public String change(@PathVariable String langes, HttpSession session){ if("us".equals(langes)){ session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,Locale.US); }else if("cn".equals(langes)){ session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,Locale.CANADA); }else{ throw new RuntimeException("你的操作有误请和管理员联系不支持"+langes+"该语言"); } return "index"; } }

    实例结果:

    二. springmvc的文件上传

    添加文件上传相关依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> 配置文件上传解析器(CommonsMultipartResolver) <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>

    Spring-mvc.xml:

    <?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: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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 通过context:component-scan元素扫描指定包下的控制器--> <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)--> <!--<context:component-scan base-package="com.zking.zf"/>--> <!--1) use-dafault-filters="false"的情况下,根据表达式包含(include-filter)或排除(exclude-filter)指定包 use-default-filters=false使用過濾器--> <context:component-scan base-package="com.zking.ssm" use-default-filters="false"> <!--type掃描註解 expression指定的註解--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,--> <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)--> <mvc:annotation-driven></mvc:annotation-driven> <!--3) ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4) 单独处理图片、样式、js等资源 --> <!--<mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/>--> <mvc:resources location="/static/" mapping="/static/**" cache-period="86400" /> <!--1) 配置国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>i18n</value> </list> </property> </bean> <!--2) 指定语言区域解析器,由它来确定使用哪个语言 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <!--3) 配置国际化操作拦截器--> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <!-- xxxxxxxxxxxxxxxxx 文件上传 xxxxxxxxxxxxxxxxxxxxxxxxx --> <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> </beans> 表单提交方式为method=“post” enctype=“multipart/form-data” <f:form action="${ctx}/file/fileload1" method="post" enctype="multipart/form-data"> <input type="file" name="img" /> <input type="submit" value="上傳"/> </f:form>

    Fileload.jsp:

    <%-- Created by IntelliJ IDEA. User: zjjt Date: 2020/7/1 Time: 16:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上傳</title> <%@include file="/common/head.jsp"%> </head> <body> <h1>文件上傳</h1> <c:if test="${msg != null}"> ${msg} <c:remove var="msg"></c:remove> </c:if> <f:form action="${ctx}/file/fileload1" method="post" enctype="multipart/form-data"> <input type="file" name="img" /> <input type="submit" value="上傳"/> </f:form> <hr> <f:form action="${ctx}/file/fileload2" method="post" enctype="multipart/form-data"> <input type="file" name="imgs" /> <input type="file" name="imgs" /> <input type="file" name="imgs" /> <input type="submit" value="上傳"/> </f:form> </body> </html> 文件项用spring提供的MultipartFile进行接收 在FileLoad.jsp name名一定要与xxxController里面MultipartFile 名一致(我的是使用myfile) FileController.java: package com.zking.ssm.controller; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.UUID; @Controller @RequestMapping("/file") public class FileController { @RequestMapping("/fileload") public String fileload() { return "Fileload"; } @RequestMapping("/fileload1") public String fileload1(MultipartFile img, HttpSession ses) throws Exception { System.out.println("fileload1"); String id = UUID.randomUUID().toString().replace("-",""); String path="f:\\temp\\uploads\\"+id; File file = new File(path); img.transferTo(file); ses.setAttribute("msg","文件上傳成功"); return "redirect:/file/fileload"; } @RequestMapping("/fileload2") public String fileload2(MultipartFile[] imgs, HttpSession ses) throws Exception { System.out.println("fileload2"); for (MultipartFile img : imgs){ String id = UUID.randomUUID().toString().replace("-",""); String path="f:\\temp\\uploads\\"+id; File file = new File(path); img.transferTo(file); } ses.setAttribute("msg","文件上傳成功"); return "redirect:/file/fileload"; } @RequestMapping("/upload") public String upload(HttpServletRequest req, MultipartFile myfile){ String fileName=myfile.getOriginalFilename(); String contentType=myfile.getContentType(); System.out.println(fileName); try { FileUtils.copyInputStreamToFile(myfile.getInputStream(),new File("f:/temp/uploads/"+fileName)); } catch (IOException e) { e.printStackTrace(); } return "redirect:/file/fileload"; } @RequestMapping("/upload1") public String upload1(MultipartFile[] imgs, HttpSession ses) throws Exception { System.out.println("upload1"); for (MultipartFile myfile : imgs){ String fileName=myfile.getOriginalFilename(); String contentType=myfile.getContentType(); try { FileUtils.copyInputStreamToFile(myfile.getInputStream(),new File("f:/temp/uploads/"+fileName)); } catch (IOException e) { e.printStackTrace(); } } ses.setAttribute("msg","文件上傳成功"); return "redirect:/file/fileload"; } } IO流读写文件

    FileUtils.copyInputStreamToFile(MultipartFile myfile ,File file);

    学后拓展:使用OSS云存储下载图片

    Processed: 0.013, SQL: 9