web校验基于JSR303

siye@r480:~/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
│   └── webapp
│       ├── index.jsp
│       └── WEB-INF
│           ├── register.jsp
│           ├── success.jsp
│           └── web.xml
└── test
    ├── java
    │   └── ocn
    │       └── site
    │           └── springmvc
    │               └── controller
    │                   └── Runtest.java
    └── resources
        └── config
            └── application.xml

19 directories, 11 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()) {
			return NAME_REGISTER;
		}
		map.put("message", "register success");
		return NAME_SUCCESS;
	}

}
package ocn.site.springmvc.domain;

import java.io.Serializable;

import javax.validation.constraints.Size;

import org.springframework.stereotype.Component;

@Component
public class User implements Serializable {

	// JSR303 验证规范
	// JSR 303 是java为Bean数据合法性校验所提供的一种标准的规范 目前java内建库中未提供具体的实现框架 不可直接使用
	// 比较推荐使用的第三方的实现框架是hibernate 并且新增了较为通用的其他验证注解
	// maven的依赖地址为 artifact/org.hibernate/hibernate-validator
	// 测试使用的版本是 5.2.0-Final

	// JSR 303 的校验注解
	// Constraint 详细信息
	// @Null 被注释的元素必须为 null
	// @NotNull 被注释的元素必须不为 null
	// @AssertTrue 被注释的元素必须为 true
	// @AssertFalse 被注释的元素必须为 false
	// @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
	// @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
	// @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
	// @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
	// @Size(max, min) 被注释的元素的大小必须在指定的范围内
	// @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
	// @Past 被注释的元素必须是一个过去的日期
	// @Future 被注释的元素必须是一个将来的日期
	// @Pattern(value) 被注释的元素必须符合指定的正则表达式

	// hibernate validator 新增的校验注解
	// Constraint 详细信息
	// @Email 被注释的元素必须是电子邮箱地址
	// @Length 被注释的字符串的大小必须在指定的范围内
	// @NotEmpty 被注释的字符串的必须非空
	// @Range 被注释的元素必须在合适的范围内

	private static final long serialVersionUID = 1L;
	private int id;
	@Size(min = 4, message = "size must >= 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.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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";

	@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>
<?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>
	<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 22:11:01 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 22:11:01 org.springframework.test.context.web.WebTestContextBootstrapper  =====>>> Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5dfcfece, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@23ceabc1, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5d5eef3d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@56f4468b]
19-09-04 22:11:01 org.springframework.beans.factory.xml.XmlBeanDefinitionReader  =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-04 22:11:01 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Refreshing org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 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 22:11:02 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 22:11:02 org.hibernate.validator.internal.util.Version  =====>>> HV000001: Hibernate Validator 5.2.0.Final
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 org.springframework.mock.web.MockServletContext  =====>>> Initializing Spring FrameworkServlet ''
19-09-04 22:11:02 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization started
19-09-04 22:11:02 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization completed in 20 ms
19-09-04 22:11:02 ocn.site.springmvc.controller.Manicontroller  =====>>> first config success
19-09-04 22:11:03 ocn.site.springmvc.controller.Runtest  =====>>> test finished
19-09-04 22:11:03 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Closing org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值