`
hawkist
  • 浏览: 35872 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

构建基于maven的综合项目(二)--验证表单、实体关系

阅读更多
一、添加表单验证
    1、页面,导入form标签,form上添加modelAttribute属性,信息提示用form:errors标签,对应model属性或boolean方法
……
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
……
<form:form modelAttribute="addUserModel" action="addUser.do" method="post">
……
<td><spring:message code="message.user.userName"/></td>
<td><input id="userName" name="userName" type="text" value="${addUserModel.userName }"/></td>
<td>
    <div><form:errors path="userName"/></div>
</td>
……
<div><form:errors path="rePassWord"/></div>
<div><form:errors path="passWordValid"/></div>
……
</form:form>

    2、和页面对应的model类
package com.cpkf.notpad.controller.account.model;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.*;
import com.cpkf.notpad.commons.constants.RegexConstants;


/**  
 * Filename:    AddUserModel.java
 * Description: 与页面表单对应的模型对象,在控制器里以
 * 				@Valid @ModelAttribute("addUserModel") AddUserModel addUserModel
 * 				参数形式出现,绑定表单输入数据
 * 				在根目录中创建校验提示信息的配置文件 ValidationMessages.properties进行国际化配置
 * 				这种校验方式局限性大,hibernate本身提供的校验器较少,还必须放在根目录
 * Company:     
 * @author:     Jiang.hu
 * @version:    1.0
 * Create at:   May 16, 2011 3:06:45 PM
 * modified:    
 */
public class AddUserModel {
	//@NotEmpty(message="{account.error.userName.required}")
	private String userName;
	private String nickname;
	//@NotEmpty(message="{account.error.email.required}")
	//@Email(message="{account.error.email.invalid}")
	private String email;
	//@Size(min=6,max=12,message="{account.error.passWord.size}")
	private String passWord;
	private String rePassWord;
	private String gender;
	private String userProvince;
	private String userCity;
	private String birthday;
	//@Pattern(regexp=RegexConstants.PHONE_REGEX,message="{account.error.phone.invalid}")
	private String phone;
	private String registTime;
	//@AssertTrue(message="{account.error.passWord.confirm}")
	public boolean isPassWordValid(){
		if(StringUtils.isNotBlank(passWord) && StringUtils.isNotBlank(rePassWord)){
			return passWord.equals(rePassWord);
		}
		return false;
	}
……
}

    3、控制器
@RequestMapping(value="/addUser.do",method={RequestMethod.GET,RequestMethod.POST})
	public String addUser(HttpServletRequest request,HttpServletResponse response,
			@Valid @ModelAttribute("addUserModel") AddUserModel addUserModel,
			BindingResult errors,
			Model model){
                //使用注解方式局限大,故而自定义校验器,使用自定义国际化文件
		UserValidator userValidator = new UserValidator();
		userValidator.addUserValidator(addUserModel, errors);
		model.addAttribute("addUserModel", addUserModel);
		if(errors.hasErrors()){
			logger.info("The parameter is invalid");
			return "addUser";
		}
		return "index";
	}

    4、校验器
package com.cpkf.notpad.controller.account.validator;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import com.cpkf.notpad.commons.constants.RegexConstants;
import com.cpkf.notpad.controller.account.model.AddUserModel;

public class UserValidator {
	public void addUserValidator(Object model,BindingResult errors){
		AddUserModel addUserModel = (AddUserModel) model;
		if(StringUtils.isBlank(addUserModel.getUserName())){
			//参数1-对应的字段名,参数2-国际化文件中对应的key值,参数三-没有找到key时默认的提示信息
			errors.rejectValue("userName","account.error.userName.required","userName is required.");
		}
		if(StringUtils.isBlank(addUserModel.getEmail())){
			errors.rejectValue("email", "account.error.email.required", "email is required.");
		}
		if(StringUtils.isNotBlank(addUserModel.getEmail()) && 
				!addUserModel.getEmail().matches(RegexConstants.EMAIL_REGEX)){
			errors.rejectValue("email", "account.error.email.invalid", "email is invalid.");
		}
		if(addUserModel.getPassWord().trim().length() < 6 || addUserModel.getPassWord().trim().length() > 12){
			errors.rejectValue("passWord", "account.error.passWord.size", "password must be between 6-12.");
		}
		if(addUserModel.getRePassWord().trim().length() < 6 || addUserModel.getRePassWord().trim().length() > 12){
			errors.rejectValue("rePassWord", "account.error.passWord.size", "password must be between 6-12.");
		}
		if(StringUtils.isNotBlank(addUserModel.getRePassWord()) && 
				!addUserModel.getPassWord().equals(addUserModel.getRePassWord())){
			errors.rejectValue("rePassWord", "account.error.passWord.confirm", "enter the password twice inconsistent.");
		}
		if(StringUtils.isNotBlank(addUserModel.getPhone()) && 
				!addUserModel.getPhone().matches(RegexConstants.PHONE_REGEX)){
			errors.rejectValue("phone", "account.error.phone.invalid", "phone is invalid.");
		}
	}
}

二、创建hibernate实体类关系
    1、account
package com.cpkf.notpad.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
/**  
 * Filename:    Account.java
 * Description: account实体类
 * Company:     
 * @author:     
 * @version:    1.0
 * Create at:   May 10, 2011 1:44:50 PM
 * modified:    
 */
@Entity
@Table(name="account")
public class Account {
	/**
	 * @Id:该类中独特标志
	 * @Column:对应表中的列
	 * @GeneratedValue:主键生成策略-自增长
	 */
	@Id
	@Column(name="account_id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long accountId;
	@Column(name="email")
	private String email;
	@Column(name="passWord")
	private String passWord;
	@Column(name="status")
	private Boolean status;
	//多对多单向,并指定中间表的表明和字段名,中间表自动生成联合组建
	//fetch加载方式EAGER-即时加载,LAZY-延迟加载
	@ManyToMany(fetch=FetchType.EAGER)
	@JoinTable(name="account_role",
			joinColumns={@JoinColumn(name="account_id",referencedColumnName="account_id")},
			inverseJoinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")})
	private Set<Role> roles = new HashSet<Role>();
	//cascade-联级操作,eg:删除account同时删除user
	//unique-外键的唯一性
	@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
	@JoinColumn(name="user_id",unique=true)
	private User user;
……
}

    2、role
package com.cpkf.notpad.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
/**  
 * Filename:    Role.java
 * Description: 角色类
 * Company:     
 * @author:     Jiang.hu
 * @version:    1.0
 * Create at:   May 19, 2011 4:13:53 PM
 * modified:    
 */
@Entity
@Table(name="role")
public class Role {
	@Id
	@Column(name="role_id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long roleId;
	@Column(name="roleName")
	private String RoleName;
	@Column(name="description")
	private String description;
	@Column(name="status")
	private Boolean status;
	//多对多双向
	@ManyToMany(fetch=FetchType.EAGER)
	@JoinTable(name="role_resource",
			joinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")},
			inverseJoinColumns={@JoinColumn(name="resource_id",referencedColumnName="resource_id")})
	private Set<Resource> resources = new HashSet<Resource>();
……
}

    3、resource
package com.cpkf.notpad.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.*;

/**  
 * Filename:    Resource.java
 * Description: 资源类
 * Company:     
 * @author:     Jiang.hu
 * @version:    1.0
 * Create at:   May 19, 2011 4:09:41 PM
 * modified:    
 */
@Entity
@Table(name="resource")
public class Resource {
	@Id
	@Column(name="resource_id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long resourceId;
	@Column(name="resourceName")
	private String resourceName;
	@Column(name="url")
	private String url;
	@ManyToMany(mappedBy="resources",fetch=FetchType.EAGER)
	private Set<Role> roles = new HashSet<Role>();
……
}

    4、其余类大同小异,创建好实体类后,启动程序,会自动创建相应表格
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics