Spring MVC框架在进行表单提交,自动封装成对象提交,在以对象的形式入参

springMVC中from表单提交对象 项目需求:springMVC中前台通过from表单形式提交对象信息到后后台。 前台jsp代码如下: 用户注册 用户名  &nb 密   码    阅读详情

最近做了一个超市订单管理系统的项目,使用的是Spring MVC 和Spring 框架。
在这里插入图片描述
如上图:进行新用户添加。此处jsp页面代码如下:

<div class="right">
        <div class="location">
            <strong>你现在所在的位置是:</strong>
            <span>用户管理页面 >> 用户添加页面</span>
        </div>
        <div class="providerAdd">
            <form id="userForm" name="userForm" method="post" 
             enctype="multipart/form-data"
            action="${pageContext.request.contextPath }/user/addsave.html">
				<input type="hidden" name="method" value="add">
                <!--div的class 为error是验证错误,ok是验证成功-->
                <div>
                    <label for="userCode">用户编码:</label>
                    <input type="text" name="userCode" id="userCode" value=""> 
					<!-- 放置提示信息 -->
					<font color="red"></font>
                </div>
                <div>
                    <label for="userName">用户名称:</label>
                    <input type="text" name="userName" id="userName" value=""> 
					<font color="red"></font>
                </div>
                <div>
                    <label for="userPassword">用户密码:</label>
                    <input type="password" name="userPassword" id="userPassword" value=""> 
					<font color="red"></font>
                </div>
                <div>
                    <label for="ruserPassword">确认密码:</label>
                    <input type="password" name="ruserPassword" id="ruserPassword" value=""> 
					<font color="red"></font>
                </div>
                <div>
                    <label >用户性别:</label>
					<select name="gender" id="gender">
					    <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="userRole" id="userRole"></select> -->
		    <select name="userRole" id="userRole"> 			<option value="1">系统管理员</option> 			<option value="2">经理</option> 			<option value="3" selected="selected">普通用户</option>
		    </select>
	            <font color="red"></font>
                </div>
                <div>
                  <input type="hidden" id="errorinfo" value="${uploadFileError}">
                 <label for="a_idPicPath">证件照:</label>
                   <input type="file" name="attachs" id="a_idPicPath"  value="">
                     <font color="red"></font>
                </div>
                <div>
                  <input type="hidden" id="errorinfo_wp" value="${uploadwpError}">
                 <label for="a_workPicPath">工作证照片:</label>
                   <input type="file" name="attachs" id="a_workPicPath"  value="">
                     <font color="red"></font>
                </div>
                <div class="providerAddBtn">
                    <input type="button" name="add" id="add" value="保存" >
					<input type="button" id="back" name="back" value="返回" >
                </div>
            </form>
        </div> </div>

下面的是实体类代码:

