webæ ¡éªç»åi18n
程序员文章站
2022-05-16 10:09:25
...
[email protected]:~/svlution/workspace/springmvc4322$ tree src/
src/
âââ main
â âââ java
â â âââ log4j.properties
â â âââ ocn
â â âââ site
â â âââ springmvc
â â âââ controller
â â â âââ Manicontroller.java
â â âââ domain
â â â âââ User.java
â â âââ setup
â â âââ Appconfig.java
â â âââ Webxmlconfig.java
â âââ resources
â â âââ i18n
â â âââ message_en_US.properties
â â âââ message_zh_CN.properties
â âââ webapp
â âââ index.jsp
â âââ WEB-INF
â âââ register.jsp
â âââ success.jsp
â âââ web.xml
âââ test
âââ java
â âââ ocn
â âââ site
â âââ springmvc
â âââ controller
â âââ Runtest.java
âââ resources
âââ config
âââ application.xml
20 directories, 13 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>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<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.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import ocn.site.springmvc.domain.User;
@Controller
public class Manicontroller {
private final Logger logger = Logger.getLogger(this.getClass());
private @Autowired User user;
private final static String NAME_SUCCESS = "success";
private final static String NAME_REGISTER = "register";
// reference annotation @ControllerAdvice
@ModelAttribute
public void handlerConfig(ModelMap map) {
map.addAttribute("user", user);
logger.info("first config success");
}
@GetMapping("/test")
public String handlerPage() {
return NAME_REGISTER;
}
// 注æäºé¡¹
// æµè¯çéªè¯ç对象è¦æ¯javabean
// BindingResult 对象ä½ä¸ºåæ°ï¼å
¶åé¢å¿
é¡»æ¯@ModelAttribute注解修饰ç对象ï¼å¦åä¼æ¥éã
// An Errors/BindingResult argument is expected to be declared immediately after
// the model attribute, the @RequestBody or the @RequestPart arguments to which
// they apply:
@PostMapping("/register")
public String handlerRegister(@ModelAttribute @Valid User user, BindingResult result, ModelMap map) {
if (result.hasErrors()) {
logger.info(result.getFieldError().getDefaultMessage());
return NAME_REGISTER;
}
map.put("message", "register success");
return NAME_SUCCESS;
}
}
package ocn.site.springmvc.domain;
import java.io.Serializable;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Component;
@Component
public class User implements Serializable {
// springå°æ°æ®æ ¡éªçé误信æ¯ç»å®å¨ FieldError å¯¹è±¡ä¸ èæ¤å¯¹è±¡æ¯ MessageSourceResolvable çå®ç°ç±»
// å¨springmvcçå½é
åæ¡æ¶ä¸ MessageSourceResolvable åæ¯è§£æå½é
åä¿¡æ¯ç对象
// æ
å¯ä»¥å¨æ°æ®æ ¡éªçæ¶å åæ¶ç»å®å½é
åçæ¬çé误信æ¯æ示
// ç»åJSR303ç使ç¨æææ´å å¨å½é
åå±æ§æ件ä¸keyçå¼å°±æ¯ 注解å称.æ è®°å段çç±»å.æ è®°çå段å称
// å¦ Length.user.name
// å¨é¡µé¢ä¸æ¾ç¤ºé误信æ¯çæ¶å æµè¯çç¯å¢ä¸ springçmessageæ ç¾åformçerroræ ç¾ åæ¶æ¯ææ¾ç¤ºå½é
åçä¿¡æ¯æ¾ç¤º
private static final long serialVersionUID = 1L;
private int id;
@Length(min = 4)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
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.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.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";
private final static String BEAN_MESSAGESOURCE = "messageSource";
private final static String i18n_FILEPATH = "i18n.message";
@Bean(BEAN_MESSAGESOURCE)
public MessageSource getMessageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(i18n_FILEPATH);
return messageSource;
}
@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>
<form:form commandName="user" action="register" method="post">
id:<form:input path="id" />
<form:errors path="id"></form:errors>
<br>
name:<form:input path="name" />
<form:errors path="name"></form:errors>
<br>
<form:button>submit</form:button>
</form:form>
</body>
</html>
<%@ 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>
<p>message:${message }</p>
</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">test</a>
</body>
</html>
Length.user.name=username length must >=4
Length.user.name=\u7528\u6237\u540D\u79F0\u7684\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E4
<?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">
<bean id="paramMap" class="org.springframework.util.LinkedMultiValueMap"></bean>
<context:component-scan base-package="ocn.site.springmvc.controller"></context:component-scan>
<context:component-scan base-package="ocn.site.springmvc.domain"></context:component-scan>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n.message"></property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.util.LinkedMultiValueMap;
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;
private MockMvc build;
private @Autowired @Qualifier("paramMap") LinkedMultiValueMap<String, String> map;
@Before
public void init() {
this.build = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void handlerPage() throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/test");
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("register"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
@Test
public void handlerRegister4success() throws Exception {
map.add("id", "34");
map.add("name", "hack");
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register");
requestBuilder.params(map);
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("success"));
ra.andExpect(MockMvcResultMatchers.model().attribute("message", "register success"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
@Test
public void handlerRegister4Failed() throws Exception {
map.add("id", "34");
map.add("name", "liy");
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register");
requestBuilder.params(map);
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("register"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
}
19-09-04 23:39:27 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-04 23:39:27 org.springframework.test.context.web.WebTestContextBootstrapper =====>>> Using TestExecutionListeners: [or[email protected]5dfcfece, org.springframework.test[email protected]23ceabc1, org.springframewor[email protected]5d5eef3d, org.springfra[email protected]56f4468b]
19-09-04 23:39:27 org.springframework.beans.factory.xml.XmlBeanDefinitionReader =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-04 23:39:27 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Refreshing org.s[email protected]31ef45e3: startup date [Wed Sep 04 23:39:27 CST 2019]; root of context hierarchy
19-09-04 23:39:28 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping =====>>> Mapped "{[/test],methods=[GET]}" onto public java.lang.String ocn.site.springmvc.controller.Manicontroller.handlerPage()
19-09-04 23:39:28 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping =====>>> Mapped "{[/register],methods=[POST]}" onto public java.lang.String ocn.site.springmvc.controller.Manicontroller.handlerRegister(ocn.site.springmvc.domain.User,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap)
19-09-04 23:39:28 org.hibernate.validator.internal.util.Version =====>>> HV000001: Hibernate Validator 5.2.0.Final
19-09-04 23:39:28 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.s[email protected]31ef45e3: startup date [Wed Sep 04 23:39:27 CST 2019]; root of context hierarchy
19-09-04 23:39:28 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.s[email protected]31ef45e3: startup date [Wed Sep 04 23:39:27 CST 2019]; root of context hierarchy
19-09-04 23:39:28 org.springframework.mock.web.MockServletContext =====>>> Initializing Spring FrameworkServlet ''
19-09-04 23:39:28 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization started
19-09-04 23:39:28 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization completed in 23 ms
19-09-04 23:39:28 ocn.site.springmvc.controller.Manicontroller =====>>> first config success
19-09-04 23:39:28 ocn.site.springmvc.controller.Manicontroller =====>>> length must be between 4 and 2147483647
19-09-04 23:39:28 ocn.site.springmvc.controller.Runtest =====>>> test finished
19-09-04 23:39:28 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Closing org.s[email protected]31ef45e3: startup date [Wed Sep 04 23:39:27 CST 2019]; root of context hierarchy
下一篇: iPhone OS 3.0演示发布
推荐阅读
-
最锋利的Visual Studio Web开发工具扩展:Web Essentials使用详解
-
Struts2学习教程之Action类如何访问WEB资源
-
基于C#动手实现网络服务器Web Server
-
linux下用renameTo方法修改java web项目中文件夹名称的实例
-
使用Python的Flask框架表单插件Flask-WTF实现Web登录验证
-
Java应用开源框架实现简易web搜索引擎
-
网易微博Web App用HTML5开发的过程介绍
-
HTML5 实战PHP之Web页面表单设计
-
HTML5教程之html 5 本地数据库(Web Sql Database)
-
python实现web方式logview的方法