SpringMvc服务端验证Controller处理

原文:SpringMvc服务端验证Controller处理

源代码下载地址:http://www.zuidaima.com/share/1550463708400640.htm

1、实体类中加注解如@Email.@NotEmpty

2、jsp界面中在所要验证的文本框后面用EL表达式${email}.${name}

3、email 和 name为实体类属性

package com.zuidaima.stationgroup.site.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


/**
 * <p>
 * SiteController:站点管理控制器
 * </p>
 * 
 *
 * 
 * 
 * 
 * @version V1.0.0
 * 
 * @author www.zuidaima.com
 *
 * @date 2013-7-16 下午3:21:36
 * 
 * @class com.megalith.site.action.SiteController
 * 
 */
@Controller
@RequestMapping("/stationgroup/site")
public class SiteController {

	@Autowired
	private SiteService siteService;

	/**
	 * 跳转到添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add() {
		return new ModelAndView("stationgroup/site/edit");
	}

	/**
	 * 添加与修改站点
	 * 
	 * @param site
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(@Valid @ModelAttribute Site site,BindingResult result,
			HttpServletRequest request, HttpServletResponse response) {
		//BindResult result必须紧跟着前面的@ModelAttribute, 否则会出错
		if (result.hasErrors()) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<FieldError> errors = result.getFieldErrors();
			for (int i = 0; i < errors.size(); i++) {
				map.put(errors.get(i).getField(), errors.get(i).getDefaultMessage());
			}
			return new ModelAndView("stationgroup/site/edit",map);
		}
		siteService.save(site);
		return new ModelAndView("redirect:/stationgroup/site");
	}

	
}

	    			

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。