Spring MVC框架升级之数据校验及文件上传

目录

一、Spring表单标签-引用标签库

1.1 Spring表单标签-引用标签库

1.2 Spring表单标签-常用表单标签

1.3 Spring表单标签-标签属性

1.4 数据校验

二、使用SpringMVC实现文件上

2.1 单文件上传

2.2 多文件上传

一、Spring表单标签-引用标签库

1.1 Spring表单标签-引用标签库

  • Spring提供的一套表单标签库

  • 将模型数据中的表单对象绑定到HTML表单元素中

用法:

<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form"%>

1.2 Spring表单标签-常用表单标签

Spring常用表单标签

名称说明
fm:form/渲染表单元素
fm:input/输入框组件标签
fm:password/密码框组件标签
fm:hidden/隐藏框组件标签
fm:textarea/多行输入框组件标签
fm:radiobutton/单选框组件标签
fm:checkbox/复选框组件标签
fm:select/下拉列表组件标签
fm:error/显示表单数据校验对应的错误信息

1.3 Spring表单标签-标签属性

以上标签都用于绑定表单对象的属性值,基本上这些标签都拥有以下属性。

  • path:属性路径,表示表单对象属性,如account、realName等
  • cssClass:表单组件对应的CSS样式类名
  • cssErrorClass:当提交表单后报错(服务端错误),采用的CSS样式类
  • cssStyle:表单组件对应的CSS样式
  • htmlEscape:绑定的表单属性值是否要对HTML特殊字符进行转换,默认为true
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/calendar/WdatePicker.js"></script>
<title>新增用户</title>
</head>
<body>
<fm:form method="post" modelAttribute="sysUser" >
	用户编码:<fm:input path="account"/><br/>
	用户名称:<fm:input path="realName"/><br/>
	用户密码:<fm:password path="password"/><br/>
	用户生日:<fm:input path="birthday" Class="Wdate" readonly="readonly" onclick="WdatePicker();" class="Wdate"/><br/>
	用户地址:<fm:input path="address"/><br/>
	联系电话:<fm:input path="phone"/><br/>
	用户角色:
	<fm:radiobutton path="roleId" value="1"/>系统管理员
	<fm:radiobutton path="roleId" value="2"/>经理
	<fm:radiobutton path="roleId" value="3" checked="checked"/>普通用户
	<br/>
	<input type="submit" value="保存"/>
</fm:form>

</body>
</html>
@GetMapping("/toAdd")
public String addUser(){
	return "sysUser/add";
}
/**
 * 添加用户
 * @param sysUser
 * @param session
 * @return
 */
@PostMapping("/add")
public String addUserSave(SysUser sysUser ,HttpSession session){
	sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
	if(sysUserService.add(sysUser)){
		return "redirect:/user/list";
	}
	return "sysUser/add";
}

1.4 数据校验

maven中添加依赖

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.1.Final</version>
</dependency>

JSR 303 约束

约束说明
@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)被注释的元素必须符合指定的正则表达式

为SysUser实体类添加属性

public class SysUser {
   	private Integer id; 				//id
   	@NotEmpty(message="用户编码不能为空")
   	private String account; 			//用户编码
	@NotEmpty(message="用户名称不能为空")
	private String realName; 			//用户名称
	@NotNull(message="密码不能为空")
	@Length(min=6,max=10,message="用户密码长度为6-10")
	private String password; 			//用户密码
	private Integer sex;  				//性别
	@Past(message="必须是一个过去的时间")
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date birthday;  			//出生日期
}

二、使用SpringMVC实现文件上

2.1 单文件上传

步骤1:导入依赖jar包

  • commons-io-2.4.jar
  • commons-fileupload-1.2.2.jar
<dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.4</version>
</dependency>

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.2.2</version>
</dependency>

步骤2:配置MultipartResovler

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.
   		CommonsMultipartResolver">
   	<property name="maxUploadSize" value="500000"/>
   	<property name="defaultEncoding" value="UTF-8"/>
</bean>

MultipartFile

  • 可以接受上传的文件数据,并提供了获取上传文件内容、文件名、文件存储等功能,是处理文件上传工作的核心工具
  • 提供了很多处理上传文件的重要方法

步骤3:增加字段

private String idPicPath;
public String getIdPicPath() {
	return idPicPath;
}
public void setIdPicPath(String idPicPath) {
	this.idPicPath = idPicPath;
}

步骤4:改造Controller层

