国际化和文件上传

国际化和文件上传

国际化

  1. 国际化(internationalization)

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

  2. java.util.Locale

    语言代码_国家代码

    注:国家代码可省略
    zh_CN

  3. ResourceBundle 加载资源文件(中英双语)

    i18n_zh_CN.properties
    i18n_en_US.properties

     		   //test是属性文件的名字,不写语言代码、国家代码,后缀名properties
     		  
     		   String path = "i18n";
     		   ResourceBundle bundle = ResourceBundle.getBundle(path, Locale.CHINA);
     		   String yhzhLabel = bundle.getString("yhzh.label");
     		
     		    
    
     		   <!--注1:需修改pom.xml将国际化资源文件输出到target文件夹-->
     		   <resource>
     		   	<directory>src/main/resources</directory>
     		        <includes>
     		                <!--<include>jdbc.properties</include>-->
     		                <include>*.properties</include>
     		                <include>*.xml</include>
     		        </includes>
     		   </resource>
    
  4. 复合消息

     		   message=hello {0}, my name is {1}
     		   java.text.MessageFormat.format(message, "zs", "ls");
     		   
     		   String message = bundle.getString("message");
    
  5. springmvc 实现动态国际化(中英双语)

    5.1 提供中英双语资源文件

    例如:

    i18n_en_US.properties
    i18n_zh_CN.properties

    5.2 通过 ResourceBundleMessageSource 加载资源文件(basenames属性)

     		       <!--1) 配置国际化资源文件 -->
     		      <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
     				<property name="basenames">
     					<list> 
     		                            <value>i18n</value>
     					</list>
     				</property>
     		       </bean>
    

    注意:必须叫messageSource!!!必须叫messageSource!!!必须叫messageSource!!!(重要的事情说三遍)

    可在开发阶段使用ReloadableResourceBundleMessageSource它能自动重新加载资源文件

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

    5.3.1 配置语言区域解析器

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

    注意:必须叫localeResolver!!!必须叫localeResolver!!!必须叫localeResolver!!!(重要的事情说三遍)

    5.3.2 语言解析器的类型

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

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

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

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

    5.5 springmvc的message标签输出

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

    为什么在 index.jsp 使用< t:message code=“user_name”/>会报错

    原因是在web.xml中配置的DispatcherServlet的url-pattern为“/”,不会匹配访问.jsp的url,
    所以直接访问首页并不会经过DispatcherServlet,导致无法读取到资源文件

    解决方案:首页转发到/WEB-INF/jsp/login.jsp即可

    切换语言的关键代码(系统必须使用SessionLocaleResolver解析器)

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

    5.6 后台代码获取国际化信息

    5.6.1 后台通过springmvc的消息机制显示消息

    5.6.2 通过RequestContext获得国际化的消息

     		RequestContext requestContext = new RequestContext(request);
     		String errorMsg = requestContext.getMessage("login.error.label");
     		System.out.println("errorMsg:" + errorMsg);
    

文件上传

struts 文件上传:

			1、定义一个上传的页面
			
						<form action="" method="post" entype="mutilpart/form-data">
							<input type="file" name="XXX">
						</form>
			
			2、定义一个子控制器
			
						private File XXX;//接受页面传递过来的文件对象
						private String XXXFileName;
						private String XXXContextType;
			
			3、文件上传的核心思想
			
						将一个文件从一个地方(本地)复制到另一个地方(服务器)
						FileUtil.copyFile(source,new File("d://"););

SpringMVC 文件上传:

			1、定义一个上传的页面
			
						<form action="" method="post" entype="mutilpart/form-data">
							<input type="file" name="XXX">
						</form>
						
			2、定义一个子控制器,controller
			
						方法中用一个参数去接受传递过来的文件对象
					
			3、文件上传的核心思想
		
						将一个文件从一个地方(本地)复制到另一个地方(服务器)
						FileUtil.copyFile(source,new File("d://"););

