1.实现用户新增
这一节我们要完成新增用户的前后台代码。
请求参数封装
Controller控制器的方法中,可以接收HttpServletRequest对象,这个对象中包含了前台的请求参数信息。
为了方便开发,一般我们都会对其进行封装,比如HashMap就挺香的,用HashMap获取某个参数,只需要我们用get方法。给HashMap设置某个参数,我们可以用put方法,反正很爽就对了。
我们单独封装一个方法,把HttpServletRequest转换为HashMap
/** * 将请求对象的参数转换为HashMap * @param request * @return */ public static Map<String, Object> handleParamToMap( HttpServletRequest request) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, String[]> entry : request.getParameterMap() .entrySet()) { String[] arr = entry.getValue(); String result = ""; if (null != arr && arr.length > 0) { for (int i = 0; i < arr.length; i++) { result += arr[i]; if (i < arr.length - 1) { result += ","; } } map.put(entry.getKey(), result); } } return map; }
具体的实现细节可以忽略,反正它可以完成我们的要求就对了。
jdbcTemplate的update方法可以接收两个参数,第一个参数是sql语句,insert语句相信我们都不陌生,是sql语法的基础。
jdbcTemplate支持这种写法,比如:
(该图片来自于网络)
按理说后面的values里面需要填写具体的参数值,但是加一个:就变成了一个占位符。比如:ln,就会对应到Map中key=ln的值。
知道这个原理后,我们就可以尝试写出保存用户的方法了。
saveUser
@PutMapping("saveUser") @ResponseBody public Map<String, Object> saveUser(HttpServletRequest request){ //拼装请求参数 Map<String, Object> params = handleParamToMap(request); //设置返回信息 Map<String, Object> resultMap = new HashMap(); resultMap.put("errCode",0); //错误码 resultMap.put("errMsg",null);//错误信息 int update = jdbcTemplate.update("INSERT INTO `vipmgr`.`user` (`user_name`, `create_time`, `header_pic`, `ip_addr`, `is_delete`, `is_logined`, `is_vip`, `last_login_time`, `nick_name`, `password`, `role_id`, `amt`, `last_sign_date`) " + "VALUES (:userName, :createTime, NULL, :ipAddr, '0', '0', '0', :lastLoginTime, :nickName, :password, '1', 0, NULL)",params); if(update != 1){ resultMap.put("errCode",11111); //错误码 resultMap.put("errMsg","系统异常,请联系管理员!");//错误信息 } return params; }
做一个整理,我们需要的参数有:
userName,createTime,ipAddr,lastLoginTime,nickName,password
其中加粗的部分是从前台传过来的,其他字段需要我们自己想办法来组装。
createTime:创建时间
lastLoginTime:上次登录时间 (额,搞错了,这个不用管,创建用户的时候还没有登录时间呢)
先看创建时间,这个用户是当前这个时间点创建的,所以我们直接想办法获取当前时间就行了。
找到我们的老朋友:Hutool,在pom.xml中添加:
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.6.3</version> </dependency>
然后这样写:
params.put("createTime", DateUtil.now());
DateUtil是Hutool里面关于时间处理的工具类。
ipAddr是IP地址的意思,如果是用户注册的时候调用了这个方法,那么是可以获取用户当前网段的IP地址的
params.put("ipAddr", request.getRemoteAddr());
为了让前台能够知道方法的调用结果,我们需要设置返回信息,一般分为错误码和错误信息,如果错误码不是00000(返回成功),那么就需要对错误信息进行展示处理。
//设置返回信息 Map<String, Object> resultMap = new HashMap(); resultMap.put("errCode",0); //错误码 resultMap.put("errMsg",null);//错误信息
最终代码
@PutMapping("saveUser") @ResponseBody public Map<String, Object> saveUser(HttpServletRequest request){ //拼装请求参数 Map<String, Object> params = handleParamToMap(request); //设置返回信息 Map<String, Object> resultMap = new HashMap(); resultMap.put("errCode",0); //错误码 resultMap.put("errMsg",null);//错误信息 params.put("createTime", DateUtil.now()); params.put("ipAddr", request.getRemoteAddr()); int update = jdbcTemplate.update("INSERT INTO `vipmgr`.`user` (`user_name`, `create_time`, `header_pic`, `ip_addr`, `is_delete`, `is_logined`, `is_vip`, `last_login_time`, `nick_name`, `password`, `role_id`, `amt`, `last_sign_date`) " + "VALUES (:userName, :createTime, NULL, :ipAddr, '0', '0', '0', :lastLoginTime, :nickName, :password, '1', 0, NULL)",params); if(update != 1){ resultMap.put("errCode",11111); //错误码 resultMap.put("errMsg","系统异常,请联系管理员!");//错误信息 } return params; }
教程写到这,没有进行测试,上面的代码是我一气呵成的。
如果有问题再说吧。
页面增加一个按钮
<div style="padding:5px;background:#fafafa;width:100%;border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" iconCls="icon-add">增加用户</a> </div>
设计保存窗口
在页面中添加
<div id="win" class="easyui-window" title="保存用户" style="width:400px;height:250px;"> <form style="padding:10px 20px 10px 40px;"> <p>用户名: <input name="userName" type="text"></p> <p>密 码: <input name="password" type="password"></p> <p>昵 称: <input name="nickName" type="text"></p> <div style="padding:5px;text-align:center;"> <a href="#" class="easyui-linkbutton" icon="icon-ok">确认保存</a> <a href="#" class="easyui-linkbutton" icon="icon-cancel">取消</a> </div> </form> </div>
这就创建了一个EasyUI风格的窗口。
新增按钮点击事件
这个窗口默认是关闭着的,所以我们要添加这个属性
<div id="win" class="easyui-window" title="保存用户" style="width:400px;height:250px;" closed="true">
然后,给按钮添加点击事件,点击按钮才显示这个窗体:
<a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="openAddWin()">增加用户</a>
function openAddWin() { $('#win').window('open'); }
保存方法
给提交按钮添加点击事件
<a href="#" class="easyui-linkbutton" icon="icon-ok" onclick="save()">确认保存</a>
save方法
function save() { $.ajax({ url: 'user/saveUser', data: $("#userForm").serialize(), type: 'put', dataType: 'json', success: function (data) { data = eval("(" + data + ")"); if (data.errCode != '00000') { alert(data.errMsg); return; } alert("保存成功!"); $('#win').window('close'); } }); }
测试:
报错了:
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
错误分析:应该是sql语句写错了,参数个数不匹配导致的。
不要慌,调试一下
这是请求参数
这是SQL语句
INSERT INTO `vipmgr`.`user` (`user_name`, `create_time`, `header_pic`, `ip_addr`, `is_delete
可以看到,具名的参数有
:userName, :createTime,:ipAddr,:lastLoginTime, :nickName, :password,
一共6个,可是Map里面只有5个,少了谁呢?
少了lastLoginTime!
好吧,现在我们改一下sql,lastLoginTime设置为null