@PostMapping("/add")
public String add(SysUser sysUser,HttpSession session,HttpServletRequest request,
				  @RequestParam(value ="idPic", required = false) MultipartFile idPic){
	String idPicPath = null;
	if(!idPic.isEmpty()){
		String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
		logger.info("上传文件路径"+path);
		String originalFile = idPic.getOriginalFilename();
		logger.info("源文件名为:"+originalFile);
		String prefix= FilenameUtils.getExtension(originalFile);
		logger.debug("原文件后缀为:" + prefix);
		int filesize = 500000;
		logger.debug("文件大小:" + idPic.getSize());
		if(idPic.getSize() >  filesize){
			request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
			return "sysUser/add";
		}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
				|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
			String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal." + prefix;
			logger.debug("新生成的文件名称为:" + idPic.getName());
			File targetFile = new File(path);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			try {
				idPic.transferTo(new File(targetFile, fileName));
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("uploadFileError", " * 上传失败!");
				return "sysUser/add";
			}
			idPicPath = File.separator+"statics"+ File.separator+"uploadfiles" + File.separator+fileName;
		}else{
			request.setAttribute("uploadFileError", " * 上传图片格式不正确");
			return "sysUser/add";
		}
	}
	sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
	sysUser.setIdPicPath(idPicPath);
	if(sysUserService.add(sysUser)){
		return "redirect:/user/list";
	}
	return "sysUser/add";
}

步骤5:改造View层

<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/WEB-INF/jsp/common/head.jsp" %>

<div class="right">
    <div class="location">
        <strong>当前位置:</strong>
        <span>用户管理页面 >> 用户添加页面</span>
    </div>
    <div class="supplierAdd">
        <form id="userForm" name="userForm" enctype="multipart/form-data" method="post"
              action="${pageContext.request.contextPath }/sys/user/add">
            <!--div的class 为error是验证错误,ok是验证成功-->
            <div>
                <label for="account">账号:</label>
                <input type="text" name="account" id="account" value="">
                <!-- 放置提示信息 -->
                <font color="red"></font>
            </div>
            <div>
                <label for="realName">真实姓名:</label>
                <input type="text" name="realName" id="realName" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="password">密码:</label>
                <input type="password" name="password" id="password" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="rpassword">确认密码:</label>
                <input type="password" name="rpassword" id="rpassword" value="">
                <font color="red"></font>
            </div>
            <div>
                <label>性别:</label>
                <select name="sex" id="sex">
                    <option value="1" selected="selected">女</option>
                    <option value="2">男</option>
                </select>
            </div>
            <div>
                <label for="birthday">出生日期:</label>
                <input type="text" Class="Wdate" id="birthday" name="birthday"
                       readonly="readonly" onclick="WdatePicker();">
                <font color="red"></font>
            </div>
            <div>
                <label for="phone">手机号码:</label>
                <input type="text" name="phone" id="phone" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="address">地址:</label>
                <input name="address" id="address" value="">
            </div>
            <div>
                <label>角色:</label>
                <!-- 列出所有的角色分类 -->
                <%-- <select name="roleId" id="roleList"></select> --%>
                <select name="roleId" id="roleId">
                    <option value="1">系统管理员</option>
                    <option value="2">经理</option>
                    <option value="3" selected="selected">普通用户</option>
                </select>
                <font color="red"></font>
            </div>
            <script>
                var idPic = null;
                var errorinfo = null;
                $(function () {
                    idPic = $("#idPic");
                    if (errorinfo.var() == null || errorinfo.var() == "") {
                        idPic.next().html(
                            "* 上传大小不能超过500K * 上传文件类型必须为:jpg、jpeg、png、pneg");
                    } else {
                        idPic.next().html(errorinfo.var());
                    }
                })
            </script>
            <div>
                <input type="hidden" id="errorinfo" value="${uploadFileError}" />
                <label for="idPic">证件照</label>
                <input type="file" name="idPic" id="idPic" />
                <font color="red"></font>
            </div>
            <div>
                <input type="hidden" id="errorinfo_wp" value="${uploadWpError}" />
                <label for="workPic">工作证照片:</label>
                <input type="file" name="workPic" id="workPic" />
                <font color="red"></font>
            </div>
            <div class="supplierAddBtn">
                <input type="button" name="add" id="add" value="保存">
                <input type="button" id="back" name="back" value="返回">
                <a href="${pageContext.request.contextPath}/user/add">添加用户</a>
            </div>
        </form>
        <%--@elvariable id="com.bdqn.pojo.SysUser" type=""--%>
        <fm:form method="post" modelAttribute="com.bdqn.pojo.SysUser">
            <fm:errors path="account" /><br />
            用尸编码:<fm:input path="account" /><br />
            <fm:errors path="realName" /><br />
            用户名称:<fm:input path="realName" /><br />
            <fm:errors path="password" /><br />
            用户密码:<fm:password path="password" /><br />
            <fm:errors path="birthday" /><br>
            用 户 生 日 :<fm:input path="birthday" Class="Wdate" readonly="readonly"
                                   onclick="WdatePicker();" class="Wdate" /><br>
            用户地址:<fm:input path="address" /><br />
            联系电话:<fm:input path="phone" /><br />
            用户角色:
            <fm:radiobutton path="roleId" value="1" />系统管理员
            <fm:radiobutton path="roleId" value="2" />经理
            <fm:radiobutton path="roleId" value="3" checked="checked" />普通用户
            <br>
            <input type="submit" value="保存" />
        </fm:form>
    </div>
