Spring boot 国际化 eng 没有效果

标签 spring spring-boot spring-mvc

我想将 th:text = "#{title.text}" 更改为 eng lang 但它显示泰语 lang 我尝试根据 this exmple 更改代码 但它不起作用。

输出放入页面登录?lang=en enter image description here 登录 Controller

package com.gpch.hotel.controller;

import javax.validation.Valid;

import com.gpch.hotel.model.User;
import com.gpch.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }




}

Login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head >    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title th:text = "#{title.text}"></title>
    <!-- Custom fonts for this template-->
    <link th:href="@{/vendor/fontawesome/css/all.min.css}" rel="stylesheet" type="text/css">
    <!-- Custom styles bootstrap 4.3.1 sb users-->
    <link rel="stylesheet" th:href="@{/css/sb-admin/sb-admin-2.min.css}">

    <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
          rel="stylesheet"></head>


<body class="bg-gradient-primary">
<div class="container">
    <div class="row justify-content-center">
        <div class="col-xl-5 col-lg-12 col-md-9">
            <div class="card o-hidden border-0 shadow-lg my-5">
                <div class="card-body">
                    <div class="mx-auto">
                        <div class="p-5">
                            <div class="text-center">
                                <form th:action="@{/login}" method="POST" class="user">
                                    <div class="form-group">
                                        <i class="fas fa-hotel fa-5x rotate-15"></i>
                                    </div>
                                    <div class="form-group">
                                        <h1 class="h4 text-gray-900 mb-4" th:text = "#{title.text}"></h1>
                                    </div>
                                    <div th:if="${param.error} " class="alert alert-danger alert-dismissible">
                                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                                        Email or Password invalid
                                    </div>

                                    <div class="form-group">
                                        <input type="email" class="form-control form-control-user"
                                               th:placeholder="Emailaddress"
                                               id="email" name="email">
                                    </div>
                                    <div class="form-group">
                                        <input type="password" class="form-control form-control-user"
                                               th:placeholder="Password"
                                               id="password" name="password">
                                    </div>
                                    <button class="btn btn-primary btn-user btn-block" name="Submit" value="Login"
                                            type="Submit"
                                            th:text="Login"></button>
                                    <p class="mt-5 mb-3 text-muted">@ CopyRight by Bearhug Teamwork 2019 Template by SB
                                        Admin 2 </p>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


</div>
<!-- script fragment -->
<script th:replace="~{fragments/script :: script}"></script>
<!-- End script fragment -->
</body>
</html>

messages_th.properties

title.text=\u0e23\u0e30\u0e1a\u0e1a\u0e01\u0e32\u0e23\u0e08\u0e31\u0e14\u0e01\u0e32\u0e23\u0e42\u0e23\u0e07\u0e41\u0e23\u0e21

messages.properties

title.text=Hotel management System

安全配置

package com.gpch.hotel.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.
                jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
                authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/dashboard").hasAnyAuthority("ADMIN","MANAGER")
                .antMatchers("/users/**").hasAnyAuthority("ADMIN")
                .antMatchers("/employees/**").hasAnyAuthority("ADMIN","MANAGER")
                .antMatchers("/products/**","/products/**").hasAnyAuthority("ADMIN","MANAGER","STAFF")
                .antMatchers("/maintenances/**").hasAnyAuthority("ADMIN","STAFF","MANAGER").anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/login").failureUrl("/login?public=true")
                .defaultSuccessUrl("/dashboard")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**", "/static/**", "/css/**", "/images/**","/vendor/**");
    }

}

WebMvcConfig

package com.gpch.hotel.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

@Configuration

public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US);
        return localeResolver;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

酒店应用

package com.gpch.hotel;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HotelApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotelApplication.class, args);
    }

}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gpch</groupId>
    <artifactId>hotel</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hotel</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

最佳答案

您缺少的是 messages.properties 中的两个或(所有其他语言)文件中的相同文本 和 messages_th.properties

假设标题是你好

messages.properties

title.text = hello 

messages_th.properties

title.text = \u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35

泰语中酒店管理系统的等效项是 ระบบการจัดการโรงแรม

Unicode: \u0E23\u0E30\u0E1A\u0E1A\u0E01\u0E32\u0E23\u0E08\u0E31\u0E14\u0E01\u0E32\u0E23\u0E42\u0E23\u0E07\u0E41\u0E23\u0E21

当您将泰语中的 hello 粘贴到 IDE 中时,Google 翻译会将泰语中的 hello 翻译为 สวัสดี,它可能会自动转换为 Unicode(对于 Windows 上的 Eclipse)

Translate

enter image description here


更新:

可能您错过了我在 HTML 或类似操作中根据语言更改内容的操作 window.location.replace('international?lang=' + selectedOption);

messages.properties

title.text = Hello
lang.change=Change the language
lang.eng=English
lang.th=Thai

messages_th.properties

title.text= \u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35
lang.change=\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E20\u0E32\u0E29\u0E32
lang.eng=\u0E2D\u0E31\u0E07\u0E01\u0E24\u0E29
lang.th=\u0E44\u0E17\u0E22

Controller

 @RequestMapping(value = "/international" , method = RequestMethod.GET)
        public ModelAndView login() {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("login");
            return modelAndView;
 }

HTML

.....

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
    $("#locales").change(function () {
        var selectedOption = $('#locales').val();
        if (selectedOption != ''){
            window.location.replace('international?lang=' + selectedOption);
        }
    });
});
</script>

<body class="bg-gradient-primary">

<span th:text="#{lang.change}"></span>:
<select id="locales">
    <option value=""></option>
    <option value="en" th:text="#{lang.eng}"></option>
    <option value="th" th:text="#{lang.th}"></option>
</select>

</body>
</html>

WebMvcConfig

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
       registry.addViewController("/international").setViewName("login.html");
    }

enter image description here enter image description here

关于Spring boot 国际化 eng 没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57265746/

相关文章:

java - 在 Spring 中自动映射 CrudRepository 与默认的 Rest URI 端点

java - 如何使用多个spring配置文件

java - spring boot多行import.sql application.yml配置

java - Spring MVC : RequestMapping not working, 未识别 URL 路径

java - 如何使用 Jackson 将嵌套的 ObjectId 序列化为 String?

java - @Value注释不返回值

tomcat - Spring 启动 : Tomcat Embedded with HTTP/2 and TLS

java - 为什么不使用@Autovired Session Factory? Java hibernate Spring

java - spring boot删除 Controller 中的员工代码困惑

java - Spring 启动 oauth2 : No userInfo endpoint - How to load the authentication (Principal) from the JWT access token directly in the client