package cn.smbms.pojo;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class User {
	private Integer id; //id
	@NotEmpty(message="用户编码不能为空")         //服务器进行验证
	private String userCode; //用户编码
	@NotEmpty(message="用户名称不能为空")
	private String userName; //用户名称
	@NotNull(message="用户密码不能为空")
	@Length(min=6,max=16,message="用户密码长度为6-10位")
	private String userPassword; //用户密码
	private Integer gender;  //性别
	@Past(message="必须是一个过去时间")
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date birthday;  //出生日期
	private String phone;   //电话
	private String address; //地址
	private Integer userRole;    //用户角色
	private Integer createdBy;   //创建者
	private Date creationDate; //创建时间
	private Integer modifyBy;     //更新者
	private Date modifyDate;   //更新时间
	
	private Integer age;//年龄
	
	private String userRoleName;    //用户角色名称
	private String idPicPath;   //文件上传路径
	private String workPicPath; //工作证上传路径
	
	public String getWorkPicPath() {
		return workPicPath;
	}

	public void setWorkPicPath(String workPicPath) {
		this.workPicPath = workPicPath;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getIdPicPath() {
		return idPicPath;
	}

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

	public User(){}
	
	public User(Integer id,String userCode,String userName,String userPassword,Integer gender,Date birthday,String phone,
			String address,Integer userRole,Integer createdBy,Date creationDate,Integer modifyBy,Date modifyDate){
		this.id = id;
		this.userCode = userCode;
		this.userName = userName;
		this.userPassword = userPassword;
		this.gender = gender;
		this.birthday = birthday;
		this.phone = phone;
		this.address = address;
		this.userRole = userRole;
		this.createdBy = createdBy;
		this.creationDate = creationDate;
		this.modifyBy = modifyBy;
		this.modifyDate = modifyDate;
	}
	public String getUserRoleName() {
		return userRoleName;
	}
	public void setUserRoleName(String userRoleName) {
		this.userRoleName = userRoleName;
	}
	public Integer getAge() {
		/*long time = System.currentTimeMillis()-birthday.getTime();
		Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
		Date date = new Date();
		Integer age = date.getYear()-birthday.getYear();
		return age;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
}

下面的是控制层的用户增加方法:

@RequestMapping(value="/addsave.html",method=RequestMethod.POST)
	public String addSave( User user,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"); 
		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";
				 }
				
			
				logger.info("uploadFile path ============== > "+path);
				//获取原文件名
				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("jpeg")
					   ||prefix.equalsIgnoreCase("png")
					   ||prefix.equalsIgnoreCase("pneg")   
					){
						//判断格式是否正确  和给图片重命名: 当前系统时间+随机数+"_Personal.jpg"
					String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
					  logger.debug("new fileName======== " + fileName);
					//创界文件用来接收上传的文件流
					File targetFile=new File(path,fileName);
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					
					try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
				
						e.printStackTrace();
						request.setAttribute(errorInfo, "*上传失败");
						flag=false;
					}
					//File.separator自适应分隔符/,linux系统或则其他系统/可能不兼容
					if(i==0){
					idPicPath=path+File.separator+fileName;
					}else if(i==1){
					 workPicPath=path+File.separator+fileName;
					}
						
				}else{
					request.setAttribute(errorInfo, "上传图片格式不正确");	
					flag=false; 
				}
				
			}
		} 

在增加方法中,直接以实体对象的方式入参,Spring MVC框架自动将属性封装成对象,在没用框架的时候,一般是在servlet中通过request.getParameter("")的方法来获取属性,在通过实体类的set方法给实体类赋值,而Spring MVC框架恰好将此步骤省略,注意:input标签中的name属性名称要与实体类中的属性名称一致.
此处代码也介绍了多文件上传的过程,使用数组方式实现多文件上传,在控制层中,在for循环中进行判断,需要注意的是要注意后台的顺序要和上传的顺序一致。此处是两文件上传也可以用两个单文件上传完成,也比较清晰明了。

Java后端如何接收多个对象入参?全方位解析最实用的解决方案! 在Java后端开发中,我们经常会遇到这样的场景:客户端要提交多个对象作为参数传递给后端处理。举个例子,比如用户下单时,可能需要传递用户信息、订单详情、商品信息等多个对象。这些数据应该怎么接收?是拆开成一堆参数?还是封装到一个大对象里?一不小心就会弄得乱七八糟,不仅开发不便,还容易埋下Bug隐患。😣今天就来和大家聊聊解决这个“接收多个对象入参”问题的各种姿势,带上示例代码,帮助大家更好地理解和掌握!希望通过这篇文章,你能找到最适合自己项目的多对象接收方式,让请求处理更加优雅和灵活!🎉。 阅读详情

相关推荐

MVC框架知识详解

MVC框架知识详解

不迁怒,不贰过。小知识,大智慧。 3118

springmvc中的数据提交方式

【注】提交请求参数与action方法的形参的名称不一致,使用注解@RequestParam来解析。【注】需要保证请求参数的名称与实体类中成员变量名称一致。【注】只能用于超链接或地址提交数据,使用注解来解析。

m0_63849044的博客 775

Spring MVC 3.0 单表单 同时提交 不同对象到后台

自定义 RequestBean 注解 及 WebArgumentResolver 完成如下格式表单提交 <form> <input name="user.name"/> <input name="user.group.name"/> <input name="group.name"/> </form> 最简单的 是 新定义 一个 过渡对象 Objects 其包含 user group.....等 然后用如上 格式提交 最终 到后台 进行各取所需

Spring MVC 绑定表单数据

Spring MVC 绑定表单数据

xiaofei0195的专栏 360

DIY电磁炉核心驱动方案:IR2153PBF自振荡半桥芯片实战指南(附电路图)

本文详细介绍了IR2153PBF自振荡半桥驱动芯片在DIY电磁炉核心驱动方案中的实战应用。该芯片集成了振荡器与600V高压驱动能力,仅需少量外围元件即可生成互补带死区的PWM信号,极大简化了半桥逆变电路设计。文章深入解析了其工作原理、关键参数,并提供了完整的电路设计、PCB布局指南及调试步骤,帮助电子爱好者构建稳定高效的感应加热驱动核心。

beer8的博客 579

Java Web 图书管理系统的制作指南

实现对图书信息的增删改查(CRUD)操作。支持用户登录与权限管理。图书借阅与归还功能。系统管理员可以管理用户信息和图书库存。

Xiaoxin的博客 1629

SpringMvc数据提交的几种方式

RequestParam:将请求参数绑定到你控制器的方法参数上,和 @PathVariable差不多的作用,不过,@RequestParam可以用于绑定名字不一样的参数。一:直接可以从前端获取数据,类型可以自己定义,但是名字一定要一样。@PathVariable: URL 绑定的占位符,绑定参数。二:将数据进行封装后提交数据,是对象数据。

m0_63628966的博客 449

星网锐捷语音网关密码重置恢复出厂设置

星网锐捷语音网关---密码重置 第一种星网锐捷SVX网关恢复出厂设置的方法 eth1口 任意口插网线,连接电脑并设置电脑固定ip为: 一, 二 网页输入: 192.168.88.86 admin 默认密码 admin 登陆。 忘记密码 可通过以下方法重置: 三: 通过crt或者 shell工具 ,连接 root@192.168.88.86 连续输入两次 passwd a12345678 reboot重启后。通过账号 密码 a12345678 即可登陆系...

cibazhanji2176的博客 1万+

layui table 传对象参数,springboot框架接收参数方法

<script> layui.use(['element', 'table', 'form', 'laydate'], function () { var element = layui.element; var table = layui.table; var form = layui.for...

wcdunf的博客 4507

s8654

The official Snapdragon Ride SX 4.0 development board provides standardized hardware support for the secondary development and functional verification of the s8654 platform.

qq_39257814的博客 6827

【推荐100个unity插件】基于关节物理控制的自行车、电动车、摩托车模拟解决方案——Simple Bicycle Physics

摘要 "简易自行车物理"是Unity的自行车模拟资源包,支持Animation Rigging,实现基于关节物理的自行车控制。兼容所有平台和渲染管线,包含预制体、材质、脚本等资源。核心脚本Bicycle Controller管理自行车物理属性,支持自定义角色设置和移动端控制。安装后,用户可快速配置骑行场景,调整转向、速度、重心等参数,并支持地面贴合、兔跳等功能。适用于开发各类自行车模拟游戏和应用。 (字数:149)

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 1366

layuiのtable相关接口,Springmvc传值问题即参数接口规范

前段代码: <body> <!--表格--> <table id="app_table" lay-filter="app_table_on"></table> </body> <!--工具栏--> <script type="text/html" id="toolBar"> <div c...

Twenty-Seven的博客 661

【AUTOSAR-E2E】-2.1-配置E2E:基于E2EPW配置一个RX接收的Signal Group(使用E2E Profile 2)

《共13页精讲》:此法也适用于E2E Profile 4/5/6/7/11/22 目录 1 检查CAN Matrix Arxml/DBC是否满足E2E需求 2 在DaVinci Developer中为Port添加E2E保护 3 在DaVinci Configurator settings设置 4 如何使用应用层的E2E保护 5 结尾 <--返回「Autosar_BSW高阶配置」总目录--> <--返回「Autosar_BSW高阶配置」专栏主页--> <--

「汽车电子助手」的博客 4417

Spring MVC 四种核心传参形式详解

路径参数是 URL 路径本身的一部分,通常用于表示某个具体资源。其中的 1,就是一个典型的路径参数。请求参数通常以 key=value 的形式出现,存在于 URL 查询串或表单数据中。GET /users?请求体参数来源于 HTTP 请求体,通常是 JSON 格式,前后端分离项目中非常常见。"age": 18对象参数并不是单独的一种数据来源,而是Spring MVC 将请求参数自动绑定为 Java 对象的结果。类型参数来源典型注解常见场景路径参数URL 路径资源定位请求参数。

2401_88153531的博客 728

手把手教你学PCIE--所有 PF(Physical Function)共同管理和分配 VF

但具体如何分配和使用 VF 取决于硬件设计、驱动程序配置以及实际应用场景。

MHD0815的博客 1462

【重识云原生】第四章云网络4.9.5.1节下一代智能网卡——DPU综述

随着数据中心的高速发展,通信能力和计算能力成为数据中心基础设施的相辅相成的两个重要发展方向。若数据中心仅关注计算能力的提升,通信基础设施的提升跟不上,那么数据中心的整体系统性能依然受限,无法发挥出真正的潜力。DPU的提出背景就是应对这些数据量和复杂性的指数级增长。未来,需要将计算移至接近数据的位置,这是目前业界所公认的以数据为中心的体系结构下的创新。综上,DPU对数据中心来说,是通过更明细的分工来实现效率的提升、实现总体系统的成本最优化。...

junbaozi的专栏 1724

Spring MVC 框架

MVC是Model View Controller的缩写,是软件工程的一种软件架构设计模式,它把软件系统分为模型、视图、控制器三个基本部分。

2302_80521088的博客 1420

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Spring MVC Controller 入参类型

入参的类型简介 从请求URL当中来的参数 url占位符 url的query部分 需要注意的是 从url中组装对象入参 从Session中来的参数 获取所有HttpSession 获取Session中指定的对象 从Cookie中来的参数 用于前后端传递数据的Map需要注意的是 HttpServletRequest和HttpServletResponse 总结一下 参考文档刚接触Spring MVC时,

lqadam的博客 8002

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

JAVA对象 转form表单_springMVC 自动将form 提交对象型数据转为Object对象数据

注意事项:1.我的后台controller层使用的是springboot中集成的springmvc来获取form表单的数据。2.我的前端用的是html加thymeleaf,后面的有个地方注意一下,th:action="@{/role/test}"是thymeleaf的标签,主要是计算项目路径.1.html页面[html]viewplaincopy[html]viewplain...

weixin_39669202的博客 1258

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Swagger入参为List

今天遇到一个奇葩的需求,为了方便,service的一个接口入参是List<Map> repayMoney(List<Map<String,Object>) 那,我为了在controller调用service,入参类型得一致呀, 那么问题来了,controller入参也得是List吧,或者是其他形式的数据,转换为List<Map> 翻遍了...

weixin_30872157的博客 4054

Spring MVC框架中的MVC是什么

本文深入解析了SpringMVC框架中MVC设计模式的应用。首先介绍了MVC模式的基本概念及其在Web开发中的价值,包括模型、视图和控制器的职责划分。重点阐述了SpringMVC的实现机制,围绕DispatcherServlet的核心处理流程,详细说明了HandlerMapping、HandlerAdapter等组件的作用。通过对比MVC与MVVM、MVP等模式,分析了各自的适用场景和优缺点。文章还结合SpringBoot的简化特性,提供了分层架构设计、异常处理等最佳实践,并给出一个完整的用户管理系统实现案

持续输出Java相关知识 1238

Spring MVC各种提交形式以及参数接收(form表单提交以及Json提交)

Spring MVC各种提交形式以及参数接收(form表单提交以及Json提交)

qq_44597856的博客 2292

Spring Boot (Spring MVC)中Controller层入参说明

备注:新版本的Spring MVC也支持该方案。 问题描述 使用Spring Boot进行项目开发,想必大多都属于前后端分离项目。因此,我们讨论在这种场景下,前端如何传参,后端如何接受参数。 请求路径参数(参数在URL上) @PathVariable:获取路径参数。 url/{id}这种形式 这种风格的api接口一般类似于取id为多少的新闻、文字等。 在url中输入:localhost:80...

kun blog 6247

Spring MVC

将应用程序分为 Controller、Model、View 三层,Controller 接收客户端请求,调用 Model 生成业务数据,传递给 View。Spring MVC 就是对这套流程的封装,屏蔽了很多底层代码,开放出接口,让开发者可以更加轻松、便捷地完成基于 MVC 模式的 Web 开发。

qq_29631521的博客 1175
上一篇: Mybatis报错:org.apache.ibatis.exceptions.PersistenceException:
下一篇: linux系统安装Nginx的步骤,解决gitlab自带nginx端口和安装nginx端口冲突
javaChengXuY
博客等级 码龄8年 15粉丝 38原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值