springboot之restfulcrud&国际化

1、默认访问首页

HelloController中
@RequestMapping({"/","/index.html"})
   public String index(){
        return "index";
    }

或者MyMvcConfig implements WebMvcConfigurer中

package com.cnstrong.springboot04webrestfulcrud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//使用WebMvcConfigurer可以扩展springmvc功能
//@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //设置视图映射规则,把什么请求映射到什么页面
        registry.addViewController("/student").setViewName("success");
    }

    //所有的WebMvcConfigurer组件都会一起起作用
    @Bean//将组件注册在容器
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer configurer = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return configurer;
    }
}
将index.html两个都不勾选shift+F6改为login.html    http://localhost:8080/和http://localhost:8080/index.html都访问login.html页面

访问webjars官网

pom.xml添加

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.3.1</version>
</dependency>

当前项目下发所有的webjars请求都要去类路径下的resources/webjars下面找

login.html的链接修改为:

<!-- Bootstrap core CSS webjars的-->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.css}" rel="stylesheet" />
<!-- Custom styles for this template 自定义的-->
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet" />
<img class="mb-4" src="./login_files/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72" />

@语法引入路径的好处:

修改resources/application.properties

server.servlet.context-path=/crud

src中会自动的加上项目名的访问路径

2、页面的国际化

springmvc时:

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

=========

springboot

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

resources下新建一个文件夹i18n

新建login.properties,login_zh_CN.properties

idea出现国际化视图

于是新建了login_en_US.properties

2)springboot自动配置好了管理国际化资源文件的组件

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.messages")
public MessageSourceProperties messageSourceProperties() {
   return new MessageSourceProperties();
}
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
   ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
   if (StringUtils.hasText(properties.getBasename())) {
      //设置国际化资源文件的基础名(去掉语言国家代码的)
      messageSource.setBasenames(StringUtils
            .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
   }
   if (properties.getEncoding() != null) {
      messageSource.setDefaultEncoding(properties.getEncoding().name());
   }
   messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
   Duration cacheDuration = properties.getCacheDuration();
   if (cacheDuration != null) {
      messageSource.setCacheMillis(cacheDuration.toMillis());
   }
   messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
   messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
   return messageSource;
}

进入到MessageSourceProperties中

public class MessageSourceProperties {

   /**
    * 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.基础名如果不包含一个指定包名,就从类路径的根目录下寻找
    */
   //我们的配置文件可以直接放在类路径下叫messages.properties
   private String basename = "messages";

修改application.properties

spring.messages.basename=i18n.login

3)去页面获取国际化的值

thymeleaf中   使用#{}读取国际化信息

    [[${session.user.name}]]  行内表达式

<label  class="sr-only" th:text="#{login.username}">Username</label>
<input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""/>
<label for="inputPassword" class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" id="inputPassword" 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>

网页出现乱码:properties内的中文需要转换为ascii码

这只是修改当前项目的设置,若是全局的,则需要

原理:

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

WebMvcAutoConfiguration
@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;
}

点进AcceptHeaderLocaleResolver

@Override
public Locale resolveLocale(HttpServletRequest request) {
   Locale defaultLocale = getDefaultLocale();
   if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
      return defaultLocale;
   }
   Locale requestLocale = request.getLocale();
   List<Locale> supportedLocales = getSupportedLocales();
   if (supportedLocales.isEmpty() || supportedLocales.contains(requestLocale)) {
      return requestLocale;
   }
   Locale supportedLocale = findSupportedLocale(request, supportedLocales);
   if (supportedLocale != null) {
      return supportedLocale;
   }
   return (defaultLocale != null ? defaultLocale : requestLocale);
}

默认根据请求头带来的区域信息获取Loacle进行国际化

修改:

当前项目下

<a href="#" class="btn btn-sm" th:href="@{/index.html(lg='zh_CN')}">中文</a>
<a href="#" class="btn btn-sm" th:href="@{/index.html(lg='en_US')}">English</a>

http://localhost:8080/crud/index.html?lg=en_US

此时区域信息解析器还是根据请求头来的

新建component包MyLocaleResolver类

package com.cnstrong.springboot04webrestfulcrud.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 request) {
        String lg = request.getParameter("lg");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(lg)){
            String[] split= lg.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

MyMvcConfig中添加

@Bean
public LocaleResolver localeResolver(){
    return new MyLocaleResolver();
}

//参数上没有区域信息的用默认的区域信息解析器,否则用自己的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值