整篇文章都是用的layul的前端框架,很多前端的东西都封装了的
1.在list.html页面添加新增按钮,代码如下:
就是你要加的那个页面加个按钮,按了之后他就会跳出来
<button class="layui-btn" onclick="x_admin_show('添加用户','/userInfo/add')" type="button"><i class="layui-icon"></i>添加</button>
2.add.html
<body>
<div class="x-body">
<form class="layui-form">
<input type="hidden" name="url" class="image">
<div class="layui-form-item">
<label class="layui-form-label ">照片:</label>
<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上传头像</button>
<div class="layui-upload-list" style="margin-left: 100px">
<img class="layui-upload-img" id="demo1" width="200" height="100" >
<p id="demoText"></p>
</div>
</div>
</div>
<div class="layui-form-item">
<label for="userName" class="layui-form-label">
<span class="x-red">*</span>登录名
</label>
<div class="layui-input-inline">
<input type="text" id="userName" name="userName" required="" lay-verify="required"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">
<span class="x-red">*</span>将会成为您唯一的登入名
</div>
</div>
<div class="layui-form-item">
<label for="tel" class="layui-form-label">
<span class="x-red">*</span>手机
</label>
<div class="layui-input-inline">
<input type="text" id="tel" name="tel" required="" lay-verify="phone"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">
<span class="x-red">*</span>将会成为您唯一的登入名
</div>
</div>
<div class="layui-form-item">
<label for="email" class="layui-form-label">
<span class="x-red">*</span>邮箱
</label>
<div class="layui-input-inline">
<input type="text" id="email" name="email" required="" lay-verify="email"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">
<span class="x-red">*</span>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"><span class="x-red">*</span>角色</label>
<div class="layui-input-block">
<!-- 角色复选框隐藏值-->
<input type="hidden" name="roleId" id="roleId">
<ul th:each="x:${roleList}" style="float: left">
<li onclick="getRid()"> <input type="checkbox" name="rName" lay-skin="primary" th:title="${x.rName}" th:value="${x.rId}"></li>
</ul>
</div>
</div>
<div class="layui-form-item">
<label for="userPwd" class="layui-form-label">
<span class="x-red">*</span>密码
</label>
<div class="layui-input-inline">
<input type="password" id="userPwd" name="userPwd" required="" lay-verify="userPwd"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">
6到16个字符
</div>
</div>
<div class="layui-form-item">
<label for="L_repass" class="layui-form-label">
<span class="x-red">*</span>确认密码
</label>
<div class="layui-input-inline">
<input type="password" id="L_repass" name="repass" required="" lay-verify="repass"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label for="L_repass" class="layui-form-label">
</label>
<button class="layui-btn" lay-filter="add" lay-submit="">
保存
</button>
</div>
</form>
</div>
</body>
3.添加js验证和新增按钮js方法,代码如下
<script>
layui.use(['form','layer'], function(){
$ = layui.jquery;
var form = layui.form
,layer = layui.layer;
//自定义验证规则
form.verify({
nikename: function(value){
if(value.length < 5){
return '昵称至少得5个字符啊';
}
}
,pass: [/(.+){6,12}$/, '密码必须6到12位']
,repass: function(value){
if($('#userPwd').val()!=$('#L_repass').val()){
return '两次密码不一致';
}
}});
//新增按钮
form.on('submit(add)', function(data){
console.log(data.field);
$.ajax({
url:"/userInfo/save/add",
async: false,
type:"POST",
dataType: "json",
data:data.field,
success: function(data){
if(data==true){
layer.alert("增加成功", {icon: 6},function () {
// 获得frame索引
var index = parent.layer.getFrameIndex(window.name);
//关闭当前frame
parent.layer.close(index);
//刷新
parent.window.location.replace("/userInfo/list")
});
}else{
layer.msg('增加失败!',{icon: 6,time:1000});
}
}
})
return false;
});
});
<script>
4.在UserInfoController下定义访问新增页面代码
//访问用户新增页面
@RequestMapping("/add")
public String add(Model model){
return "userInfo/add";
}
5.因为用户新增里设计到头像上传,所以先完成头像上传功能,图片上传的html在前面代码已经写好了,在上面的js代码后面 加上图片上传js代码
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
elem: '#test1'
,url: '/userInfo/upload/'
,accept:'url'
,size:50000
,before: function(obj){
obj.preview(function(index, file, result){
//显示上传图片
$('#demo1').attr('src', result);
});
}
,done: function(res){
//如果上传失败
if(res.code > 0){
return layer.msg('上传失败');
}
//上传成功
var demoText = $('#demoText');
demoText.html('<span style="color: #4cae4c;">上传成功</span>');
var fileupload = $(".image");
//把图片在项目中的路径存入到 属性 class=image的input框中
fileupload.attr("value",res.src);
console.log(fileupload.attr("value"));
}
,error: function(){
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function(){
uploadInst.upload();
});
}
});
});
6.图片上传前端完成后,在来配置文件上传的配置,在application.properties中加入 图片上传配置
#=====文件上传#
文件访问路径 file.path=/upload/**
静态资源文件访问路径 file.staticPath=/upload
#文件保存的绝对路径 file.address=f://springbootimage/
#是否支持 multipart 上传文件 spring.servlet.multipart.enabled=true
#最大支持文件大小 spring.servlet.multipart.max-file-size=30MB
#最大支持请求大小 spring.servlet.multipart.max-request-size=30MB
7.在com.hqyj.config包下创建UploadConfig 类,它是springboot用来注册文件上传虚拟路径的 //文件上传注册,注册虚拟路径
//这个是映射绝对路径和关系虚拟路径的
@Configuration
public class UploadConfig implements WebMvcConfigurer {
@Value("${file.path}")
private String path;
@Value("${file.address}")
private String address;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(path).addResourceLocations("file:" + address);
}
}
8.在UserInfoController注入配置属性,代码如下
//注入上传文件的绝对物理目录路径
@Value("${file.address}")
private String fileAddres;
//注入访问上传文件的静态资源路径
@Value("${file.staticPath}")
private String fileStaicPath;
9.在UserInfoController定义图片上传方法,代码如下
//图片上传
@ResponseBody
@RequestMapping("/upload")
public Map upload(MultipartFile file, HttpServletRequest request){
//记录图片后缀
String prefix="";
//记录当天日期
String dateStr="";
try{
if(file!=null){
//获取上传图片的后缀
String originalName = file.getOriginalFilename();
prefix=originalName.substring(originalName.lastIndexOf(".")+1);
//生成随机一个uuid字符串作为上传图片的名称,保持图片名称的唯一性
String uuid = UUID.randomUUID()+"";
//获取当天日期作为上传图片的上一级目录
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateStr = simpleDateFormat.format(date);
//得到上传图片的全路径
String filepath = fileAddres+"\\" + dateStr+"\\"+uuid+"." + prefix;
//打印查看上传路径
System.out.println(filepath);
File files=new File(filepath);
//判读目录是否存在,不存在就创建
if(!files.isDirectory()){
files.mkdirs();
}
//上传图片
file.transferTo(files);
//记录图片在项目中的路径,状态码,并传到前端
Map<String,Object> map2=new HashMap<>();
map2.put("src",fileStaicPath+"/"+ dateStr+"/"+uuid+"." + prefix);
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
return map;
}
}catch (Exception e){
e.printStackTrace();
}
Map<String,Object> map=new HashMap<>();
map.put("code",1);
map.put("msg","");
return map;
}
10.图片上传实现完毕,测试一下
11.图片上传实现完毕后,继续写用户级联新增,考虑新增页面需要加载角色信息,所以 先写加载角色信息代码,在dao层定义RoleInfoDao,代码如下:
@Repository
public interface RoleInfoDao extends JpaRepository<RoleInfo,Integer> {
}
12.在service层定义接口,代码如下
public interface RoleInfoService {
/**
* 查询所有角色
* @return
*/
List<RoleInfo> select();
}
13.在com.hqyj.service.impl定义RoleInfoServiceImpI,代码如下
@Service
public class RoleInfoServiceImpI implements RoleInfoService {
@Autowired
RoleInfoDao roleInfoDao;
@Override
public List<RoleInfo> select() {
return roleInfoDao.findAll();
}
}
14.在UserInfoController注入RoleInfoService,代码如下
//注入角色详细信息服务类
@Autowired
private RoleInfoService roleInfoService;
15.在UserInfoController修改add方法,代码如下
//访问用户新增页面
@RequestMapping("/add")
public String add(Model model){
//查询角色信息加载到用户新增页面
List<RoleInfo> roleInfoList = roleInfoService.select();
model.addAttribute("roleList",roleInfoList);
return "userInfo/add";
}
16.在add.html修改页面 角色方法,代码如下
<div class="layui-form-item">
<label class="layui-form-label"><span class="x-red">*</span>角色</label>
<div class="layui-input-block">
<!-- 角色复选框隐藏值-->
<input type="hidden" name="roleId" id="roleId">
<ul th:each="x:${roleList}" style="float: left">
<li onclick="getRid()"> <input type="checkbox" name="rName" lay-skin="primary" th:title="${x.rName}" th:value="${x.rId}"></li>
</ul>
</div>
</div>
17.复选框选中的getRid()的js代码如下
//获取选中角色是复选框的值
function getRid() {
var rId="";
$('input[type=checkbox]:checked').each(function() {
rId+=$(this).val()+",";
});
console.log(rId)
$("#roleId").val(rId);
}
18.测试下,看下角色是否查询到add页面
19.定义pojo类UserInfoParam 作为新增的 参数实体,set和get方法自行生成
public class UserInfoParam {
private Integer uId;
private String userName;
private String userPwd;
private String tel;
private String email;
//头像路径
private String url;
private Date joinTime;
//是否启用
private Integer status;
private String roleId;
20. Service层添加新增方法的接口
boolean add(UserInfoParam userInfoParam);
21.Service.impl层添加新增实现类代码
@Override
public boolean add(UserInfoParam userInfoParam) {
UserInfo userInfo = null;
UserDetail userDetail = null;
try {
//用户表
userInfo = new UserInfo();
userInfo.setUserName(userInfoParam.getUserName());
userInfo.setUserPwd(userInfoParam.getUserPwd());
//User_Detail表的信息
userDetail = new UserDetail();
userDetail.setTel(userInfoParam.getTel());
userDetail.setEmail(userInfoParam.getEmail());
userDetail.setJoinTime(new Date());
userDetail.setStatus(1);
userDetail.setUrl(userInfoParam.getUrl());
List<RoleInfo> roleInfoList = new ArrayList<>();
//角色 表的信息
if (!userInfoParam.getRoleId().equals("")) {
//取出角色的id
String[] rrr = userInfoParam.getRoleId().split(",");
for (int i = 0; i < rrr.length; i++) {
RoleInfo r = roleInfoDao.findById(Integer.parseInt(rrr[0])).get();
roleInfoList.add(r);
}
}
//添加角色
userInfo.setRoleInfoList(roleInfoList);
userInfo.setUserDetail(userDetail);
userInfoDao.save(userInfo);
return true;
} catch (NumberFormatException e) {
e.printStackTrace();
}
return false;
}
22.在UserInfoController添加save方法,代码如下
//保存
@RequestMapping("/save/{path}")
@ResponseBody
public boolean save(UserInfoParam userInfoParam, @PathVariable("path") String path){
//新增
if(path.equals("add")){
return userInfoService.add(userInfoParam);
}else{//修改
return false;
}
}