</div>
</section>
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/sysUser/add.js" />

2.2 多文件上传

步骤1:增加字段

private String idPicPath;
private String workPicPath;
public String getIdPicPath() {
	return idPicPath;
}
public void setIdPicPath(String idPicPath) {
	this.idPicPath = idPicPath;
}
public String getWorkPicPath() {
	return workPicPath;
}
public void setWorkPicPath(String workPicPath) {
	this.workPicPath = workPicPath;
}

步骤2:SysUserDaoImpl类的add()方法进行升级改造

@Override
public int add(Connection connection, SysUser user) throws Exception {
	PreparedStatement pstm = null;
	int updateRows = 0;
	if(null != connection){
		String sql = "insert into t_sys_user (account,realName,password" +
				", roleId,sex,birthday,phone,address,createdTime" +
				", createdUserId,idPicPath,workPicPath) " +
				"values(?,?,?,?,?,?,?,?,?,?,?,?)";
		Object[] params = {user.getAccount(),user.getRealName()
				,user.getPassword(),user.getRoleId(),user.getSex()
				,user.getBirthday(),user.getPhone(),user.getAddress()
				,user.getCreatedTime(),user.getCreatedUserId()
				,user.getIdPicPath(),user.getWorkPicPath()};
		updateRows = BaseDao.execute(connection, pstm, sql, params);
		BaseDao.closeResource(null, pstm, null);
	}
	return updateRows;
}

步骤3:改造Controller层

	@PostMapping(value="/add")
	public String add(SysUser sysUser,HttpSession session,HttpServletRequest request,
							  @RequestParam(value ="attachs", required = false) MultipartFile[] attachs){
		String idPicPath = null;
		String workPicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		logger.info("uploadFile path ============== > "+path);
		for(int i = 0;i < attachs.length ;i++){
			MultipartFile attach = attachs[i];
			if(!attach.isEmpty()){
				if(i == 0){
					errorInfo = "uploadFileError";
				}else if(i == 1){
					errorInfo = "uploadWpError";
				}
				String oldFileName = attach.getOriginalFilename();
				logger.info("uploadFile oldFileName ============== > "+oldFileName);
				String prefix=FilenameUtils.getExtension(oldFileName);
				logger.debug("uploadFile prefix============> " + prefix);
				int filesize = 500000;
				logger.debug("uploadFile size============> " + attach.getSize());
				if(attach.getSize() >  filesize){
					request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
					flag = false;
				}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
					String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
					logger.debug("new fileName======== " + attach.getName());
					File targetFile = new File(path);
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					try {
						attach.transferTo(new File(targetFile, fileName));
					} catch (Exception e) {
						e.printStackTrace();
						request.setAttribute(errorInfo, " * 上传失败!");
						flag = false;
					}
					if(i == 0){
						idPicPath = File.separator+"statics"+ File.separator
								+"uploadfiles"+File.separator+fileName;
					}else if(i == 1){
						workPicPath = File.separator+"statics"+ File.separator
								+"uploadfiles"+File.separator+fileName;
					}
					logger.debug("idPicPath: " + idPicPath);
					logger.debug("workPicPath: " + workPicPath);

				}else{
					request.setAttribute(errorInfo, " * 上传图片格式不正确");
					flag = false;
				}
			}
		}
		if(flag){
			sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
			sysUser.setIdPicPath(idPicPath);
			sysUser.setWorkPicPath(workPicPath);
			if(sysUserService.add(sysUser)){
				return "redirect:/user/list";
			}
		}
		return "sysUser/add";
	}

