zoukankan      html  css  js  c++  java
  • 国际化相关

    国际化相关

    来段注释:

    /***
     * ┌───┐   ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
     * │Esc│   │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│  ┌┐    ┌┐    ┌┐
     * └───┘   └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘  └┘    └┘    └┘
     * ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
     * │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
     * ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
     * │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ |  │ │Del│End│PDn│ │ 7 │ 8 │ 9 │   │
     * ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
     * │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter  │               │ 4 │ 5 │ 6 │   │
     * ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤     ┌───┐     ├───┼───┼───┼───┤
     * │ Shift  │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│  Shift   │     │ ↑ │     │ 1 │ 2 │ 3 │   │
     * ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
     * │ Ctrl│    │Alt │         Space         │ Alt│    │    │Ctrl│ │ ← │ ↓ │ → │ │   0   │ . │<─┘│
     * └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
     */
    1.  默认访问首页
    //使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
    //@EnableWebMvc 不要接管SpringMVC
    @Configuration
    public class MyMvcConfig extends WebMvcConfigurerAdapter {  
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    // super.addViewControllers(registry);
    //浏览器发送 /atguigu 请求来到 success
    registry.addViewController("/atguigu").setViewName("success");
    } 

    //所有的WebMvcConfigurerAdapter组件都会一起起作用 @Bean //将组件注册在容器 public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login");
    //index.html 请求 转到login ,即定位首页登陆 registry.addViewController("/index.html").setViewName("login"); } }; return adapter; } }

      2.国际化

    • 编写国际化配置文件
    • 使用 ResourceBundleMessageSource 管理国际化资源文件
    • 在页面使用 fmt:message 取出国际化内容。

    步骤:

    • 编写国际化配置文件,抽取页面需要显示的国际化消息

     

    • springboot 自动配置好了管理国际化资源文件的组件
    @ConfigurationProperties(prefix = "spring.messages")
      public class MessageSourceAutoConfiguration {
    /**
    * Comma‐separated list of basenames (essentially a fully‐qualified classpath
    * location), each following the ResourceBundle convention with relaxed support for
    * slash based locations. If it doesn't contain a package qualifier (such as
    * "org.mypackage"), it will be resolved from the classpath root.
    */
    private String basename = "messages";
    //我们的配置文件可以直接放在类路径下叫messages.properties;
    @Bean
    public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    if (StringUtils.hasText(this.basename)) {
    //设置国际化资源文件的基础名(去掉语言国家代码的)
    messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
    StringUtils.trimAllWhitespace(this.basename)));
      } 
    if (
    this.encoding != null) { messageSource.setDefaultEncoding(this.encoding.name());     }
    messageSource.setFallbackToSystemLocale(
    this.fallbackToSystemLocale); messageSource.setCacheSeconds(this.cacheSeconds); messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat); return messageSource; }
    • 去页面获取国际化的值

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta http‐equiv="Content‐Type" content="text/html; charset=UTF‐8">
    <meta name="viewport" content="width=device‐width, initial‐scale=1, shrink‐to‐
    fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Signin Template for Bootstrap</title>
    <!‐‐ Bootstrap core CSS ‐‐>
    <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
    <!‐‐ Custom styles for this template ‐‐>
    <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}"rel="stylesheet">
    </head> <body class="text‐center"> <form class="form‐signin" action="dashboard.html"> <img class="mb‐4" th:src="@{/asserts/img/bootstrap‐solid.svg}" src="asserts/img/bootstrap‐solid.svg" alt="" width="72" height="72"> <h1 class="h3 mb‐3 font‐weight‐normal" th:text="#{login.tip}">Please signin</h1> <label class="sr‐only" th:text="#{login.username}">Username</label> <input type="text" class="form‐control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""> <label class="sr‐only" th:text="#{login.password}">Password</label> <input type="password" class="form‐control" placeholder="Password" th:placeholder="#{login.password}" required="">
    <div class="checkbox mb‐3"> <label> <input type="checkbox" value="remember‐me"/> [[#{login.remember}]] </label> </div> <button class="btn btn‐lg btn‐primary btn‐block" type="submit" th:text="# {login.btn}">Sign in</button> <p class="mt‐5 mb‐3 text‐muted">© 2017‐2018</p>
    <a class="btn btn-sm"  th:href="@{/login(l='zh_CN')}">中文</a>
    <a class="btn btn-sm"  th:href="@{/login(l='en_US')}">English</a>
    </form>

    </body>
     </html>

     效果:

    根据浏览器语言设置的信息切换了国际化;

    原理:

    国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象); 

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
    public LocaleResolver localeResolver() {
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
    return new FixedLocaleResolver(this.mvcProperties.getLocale());
    } 
    AcceptHeaderLocaleResolver localeResolver
    = new AcceptHeaderLocaleResolver(); localeResolver.setDefaultLocale(this.mvcProperties.getLocale()); return localeResolver; } 默认的就是根据请求头带来的区域信息获取Locale进行国际化
    •  点击链接切换国际化
    /**
    * 可以在连接上携带区域信息
    */
    public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
            String l = request.getParameter("l");
             Locale locale = Locale.getDefault();
                if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
        locale = new Locale(split[0],split[1]);
        } 
    return locale;
    } 
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Localelocale) {
      }
    }
    @Bean
    public LocaleResolver localeResolver(){     return new MyLocaleResolver();   } }

     3.  登陆

    模板引擎页面修改之后,要实时生效,需要做一些操作

      1.禁用模板缓存

    spring.thymeleaf.cache=false

      2.页面修改了之后,Ctrl +F9  重新编译

       登陆错误的消息显示

    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

    4.使用拦截器进行登陆检查

    /**
    * 登陆检查,
    */
    public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
    Object handler) throws Exception {
    Object user = request.getSession().getAttribute("loginUser");
    if(user == null){
    //未登陆,返回登陆页面
    request.setAttribute("msg","没有权限请先登陆");
    request.getRequestDispatcher("/index.html").forward(request,response);
    return false;
    }else{
    //已登陆,放行请求
    return true;
        }
    }
     @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
        handler, ModelAndView modelAndView) throws Exception {
    }
     @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
    Object handler, Exception ex) throws Exception {
        }
    }

    注册拦截器

    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
    WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("login");
    registry.addViewController("/index.html").setViewName("login");
    registry.addViewController("/main.html").setViewName("dashboard");
      } 
    //注册拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { //super.addInterceptors(registry); //静态资源; *.css , *.js //SpringBoot已经做好了静态资源映射 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");  }   }; return adapter; }

     

    参照别人的详情

     详细的国际化配置

    听起来高大上的国际化,起始就是在利用浏览器语言,或者页面中的中英文切换,将页面的文字在其他语言和中文进行切换,比如:

    我们想让这个功能实现,点击中文,页面就是中文的,点击英文就是英文的。

    国际化配置

      那么我们来看,SpringBoot默认是按照你浏览器的语言来切换中英文的,配置文件呢,我们可以在resources中这样写:

    1. 新建一个名叫“i18n”的包,我们用来存放国际化配置,然后在这个包下,我们再创建几个properties的配置文件,用来配置语言:

      如图方式,我们创建3个文件,分别是无语言配置时候生效的login.properties;中文生效的login_zh_CN.properties;英文生效的login_en_US.properties; 

      也就是以下划线的组合:文件名_区域_语言.properties;当我们这样命名生成文件后,IDEA也会帮我们识别这是个国际化配置包,自动转换成如下的模式:

      当然变成如上模式的时候,我们再需要添加配置文件,直接在包右键new就可以了

    方便了许多~

    2. 我们要在这些配置文件里做些改动,先来点击login_en_US的配置文件,然后点击下边如图所示的Resource Bundle的按钮,切换编辑模式:

      按照如图的方法,点击加号,添加一个key,我们取名叫login.tip就是页面中用到的提示的意思

     接下来,按照我们页面需要转换的量,来做配置,如下图(我把等下登录页要用的都配置好了):

    还没完,不要急,看起来复杂,学会了就简单了,后边我们需要将页面上引用这些值,来看。

    记得在我们的application.properties中添加配置参数,让我们的配置生效:

    spring.messages.basename=i18n.login

    HTML页-配置

      基于之前的文章,我们了解到Thymeleaf中的语法中@和#的作用,看看如何使用,先直接上图:

      前边表单里我们将所有需要的参数用#{xx.yy}的形式,按照配置的国际化参数都设置好,为了使用模板,我们需要用到th:text之类的参数来替换原来的参数。(注意看原来页有同样的text、placeholder等参数)

     而为了使Thymeleaf模板生效,别忘了在html的参数中加上这句xmlns:

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>

      这样,我们就可以在切换浏览器语言的情况下,进行中英文切换了,设置方法以chrome举例(需要英文就添加英文置顶):

    自定义配置,使我们页面中的中英文切换生效

    有耐心的同学,我们来看一下正题,怎么使自己的配置生效:

    1.  文章顶部的截图,我们看到的中英文按钮的HTML,我们来看,如何配置:

      注意,我这里将访问的页面其实是;localhost:8080/index.html?l=zh_CN,这也是我们点击中文按钮以后生成的链接。在Thymeleaf的模板语法中,参数是不用“?”的,而是使用小括号,然后参数按照key=value的形式设置,注意单引号;

    2. 为了让自定义的配置生效,我们要做的就是覆盖或改变默认的配置,那么我们新建一个文件 MyLocaleResolver,用来实现 LocaleResolver 接口的作用; 

      具体方法:(因为我们的区域是用下划线“_”来配置的,所以这里用分隔符来取得区域和语言,放到request中)

    复制代码
    package com.iceodin.common.component;
    
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.LocaleResolver;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Locale;
    
    /**
     * 在链接上携带区域信息
     */
    public class MyLocaleResolver implements LocaleResolver {
    
        @Override
        public Locale resolveLocale(HttpServletRequest httpServletRequest) {
            String l = httpServletRequest.getParameter("l");
            Locale locale = Locale.getDefault();
            if (!StringUtils.isEmpty(l)) {
                String[] split = l.split("_");
                locale = new Locale(split[0], split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    
        }
    }
    复制代码

    3. 让我们的配置生效,当然就要把配置加入到SpringBoot的容器中,所以,在之前的配置文件中,加入Bean:

    4. 最好我们来看成果喽:

      默认的语言展示,由于浏览器默认中文,所以:

      然后点击下方English,看url和页面的变化:

      我们再点击中文:

     

  • 相关阅读:
    poi隐藏列
    凯西太太的果园
    java中不可变对象深入理解
    excel添加空白行的快捷键
    如何在多个页面中,引入一个公共组件
    对后端返回的数据进行适配
    我与时间管理的故事
    在前端团队的那些日子(初见)
    我是这样做时间管理的(下)
    我是这样做时间管理的(上)
  • 原文地址:https://www.cnblogs.com/thelovelybugfly/p/11169718.html
Copyright © 2011-2022 走看看