SpringMVC 与 struts2 的区别:

  • 1、struts 核心处理器 是过滤器 StrutsPrepareAndExcuterFilter

    SpringMVC 的核心处理器 是 **servlet(DispatcherServlet)**
    
  • 2、struts 是多例

    SpringMVC 是单例

  • 3、struts是基于类编程

    SpringMVC 是基于方法编程

  1. springmvc 的文件上传
    对比以下struts:

    struts文件上传:

    • 1、二进制存在数据库

    • 2、存储到具体的硬盘目录

    • 3、存储到服务器中

      真实路径与虚拟路径

      通过虚拟路径获取真实路径

        			request.getservletContext.getrealPath(虚拟路径);
        			fileutil.copyInputStreamtofile(file.getInput);
        			
        			fileutil.copyofile(file,new file(真路径))
      

    6.1 添加文件上传相关依赖

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

    6.2 在 springmvc-servlet.xml 配置文件上传解析器(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>
    

    6.3 表单提交方式为method=“post” enctype="multipart/form-data"
    upload.jsp

    	<%--
    	  Created by IntelliJ IDEA.
    	  User: Admin
    	  Date: 2019/9/29
    	  Time: 22:32
    	  To change this template use File | Settings | File Templates.
    	--%>
    	<%@ page contentType="text/html;charset=UTF-8" language="java" %>
    	<html>
    	<head>
    	    <title>SpringMVC 文件上传</title>
    	</head>
    	<body>
    	    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    	        上传文件:<input type="file" name="img" >
    	        <button type="submit">提交</button>
    	    </form>
    	</body>
    	</html>
    	
    

    6.4 文件项用spring提供的MultipartFile进行接收

    json处理 : 在方法上面加上@ResponseBody这个注解就好了

    HelloController

    	@RequestMapping("/upload")
    	    public String upload(MultipartFile img) throws IOException {
    	        FileUtils.copyInputStreamToFile(img.getInputStream(),new File("D:/yyy/"+img.getOriginalFilename()));
    	        return "forward:upload";
    	    }
    

    6.5 IO流读写文件

    工具类:

    JSONResult

    	package com.dj.util;
    	
    	public class JSONResult {
    	
    	    // 响应业务状态
    	    private Integer status;
    	
    	    // 响应消息
    	    private String msg;
    	
    	    // 响应中的数据
    	    private Object data;
    	    
    	    private String ok;    // 不使用
    	
    	    public static JSONResult build(Integer status, String msg, Object data) {
    	        return new JSONResult(status, msg, data);
    	    }
    	
    	    public static JSONResult ok(Object data) {
    	        return new JSONResult(data);
    	    }
    	
    	    public static JSONResult ok() {
    	        return new JSONResult(null);
    	    }
    	    
    	    public static JSONResult errorMsg(String msg) {
    	        return new JSONResult(500, msg, null);
    	    }
    	    
    	    public static JSONResult errorMap(Object data) {
    	        return new JSONResult(501, "error", data);
    	    }
    	    
    	    public static JSONResult errorTokenMsg(String msg) {
    	        return new JSONResult(502, msg, null);
    	    }
    	    
    	    public static JSONResult errorException(String msg) {
    	        return new JSONResult(555, msg, null);
    	    }
    	
    	    public JSONResult() {
    	
    	    }
    	
    	    public JSONResult(Integer status, String msg, Object data) {
    	        this.status = status;
    	        this.msg = msg;
    	        this.data = data;
    	    }
    	
    	    public JSONResult(Object data) {
    	        this.status = 200;
    	        this.msg = "OK";
    	        this.data = data;
    	    }
    	
    	    public Boolean isOK() {
    	        return this.status == 200;
    	    }
    	
    	    public Integer getStatus() {
    	        return status;
    	    }
    	
    	    public void setStatus(Integer status) {
    	        this.status = status;
    	    }
    	
    	    public String getMsg() {
    	        return msg;
    	    }
    	
    	    public void setMsg(String msg) {
    	        this.msg = msg;
    	    }
    	
    	    public Object getData() {
    	        return data;
    	    }
    	
    	    public void setData(Object data) {
    	        this.data = data;
    	    }
    	
    	    public String getOk() {
    	        return ok;
    	    }
    	
    	    public void setOk(String ok) {
    	        this.ok = ok;
    	    }
    	
    	}
    
    
    	@ResponseBody
    	    @RequestMapping("/jsonData3")
    	    public JSONResult jsonData3(){
    	        Map map = new HashMap();
    	
    	        return JSONResult.ok("成功:这里可以存放字符串、对象、数组、集合都行,这样可以节省拼接map集合的过程");
    	    }
    	
    	    @ResponseBody
    	    @RequestMapping("/jsonData4")
    	    public JSONResult jsonData4(){
    	        return JSONResult.errorMsg("失败:这里可以存放字符串、对象、数组、集合都行,这样可以节省拼接map集合的过程");
    	    }
    

    6.6 保存文件上传记录

     		     springmvc文件上传关键代码
     		   
     		      File targetFile = ....;
     		      MultipartFile mf = ....;
     		      String fileName = mf.getOriginalFilename(); 
     		      mf.transferTo(targetFile);
    
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值