步骤4:改造View层

<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/WEB-INF/jsp/common/head.jsp" %>

<div class="right">
    <div class="location">
        <strong>当前位置:</strong>
        <span>用户管理页面 >> 用户添加页面</span>
    </div>
    <div class="supplierAdd">
        <form id="userForm" name="userForm" enctype="multipart/form-data" method="post"
              action="${pageContext.request.contextPath }/sys/user/add">
            <!--div的class 为error是验证错误,ok是验证成功-->
            <div>
                <label for="account">账号:</label>
                <input type="text" name="account" id="account" value="">
                <!-- 放置提示信息 -->
                <font color="red"></font>
            </div>
            <div>
                <label for="realName">真实姓名:</label>
                <input type="text" name="realName" id="realName" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="password">密码:</label>
                <input type="password" name="password" id="password" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="rpassword">确认密码:</label>
                <input type="password" name="rpassword" id="rpassword" value="">
                <font color="red"></font>
            </div>
            <div>
                <label>性别:</label>
                <select name="sex" id="sex">
                    <option value="1" selected="selected">女</option>
                    <option value="2">男</option>
                </select>
            </div>
            <div>
                <label for="birthday">出生日期:</label>
                <input type="text" Class="Wdate" id="birthday" name="birthday"
                       readonly="readonly" onclick="WdatePicker();">
                <font color="red"></font>
            </div>
            <div>
                <label for="phone">手机号码:</label>
                <input type="text" name="phone" id="phone" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="address">地址:</label>
                <input name="address" id="address" value="">
            </div>
            <div>
                <label>角色:</label>
                <!-- 列出所有的角色分类 -->
                <%-- <select name="roleId" id="roleList"></select> --%>
                <select name="roleId" id="roleId">
                    <option value="1">系统管理员</option>
                    <option value="2">经理</option>
                    <option value="3" selected="selected">普通用户</option>
                </select>
                <font color="red"></font>
            </div>
            <script>
                var idPic = null;
                var errorinfo = null;
                $(function () {
                    idPic = $("#idPic");
                    if (errorinfo.var() == null || errorinfo.var() == "") {
                        idPic.next().html(
                            "* 上传大小不能超过500K * 上传文件类型必须为:jpg、jpeg、png、pneg");
                    } else {
                        idPic.next().html(errorinfo.var());
                    }
                })
            </script>
            <div>
                <input type="hidden" id="errorinfo" value="${uploadFileError}" />
                <label for="idPic">证件照</label>
                <input type="file" name="idPic" id="idPic" />
                <font color="red"></font>
            </div>
            <div>
                <input type="hidden" id="errorinfo_wp" value="${uploadWpError}" />
                <label for="workPic">工作证照片:</label>
                <input type="file" name="workPic" id="workPic" />
                <font color="red"></font>
            </div>
            <div class="supplierAddBtn">
                <input type="button" name="add" id="add" value="保存">
                <input type="button" id="back" name="back" value="返回">
                <a href="${pageContext.request.contextPath}/user/add">添加用户</a>
            </div>
        </form>
        <%--@elvariable id="com.bdqn.pojo.SysUser" type=""--%>
        <fm:form method="post" modelAttribute="com.bdqn.pojo.SysUser">
            <fm:errors path="account" /><br />
            用尸编码:<fm:input path="account" /><br />
            <fm:errors path="realName" /><br />
            用户名称:<fm:input path="realName" /><br />
            <fm:errors path="password" /><br />
            用户密码:<fm:password path="password" /><br />
            <fm:errors path="birthday" /><br>
            用 户 生 日 :<fm:input path="birthday" Class="Wdate" readonly="readonly"
                                   onclick="WdatePicker();" class="Wdate" /><br>
            用户地址:<fm:input path="address" /><br />
            联系电话:<fm:input path="phone" /><br />
            用户角色:
            <fm:radiobutton path="roleId" value="1" />系统管理员
            <fm:radiobutton path="roleId" value="2" />经理
            <fm:radiobutton path="roleId" value="3" checked="checked" />普通用户
            <br>
            <input type="submit" value="保存" />
        </fm:form>
    </div>
</div>
</section>
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/sysUser/add.js" />
  • 26
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值