资源引入&国际化

138 阅读4分钟

这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

资源引入

上一篇,我们说完了配置,现在应该导入我们的资源,因为这一篇还不涉及到我们的实体类,所以暂且先不列举

有一些资源文件因为无法上传在另一篇文章中。

画框的是我们主要用到的

最先我们导入我们的登录页面

<!DOCTYPE html>
<html lang="en">
	<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" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="asserts/css/signin.css" rel="stylesheet">
	</head>

	<body class="text-center">
		<form class="form-signin" action="dashboard.html">
			<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
			<label class="sr-only">Username</label>
			<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
			<label class="sr-only">Password</label>
			<input type="password" class="form-control" placeholder="Password" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me"> Remember me
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm">中文</a>
			<a class="btn btn-sm">English</a>
		</form>

	</body>

</html> 

我们这个文件要放在templates文件夹下面,这样才能被我们的MVC模板解析解析到

这个时候我们运行项目我们可能打开的并不是这个首页,而是我们原来的那个

crud是我在配置文件中配置的项目路径

那怎么样才能转到我们的这个页面呢?

第一种方法:

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

将这个方法添加到我们的Controller中,就可以访问我们的登录页面了

第二种方法:

我们也可以在我们的MVC配置中添加我们的视图映射直接跳转到我们的登陆页面

下面是代码

 @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("main.html").setViewName("dashboard");

            }
        };
        return webMvcConfigurer;
    }

我们的好多资源都默认引用到我们静态文件夹下,如果是公共资源,我们可以引用webjars

引用该jar

在我们html中使用th和@进行更改

国际化

在我们的登陆页面中应该有好几种语言,我们需要让他适应多种语言环境

1)、编写国际化配置文件;

2)、使用ResourceBundleMessageSource管理国际化资源文件

3)、在页面使用fmt:message取出国际化内容

编写国际化配置文件

抽取页面需要显示的国际化消息,首先我们创建几个文件

其中资源包是我们的idea自己生成的,我们只需要创建资源包下面的文件,当idea检测到我们要创建国际化文件时,就会自动生成这个文件包


创建文件之后,我们去更改一下我们的文件编码,如果编码不正确,最后显示出来会乱码

这些工作做完之后我们开始编写国际化文件

#中文界面
login.tip=请登录
login.password=密码
login.btn=登录
login.username=用户名
login.remember=记住我

#英文界面
login.tip=Please sign in
login.password=password
login.btn=Log in 
login.username=username
login.remember=remember

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

我们去application文件中设置国际化资源文件的路径

修改登录页面,获取国际化值

在文章之后我们会列举我们的文件,这里只标出我们需要修改的地方。

这些做完之后,我们在浏览器上就能切换界面的中英文了,但是并不是通过按钮切换,而是通过我们去切换浏览器的首选语言切换

想要用链接切换,那我们就要去了解页面是怎么通过语言设置切换中英文的,我们按F12,查看请求头

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

编写一个组件

在连接上携带区域信息,去继承LocaleResolver(获取区域信息对象),重写其中方法resolveLocale(解析区域信息)

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        System.out.println("aaaa"+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, Locale locale) {

    }
}

我们组件写完了,我们需要把他加在容器中

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

最后在修改一下我们的按键,使他带上我们的请求

<!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" th:action="@{/user/login}" method="post">
    <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 sign in</h1>
    <!--判断-->
    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    <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 class="sr-only" th:text="#{login.password}">Password</label>
    <input type="password" name="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="@{/index.html(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>

</html>