欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

i18n基于session配置

程序员文章站 2022-05-16 09:29:48
...
[email protected]:~/svlution/workspace/springmvc4322$ tree src/
src/
├── main
│   ├── java
│   │   ├── log4j.properties
│   │   └── ocn
│   │       └── site
│   │           └── springmvc
│   │               ├── controller
│   │               │   └── Manicontroller.java
│   │               ├── setup
│   │               │   ├── Appconfig.java
│   │               │   └── Webxmlconfig.java
│   │               └── utils
│   │                   └── ConstraintsUtils.java
│   ├── resources
│   │   └── i18n
│   │       ├── message_en_US.properties
│   │       └── message_zh_CN.properties
│   └── webapp
│       ├── index.jsp
│       └── WEB-INF
│           ├── register.jsp
│           └── web.xml
└── test
    ├── java
    └── resources

15 directories, 10 files
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.22.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
package ocn.site.springmvc.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

///springmvc4322/src/main/java/ocn/site/springmvc/controller/Manicontroller.java
@Controller
public class Manicontroller {

	private final Logger logger = Logger.getLogger(this.getClass());

	@GetMapping("/test/{var}")
	public String handler(HttpServletRequest request, @PathVariable("var") String path, @RequestParam String locale) {
		HttpSession session = request.getSession();
		if ("china".equals(locale)) {
			session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));
		} else if ("english".equals(locale)) {
			session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"));
		} else {
			session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, LocaleContextHolder.getLocale());
		}
		RequestContext requestContext = new RequestContext(request);
		logger.info(requestContext.getMessage("username"));
		logger.info(requestContext.getMessage("passwd"));
		return path;
	}

}
package ocn.site.springmvc.setup;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import ocn.site.springmvc.utils.ConstraintsUtils;

///springmvc4322/src/main/java/ocn/site/springmvc/setup/Appconfig.java
@Configuration
@EnableWebMvc
@ComponentScan({ "ocn.site.springmvc.controller", "ocn.site.springmvc.domain" })
public class Appconfig extends WebMvcConfigurerAdapter {

	// 应当特别关注此处的配置。有时配置错误,会出现以下的错误信息提示
	// No message found under code xxx for locale xxx
	// 出现以上的配置错误,往往有以下几点原因。
	// 1)找不到本地化属性文件,该文件是要放置在src目录下的!
	// 如果内嵌了多层目录,使用英文符号.而不是英文符号/,比如 ocn.site.springmvc.i18n.message
	// 2)本地属性文件名称匹配错误,一般命名为 message_zh_CN.properties
	// 3)相关处理的组件未被正确的注册。
	// 注意!不论是java-config还是xml-config的配置,都是要手动的配置bean的名称的。
	// 这里在测试的时候,使用默认的驼峰命名机制是失败的,具体原因待定。
	// MessageSource相关的组件,一定要命名为 messageSource
	// LocaleResolver相关的组件,一定要命名为 localeResolver
	@Bean(value = ConstraintsUtils.MESSAGE_SOURCE) // must defined beanname
	public MessageSource getMessageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename("i18n.message");
		return messageSource;
	}

	@Bean(value = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
	public LocaleResolver getLocaleResolver() {
		return new SessionLocaleResolver();
	}

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		// TODO Auto-generated method stub
//		super.configureDefaultServletHandling(configurer);
		configurer.enable();
	}

	@Bean
	public ViewResolver getViewResolver() {
		return new InternalResourceViewResolver(ConstraintsUtils.PREFIX, ConstraintsUtils.SUFFIX);
	}

}
package ocn.site.springmvc.setup;

import javax.servlet.Filter;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import ocn.site.springmvc.utils.ConstraintsUtils;

// /springmvc4322/src/main/java/ocn/site/springmvc/setup/Webxmlconfig.java
public class Webxmlconfig extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return new Class<?>[] { Appconfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		// TODO Auto-generated method stub
		return new String[] { "/" };
	}

	@Override
	protected Filter[] getServletFilters() {
		// TODO Auto-generated method stub
		return new Filter[] { new CharacterEncodingFilter(ConstraintsUtils.ENCODING, true),
				new HiddenHttpMethodFilter() };
	}

}
package ocn.site.springmvc.utils;

// /springmvc4322/src/main/java/ocn/site/springmvc/utils/ConstraintsUtils.java
public interface ConstraintsUtils {

	String ENCODING = "UTF-8";
	String PREFIX = "/WEB-INF/";
	String SUFFIX = ".jsp";
	String MESSAGE_SOURCE = "messageSource";

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<!-- /springmvc4322/src/main/webapp/WEB-INF/register.jsp -->
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
	<spring:message code="username"></spring:message>
	<spring:message code="passwd"></spring:message>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
	<display-name>springmvc4322</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- /springmvc4322/src/main/webapp/WEB-INF/web.xml -->
	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<el-ignored>false</el-ignored>
			<scripting-invalid>true</scripting-invalid>
		</jsp-property-group>
	</jsp-config>

</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
	<a href="test/register?locale=china">china</a>
	<a href="test/register?locale=english">english</a>
</body>
</html>
# /springmvc4322/src/main/resources/i18n/message_en_US.properties
username=username
passwd=password
# /springmvc4322/src/main/resources/i18n/message_zh_CN.properties
username=\u7528\u6237\u540D
passwd=\u5BC6\u7801
九月 03, 2019 2:54:56 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 3029 ms
19-09-03 14:55:03 ocn.site.springmvc.controller.Manicontroller  =====>>> 用户名
19-09-03 14:55:03 ocn.site.springmvc.controller.Manicontroller  =====>>> 密码
19-09-03 14:55:06 ocn.site.springmvc.controller.Manicontroller  =====>>> username
19-09-03 14:55:06 ocn.site.springmvc.controller.Manicontroller  =====>>> password