siye@r480:~/svlution/workspace/springmvc4322$ tree src/
src/
├── main
│ ├── java
│ │ ├── log4j.properties
│ │ └── ocn
│ │ └── site
│ │ └── springmvc
│ │ ├── controller
│ │ │ └── Manicontroller.java
│ │ └── setup
│ │ ├── Appconfig.java
│ │ └── Webxmlconfig.java
│ ├── resources
│ │ └── i18n
│ │ ├── message_en_US.properties
│ │ └── message_zh_CN.properties
│ └── webapp
│ ├── index.jsp
│ └── WEB-INF
│ ├── register.jsp
│ └── web.xml
└── test
├── java
│ └── ocn
│ └── site
│ └── springmvc
│ └── controller
│ └── Runtest.java
└── resources
└── config
└── application.xml
19 directories, 11 files
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.22.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.22.RELEASE</version>
<scope>test</scope>
</dependency>
package ocn.site.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.support.RequestContext;
@Controller
public class Manicontroller {
private final Logger logger = Logger.getLogger(this.getClass());
@GetMapping("/test")
public String handler(HttpServletRequest request) {
RequestContext context = new RequestContext(request);
logger.info(context.getMessage("key"));
return "register";
}
}
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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan({ "ocn.site.springmvc.controller", "ocn.site.springmvc.domain" })
public class Appconfig extends WebMvcConfigurerAdapter {
private final static String PREFIX = "/WEB-INF/";
private final static String SUFFIX = ".jsp";
@Bean("messageSource")
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 CookieLocaleResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver getViewResolver() {
return new InternalResourceViewResolver(PREFIX, 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;
public class Webxmlconfig extends AbstractAnnotationConfigDispatcherServletInitializer {
private final static String ENCODING = "utf-8";
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { Appconfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[] { new CharacterEncodingFilter(ENCODING, true), new HiddenHttpMethodFilter() };
}
}
<%@ 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>
<spring:message code="key"></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>
<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?locale=zh_CN">chinese</a>
<a href="test?locale=en_US">english</a>
</body>
</html>
key=english
key=\u4E2D\u6587
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="ocn.site.springmvc.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n.message"></property>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"></bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
package ocn.site.springmvc.controller;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:config/application.xml")
public class Runtest {
private final Logger logger = Logger.getLogger(this.getClass());
private @Autowired WebApplicationContext wac;
@Test
public void chinese() throws Exception {
run("zh_CN");
}
@Test
public void english() throws Exception {
run("en_US");
}
private void run(String localename) throws Exception {
MockMvc build = MockMvcBuilders.webAppContextSetup(this.wac).build();
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/test");
requestBuilder.param("locale", localename);
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("register"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
}
19-09-05 11:03:37 org.springframework.test.context.web.WebTestContextBootstrapper =====>>> Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19-09-05 11:03:37 org.springframework.test.context.web.WebTestContextBootstrapper =====>>> Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6d78f375, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@50c87b21, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5f375618, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1810399e]
19-09-05 11:03:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-05 11:03:38 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Refreshing org.springframework.web.context.support.GenericWebApplicationContext@6eebc39e: startup date [Thu Sep 05 11:03:38 CST 2019]; root of context hierarchy
19-09-05 11:03:38 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping =====>>> Mapped "{[/test],methods=[GET]}" onto public java.lang.String ocn.site.springmvc.controller.Manicontroller.handler(javax.servlet.http.HttpServletRequest)
19-09-05 11:03:38 org.hibernate.validator.internal.util.Version =====>>> HV000001: Hibernate Validator 5.2.0.Final
19-09-05 11:03:39 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@6eebc39e: startup date [Thu Sep 05 11:03:38 CST 2019]; root of context hierarchy
19-09-05 11:03:39 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@6eebc39e: startup date [Thu Sep 05 11:03:38 CST 2019]; root of context hierarchy
19-09-05 11:03:39 org.springframework.mock.web.MockServletContext =====>>> Initializing Spring FrameworkServlet ''
19-09-05 11:03:39 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization started
19-09-05 11:03:39 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization completed in 18 ms
19-09-05 11:03:39 ocn.site.springmvc.controller.Manicontroller =====>>> 中文
19-09-05 11:03:39 ocn.site.springmvc.controller.Runtest =====>>> test finished
19-09-05 11:03:39 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Closing org.springframework.web.context.support.GenericWebApplicationContext@6eebc39e: startup date [Thu Sep 05 11:03:38 CST 2019]; root of context hierarchy
public static final String DEFAULT_PARAM_NAME = "locale";
private String paramName = DEFAULT_PARAM_NAME;
public void setParamName(String paramName) {
this.paramName = paramName;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {
String newLocale = request.getParameter(getParamName());
if (newLocale != null) {
if (checkHttpMethod(request.getMethod())) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver == null) {
throw new IllegalStateException(
"No LocaleResolver found: not in a DispatcherServlet request?");
}
try {
localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
}
catch (IllegalArgumentException ex) {
if (isIgnoreInvalidLocale()) {
logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + ex.getMessage());
}
else {
throw ex;
}
}
}
}
return true;
}