`

springmvc的rest风格之三实现用户添加(JSR 303 – Bean Validation服务端数据验证)

 
阅读更多

添加bean-validator.jar

修改实体类User.java,添加默认构造器以及数据验证信息

package com.test.model;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class User {
	private String username;
	private String nickname;
	private String password;
	private String email;

	public User() {
		super();
	}

	public User(String username, String nickname, String password, String email) {
		super();
		this.username = username;
		this.nickname = nickname;
		this.password = password;
		this.email = email;
	}

	@NotEmpty(message="邮箱不能为空!")
	@Email(message="邮箱格式不正确!")
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	@NotEmpty(message="密码不能为空!")
	@Size(min = 6, max = 10, message = "密码的长度必须在5到10位!")
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@NotEmpty(message="用户名不能为空!")
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

 

Action控制器UserController.java中添加方法:

/**
 * 添加用户前
 * 
 * @param model
 * @return
 */
@RequestMapping(value = "/addUserPro", method = RequestMethod.GET)
public String addUserPro(Model model) {
	// 如果不添加下面这一句的话,sf:form标签中的modelAttribute="user"会在request中找user实例,没有的话会报错
	model.addAttribute(new User());
	return "user/addUser";
}

/**
 * 添加用户
 * 
 * @param user
 * @return
 */
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
// 这里的参数user要和页面上modelAttribute属性值一致
public String addUser(@Valid User user, BindingResult br) {// 紧跟Valid参数之后写验证结果类
	if (br.hasErrors()) {
		return "user/addUser";
	}
	users.put(user.getUsername(), user);
	return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/userList";
}

 

修改用户列表页面/jsp/user/userList.jsp添加:<a href="addUserPro">添加用户</a>

添加用户新增页面/jsp/user/addUser.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>添加用户</title>
</head>
<body>
	<sf:form method="post" modelAttribute="user" action="addUser">
		用户名*:<sf:input path="username"/><sf:errors path="username" cssStyle="color:red"/><br>
		别名:<sf:input path="nickname"/><br>
		密码*:<sf:password path="password"/><sf:errors path="password" cssStyle="color:red"/><br>
		邮箱*:<sf:input path="email"/><sf:errors path="email" cssStyle="color:red"/><br>
		<input type="submit" value="添加"/>
	</sf:form>
</body>
</html>

 

springmvc配置文件spring-mvc.xml中添加<mvc:annotation-driven/>,如果没有这个标签,程序会直接跳过验证逻辑,因为它提供@Valid支持(很惭愧,研究了半天,只知其一,不知其二,知道这个标签里面注入了两个bean,但不知道在什么情况下用必须这个标签)

<?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-3.0.xsd">
        
    <mvc:annotation-driven/>

	<context:component-scan base-package="com.test.controller" />

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 全局异常处理 -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<!-- 设置显示异常信息的视图逻辑 -->
				<prop key="com.test.exception.UserException">user/loginUser</prop>
			</props>
		</property>
	</bean>
	
</beans>

 

为了解决中文乱码问题,在web.xml中添加

<filter>
	<filter-name>characterEncodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>GBK</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>characterEncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

 

在浏览器中输入:

http://127.0.0.1:9900/springmvc_005_rest_03/user/,进入到用户添加页面,不填写任何信息,直接点击“登录”按钮,页面显示

 

  • 大小: 4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics