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

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