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
上一篇: 显卡供电的隐藏误区:你中招了么?
下一篇: I18N
推荐阅读
-
PHP中SESSION的注销与清除_php技巧
-
使用无限生命期Session的方法
-
关于扩展 Laravel 默认 Session 中间件导致的 Session 写入失效问题分析,laravelsession
-
php中session 与 cookie的区别以及用法
-
PHP基于cookie与session统计网站访问量并输出显示的方法
-
PHP session垃圾回收机制
-
比较全的PHP 会话(session 时间设定)使用入门代码
-
cookie和session的加密?
-
PHP中SESSION丢失(不能跨页面传递)解决办法
-
session.save_path is correct (/var/lib/php/session) in Unknown on line 0