初学java,大神路过看看就好,如果有问题请多多指教,谢谢
一、效果演示
1、查看ftp站点的物理路径中的文件
2、点击提交之后新增一条用户信息数据,将图片文件上传到ftp服务器上
二、java代码实现
2.1、首先要自己新建一个maven项目,具体在上一篇博客有讲到
2.2、新建一个ftp服务器的资源文件ftp.properties
资源文件的内容:
#启动双协议,8083用于ftp上传,8083用于查看(这样不需要输入ftp账号密码)
localhost=127.0.0.1
#ftp上传端口
port=2121
ftpUserName=test
ftpPassword=123
ftpPath=ftp
#http协议查看用户图片端口
ftpLookPort=2121
#ftp查看用户图片链接
ftpLookUrl=http://127.0.0.1:8083
#本地图片的保存路径
userFilePath=/userImage/
在spring-mybatis配置文件中加载
然后打开iis服务管理然后
点击添加
将上传文件所需要的工具类封装到util包里面
1、FTP_Upload_Download(文件上传)类
package com.ysm.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author admin
*
*/
@Component
public class FTP_Upload_Download {
// 读取ftp.property文件属性值
/**
* 主机ip
*/
@Value("${localhost}")
private String localhost;
/**
* 上传端口
*/
@Value("${port}")
private int port;
/**
* 用户名
*/
@Value("${ftpUserName}")
private String ftpUserName;
/**
* 密码
*/
@Value("${ftpPassword}")
private String ftpPassword;
/**
* 默认地址
*/
@Value("${ftpPath}")
private String ftpPath;
/**
* ftp查看端口
*/
@Value("${ftpLookPort}")
String lookPort;
/**
* ftp查看链接
*/
@Value ("${ftpLookUrl}")
String ftpLookUrl;
/**
* 用户图片上传的路径
*/
@Value("${userFilePath}")
String userFilePath;
public final String getUserFilePath() {
return userFilePath;
}
public final void setUserFilePath(String userFilePath) {
this.userFilePath = userFilePath;
}
@Value("${folderName}")
String folderName;
@Value("${processFilePath}")
String processFilePath;
/**
* 获取FTPClict对象
*
* @param localhost
* 主机
* @param port
* 端口
* @param ftpUserName
* ftp用户名
* @param ftpPasswork
* ftp密码
* @param ftpPath
* ftp工作路径
* @return
*/
private FTPClient getFTPClient(String localhost, int port, String ftpUserName, String ftpPasswork, String ftpPath) {
FTPClient ftpClient = new FTPClient();
try {
// 连接ftp
ftpClient.connect(localhost, port);
ftpClient.login(ftpUserName, ftpPasswork);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
// 取消连接
ftpClient.disconnect();
return null;
}
// 中文支持
ftpClient.setControlEncoding("UTF-8");
// 二进制
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return ftpClient;
}
/**
* ftp上传
*
* @param fileName
* 保存ftp文件名称
* @param file
* 要上传的文件
*/
public boolean upload(String fileName, InputStream input,String ftpPath) {
FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath);
try {
// 切换到上传目录
if (!ftpClient.changeWorkingDirectory(ftpPath)) {
// 如果目录不存在创建目录
String[] dirs = ftpPath.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir)) {
continue;
}
tempPath += "/" + dir;
if (!ftpClient.changeWorkingDirectory(tempPath)) {
ftpClient.makeDirectory(tempPath);
ftpClient.changeWorkingDirectory(tempPath);
}
}
}
System.out.println(ftpPath);
System.out.println(ftpClient.printWorkingDirectory());
fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");
// 上传文件
boolean b=ftpClient.storeFile(fileName, input);
System.out.println(ftpClient.getReplyCode());
return b;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ftpClient != null) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* <p>删除ftp上的文件</p>
* @author tangw 2010-12-26
* @param srcFname
* @return true || false
*/
public boolean removeFile(String srcFname,String ftpPath){
FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath);
boolean flag = false;
if( ftpClient!=null ){
try {
flag = ftpClient.deleteFile(srcFname);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (ftpClient != null) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return flag;
}
/**
*
* @param fileName
* @param input
*/
public Boolean upload(String fileName, InputStream input ){
return upload(fileName,input,ftpPath);
}
/**
* ftp下载
*
* @param fileName
* 要下载的文件名
* @param localPath
* 保存本地路径
*
*/
public void download(String fileName, String localPath) {
FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(localPath);
ftpClient.retrieveFile(fileName, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ftpClient != null) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getLocalhost() {
return localhost;
}
public void setLocalhost(String localhost) {
this.localhost = localhost;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFtpUserName() {
return ftpUserName;
}
public void setFtpUserName(String ftpUserName) {
this.ftpUserName = ftpUserName;
}
public String getFtpPassword() {
return ftpPassword;
}
public void setFtpPassword(String ftpPassword) {
this.ftpPassword = ftpPassword;
}
public String getFtpPath() {
return ftpPath;
}
public void setFtpPath(String ftpPath) {
this.ftpPath = ftpPath;
}
public String getLookPort() {
return lookPort;
}
public void setLookPort(String lookPort) {
this.lookPort = lookPort;
}
public String getFtpLookUrl() {
return ftpLookUrl;
}
public void setFtpLookUrl(String ftpLookUrl) {
this.ftpLookUrl = ftpLookUrl;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getProcessFilePath() {
return processFilePath;
}
public void setProcessFilePath(String processFilePath) {
this.processFilePath = processFilePath;
}
}
2、LayuiResponseData类(layui表格数据格式封装)
package com.ysm.util;
import java.util.List;
/**
* layui表格数据格式
* @author admin
*
*/
public class LayuiResponseData {
//响应码 数据总数
private int code=0, count;
//消息
private String msg="";
//数据
List<?> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<?> getData() {
return data;
}
public void setData(List<?> data) {
this.data = data;
}
public LayuiResponseData(int count,List<?> data){
this.count=count;
this.data=data;
}
public LayuiResponseData() {
}
}
3、LayuiUploadResponse(返回上传文件的字符串封装)
package com.ysm.util;
public class LayuiUploadResponse {
String intactPath;
String path;
String fileName;
public String getIntactPath() {
return intactPath;
}
public void setIntactPath(String intactPath) {
this.intactPath = intactPath;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
5、Tools(开发常用的工具类用来验证数字之类)
package com.ysm.util;
/**
* 开发常用工具类
* @author admin
*
*/
public class Tools {
/**
*
* @param value
* @return 如果字符串不为空或者长度不为零返回true
*/
public static boolean isNotNull( String value ) {
if( value == null || "".equals( value.trim()) || "null".equalsIgnoreCase(value) ) {
return false;
}
return true;
}
/**
* ISO编码转换成UTF8编码
* @param s
* @return
*/
public static String ISOtoUTF8(String s) {
try {
s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (Exception e) {
}
return s;
}
/**
* 是否为num
* @param str
* @return boolean
*/
public static boolean isNum(String str){
return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
}
}
新建一个Vo来接收查询数据
package com.ysm.vo;
import com.ysm.entity.User;
public class UserVo extends User{
/**
*
*/
private static final long serialVersionUID = 1L;
private String roleTypeName;
private String sexName;
private String loginTimeStr;
private String userImageStr;
public final String getUserImageStr() {
return userImageStr;
}
public final void setUserImageStr(String userImageStr) {
this.userImageStr = userImageStr;
}
public final String getLoginTimeStr() {
return loginTimeStr;
}
public final void setLoginTimeStr(String loginTimeStr) {
this.loginTimeStr = loginTimeStr;
}
public final String getSexName() {
return sexName;
}
public final void setSexName(String sexName) {
this.sexName = sexName;
}
public final String getRoleTypeName() {
return roleTypeName;
}
public final void setRoleTypeName(String roleTypeName) {
this.roleTypeName = roleTypeName;
}
}
在user.xml里面的resultMap标签下添加以下
<!-- 查询表格 -->
<select id="selectUserTable" resultType="com.ysm.vo.UserVo">
SELECT * FROM USER INNER JOIN roletypetb ON user.roleTypeId = roletypetb.roleTypeId
<if test="name !=null">
and USER.name like '%${name}%'
</if>
limit #{begin},#{page}
</select>
<!-- 查询总数 -->
<select id="selectUserCount" resultType="com.ysm.vo.UserVo">
select count(id) as id from user INNER JOIN roletypetb ON user.roleTypeId = roletypetb.roleTypeId
<if test="name !=null">
and USER.name like '%${name}%'
</if>
</select>
<!-- 新增数据 -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="y.id" keyColumn="id">
insert into user(name,password,sex,loginTime,userImage,roleTypeId)
values(#{y.name},#{y.password},#{y.sex},#{y.loginTime},#{y.userImage},#{y.roleTypeId})
</insert>
<!-- 查询修改用户,绑定数据-->
<select id="selectUpdateUserById" resultType="com.ysm.vo.UserVo">
SELECT * FROM USER INNER JOIN roletypetb ON user.roleTypeId = roletypetb.roleTypeId
where id=#{id}
</select>
<!-- 自定义修改sql -->
<update id="updateUserById" parameterType="com.ysm.entity.User">
update user set name=#{name},password=#{password},sex=#{sex},loginTime=#{loginTime},
userImage=#{userImage},roleTypeId=#{roleTypeId}
where id=#{id}
</update>
<select id="selectUserByName" resultType="com.ysm.entity.User">
select * from user
where name=#{name}
</select>
在UserMapper.java中添加配置文件中的方法(注意方法名称与上面查询标签里面的id一一对应)
List<UserVo> selectUserTable(@Param("begin") Integer begin,@Param("page") Integer page,@Param("name") String name);
List<UserVo> selectUserCount(@Param("name") String name);
int insertUser(@Param("y") UserVo y);
UserVo selectUpdateUserById(@Param("id") Integer id);
int updateUserById(UserVo userVo);
User selectUserByName(@Param("name") String name);
在IUserService中添加以下抽象方法
List<UserVo> selectUserTable(Integer begin,Integer page,String name);
List<UserVo> selectUserCount(String name);
boolean insertUser(UserVo y,MultipartFile file);
UserVo selectUpdateUserById(Integer id);
int updateUserById(UserVo y,MultipartFile file);
User selectUserByName(String name);
IUservice中的实现类
package com.ysm.service.impl;
import com.ysm.entity.User;
import com.ysm.mapper.UserMapper;
import com.ysm.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ysm.util.FTP_Upload_Download;
import com.ysm.util.Tools;
import com.ysm.vo.UserVo;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 服务实现类
* </p>
*
* @author admin
* @since 2018-11-01
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Autowired
UserMapper userMapper;
@Autowired
FTP_Upload_Download upload;
/**
* 查询所有用户的数据
*/
public List<UserVo> selectUserTable(Integer begin, Integer page, String name) {
// TODO Auto-generated method stub
List<UserVo> listUser=userMapper.selectUserTable(begin, page, name);
for (Iterator iterator = listUser.iterator(); iterator.hasNext();) {
UserVo userVo = (UserVo) iterator.next();
String imageUrl=upload.getFtpLookUrl()+userVo.getUserImage();
userVo.setUserImageStr(imageUrl);
if (userVo.getSex()==0) {
userVo.setSexName("男");
}
else {
userVo.setSexName("女");
}
}
return listUser;
}
/**
* 查询用户的总行数
*/
public List<UserVo> selectUserCount(String name) {
// TODO Auto-generated method stub
return userMapper.selectUserCount(name);
}
/**
* 新增用户信息
*/
public boolean insertUser(UserVo userVo,MultipartFile file) {
// TODO Auto-generated method stub
boolean returnValue=false;
String path = upload.getUserFilePath();
String fileName =System.currentTimeMillis()+".jpg";
InputStream is = null;
try {
is = file.getInputStream();
//ftp是否上传成功
boolean b=upload.upload(fileName, is,path);
if(!b){
return returnValue;
}
userVo.setUserImage(path+fileName);
if (Tools.isNotNull(userVo.getName())&&Tools.isNotNull(userVo.getPassword())
&&Tools.isNotNull(userVo.getLoginTimeStr())&&userVo.getSex()!=null) {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
try {
userVo.setLoginTime(format.parse(userVo.getLoginTimeStr()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i=userMapper.insertUser(userVo);
if(i==0){
return returnValue;
}
else {
returnValue=true;
return returnValue;
}
}
else {
return returnValue;
}
} catch (IOException e) {
e.printStackTrace();
return returnValue;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 根据ID修改用户绑定操作
*/
public UserVo selectUpdateUserById(Integer id) {
// TODO Auto-generated method stub
UserVo userVo=userMapper.selectUpdateUserById(id);
StringBuilder imageUrl = new StringBuilder();
imageUrl.append(upload.getFtpLookUrl()+userVo.getUserImage());
userVo.setUserImageStr(imageUrl.toString());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
userVo.setLoginTimeStr(sdf.format(userVo.getLoginTime()));
return userVo;
}
/**
* 修改保存操作
*/
public int updateUserById(UserVo userVo, MultipartFile file) {
// TODO Auto-generated method stub
int returnUpdate=0;
InputStream is = null;
String userImageStrYan=userVo.getUserImage();
try {
if (userImageStrYan!=null&&!userImageStrYan.equals("")) {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
try {
userVo.setLoginTime(format.parse(userVo.getLoginTimeStr()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
returnUpdate=userMapper.updateUserById(userVo);
}
else {
String path = upload.getUserFilePath();
String fileName =System.currentTimeMillis()+".jpg";
is = file.getInputStream();
//ftp是否上传成功
boolean b=upload.upload(fileName, is,path);
//如果上传文件成功
if (b) {
//删除以前的照片
Integer updateId=userVo.getId();
UserVo userVo2=userMapper.selectUpdateUserById(updateId);
String ftpPath= upload.getUserFilePath();
String srcFname=userVo2.getUserImage();
//根据图片名称删除服务器上的照片
boolean ff= upload.removeFile(srcFname, ftpPath);
userVo.setUserImage(path+fileName);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
try {
userVo.setLoginTime(format.parse(userVo.getLoginTimeStr()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
returnUpdate=userMapper.updateUserById(userVo);
}
else {
}
}
return returnUpdate;
} catch (IOException e) {
e.printStackTrace();
return returnUpdate;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 登录方法
*/
public User selectUserByName(String name) {
// TODO Auto-generated method stub
return userMapper.selectUserByName(name);
}
}
在src–》web包下UserController
package com.ysm.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.ysm.entity.Roletypetb;
import com.ysm.entity.User;
import com.ysm.service.IRoletypetbService;
import com.ysm.service.IUserService;
import com.ysm.util.FTP_Upload_Download;
import com.ysm.util.LayuiResponseData;
import com.ysm.vo.UserVo;
/**
* <p>
* 前端控制器
* </p>
*
* @author
* @since 2018-11-01
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService iUserService;
@Autowired
IRoletypetbService iRoletypetbService;
@Autowired
FTP_Upload_Download upload;
//查询用户所有信息
@RequestMapping("selectUserTable")
@ResponseBody
public Object selectUserTable(String name,Integer page, Integer limit) {
if(name==null||name.equals("")) {
name=null;
}
if (page==null) {
page=1;
}
if (limit==null) {
limit=10;
}
int begin=(page-1)* limit;
List<UserVo> userVosCount=iUserService.selectUserCount(name);
int count=userVosCount.get(0).getId();
List<UserVo> listUser=iUserService.selectUserTable(begin, count, name);
return new LayuiResponseData(count, listUser);
}
//弹出新增用户窗口
@RequestMapping("insertUser")
@ResponseBody
public ModelAndView insertUser(UserVo userVo) {
ModelAndView userMv=new ModelAndView("insertUser");
List<Roletypetb> listRole=iRoletypetbService.selectList(null);
userMv.addObject("listRole", listRole);
return userMv;
}
//新增保存操作
//@RequestParam(required=false)MultipartFile file 表示图片接受可为空
@RequestMapping("insertUserSubmit")
@ResponseBody
public Object insertUserSubmit(UserVo userVo,@RequestParam(required=false)MultipartFile file)
throws Exception {
boolean returnValue=iUserService.insertUser(userVo, file);
return returnValue;
}
//删除用户
@RequestMapping("deleteUserById")
@ResponseBody
public Object deleteUserById(Integer userId) {
boolean returnValue=false;
User user=iUserService.selectById(userId);
String ftpPath= upload.getUserFilePath();
String srcFname=user.getUserImage();
//根据图片名称删除服务器上的照片
boolean ff= upload.removeFile(srcFname, ftpPath);
if (ff) {
returnValue=iUserService.deleteById(userId);
}
return returnValue;
}
//绑定修改数据
@RequestMapping("selectUpdateUserById")
@ResponseBody
public Object selectUpdateUserById(Integer userId) {
ModelAndView updateUserView=new ModelAndView("updateUser");
UserVo userVo=iUserService.selectUpdateUserById(userId);
List<Roletypetb> listRole=iRoletypetbService.selectList(null);
updateUserView.addObject("listRole", listRole);
updateUserView.addObject("updateUser", userVo);
return updateUserView;
}
//修改数据提交
@RequestMapping("updateUserSubmit")
@ResponseBody
public Object updateUserSubmit(UserVo userVo,@RequestParam(required=false) MultipartFile file)
throws Exception {
int returnUpdate=iUserService.updateUserById(userVo, file);
return returnUpdate;
}
//用户登录
@RequestMapping("login")
@ResponseBody
public Object login(String userName,String password) {
ModelAndView MainMv=new ModelAndView("Main");
boolean returnValue=false;
User user=iUserService.selectUserByName(userName);
if (user!=null) {
String dbpassword=user.getPassword();
if (dbpassword.equals(password)) {
MainMv.addObject("user", user);
return MainMv;
}
else {
return returnValue;
}
}
else {
return returnValue;
}
}
}
三、与页面交互
(1)新建jsp页面文件以及样式(如下图所示)
1、PublicLink.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- 这个是界面用来与controller层交互 -->
<c:set var="path" value="${pageContext.request.contextPath}"></c:set>
<!-- 这个是用来获取样式以及相关的js文件 -->
<c:set var="pathweb" value="${pageContext.request.contextPath}/web"></c:set>
<!-- 这个是用来进行页面跳转 -->
<c:set var="pathjsp" value="${pageContext.request.contextPath}/jsp"></c:set>
<!-- 这个是直接获取项目路径 -->
<c:set var="pathmain" value="${pageContext.request.contextPath}"></c:set>
2、进入主页面 Main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="${pathweb}/content/layui/css/layui.css" media="all">
<title>测试模板</title>
</head>
<body class="layui-layout-body" layadmin-themealias="default">
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-logo">超越宝典汽配汽修管理系统</div>
<!-- 头部区域(可配合layui已有的水平导航) -->
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item"><a href="">控制台</a></li>
<li class="layui-nav-item" id="OrderManager"><a href="">订单管理</a></li>
<li class="layui-nav-item" id="UserManager"><a href="javascript:;">用户管理</a></li>
<li class="layui-nav-item">
<a href="javascript:;">其它系统</a>
<dl class="layui-nav-child">
<dd><a href="">邮件管理</a></dd>
<dd><a href="">消息管理</a></dd>
<dd><a href="">授权管理</a></dd>
</dl>
</li>
</ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item">
<a href="javascript:;">
<img src="http://t.cn/RCzsdCq" class="layui-nav-img">
小雨
</a>
<dl class="layui-nav-child">
<dd><a href="">基本资料</a></dd>
<dd><a href="">安全设置</a></dd>
</dl>
</li>
<li class="layui-nav-item"><a href="#" id="outToLogin">退了</a></li>
</ul>
</div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll">
<!-- 左侧导航区域(可配合layui已有的垂直导航) -->
<ul class="layui-nav layui-nav-tree" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;">所有商品</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">列表一</a></dd>
<dd><a href="javascript:;">列表二</a></dd>
<dd><a href="javascript:;">列表三</a></dd>
<dd><a href="">超链接</a></dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;">解决方案</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;" >商品管理</a></dd>
<dd><a href="javascript:;">列表二</a></dd>
<dd><a href="">超链接</a></dd>
</dl>
</li>
<li class="layui-nav-item"><a href="">云市场</a></li>
<li class="layui-nav-item"><a href="">发布商品</a></li>
</ul>
</div>
</div>
<!-- 外层的滚动条 -->
<div class="layui-body" style="height:610px">
<!-- 内层的滚动条 -->
<iframe id="content" src="${pathjsp}/userMain.jsp" style="height:610px;width:99%" frameborder="0" class="layadmin-iframe"></iframe>
</div>
</div>
<script src="${pathweb}/content/layui/jquery-3.3.1.min.js"></script>
<script src="${pathweb}/content/layui/layui.all.js"></script>
<script>
layui.use('element', function(){
var element = layui.element;
});
$("#UserManager").click(function(){
$("#content").attr("src", "${pathjsp}/userMain.jsp");
});
$("#OrderManager").click(function(){
$("#content").attr("src", "${pathjsp}/userMain.jsp");
});
</script>
</body>
</html>
3、userMain.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 直接加载 PublicLink.jsp文件即可,这样不用一一配置那么多内容-->
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="${pathweb}/content/layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-fluid">
<div class="layui-col-md12">
<form class="layui-form batchinput-form" action="">
<div class="layui-form-item" style="margin: 2% auto 0.5% auto">
<div class="layui-inline">
<label class="layui-form-label">用户名称</label>
<div class="layui-input-inline">
<input type="text" lay-verify="required" id="name" placeholder="请输入" autocomplete="off" class="layui-input">
</div>
</div>
<button type="button" class="layui-btn layui-btn-normal" id="selectbyCondition">条件查询</button>
<button type="button" class="layui-btn" id="InsertUser">新增</button>
<button type="button" class="layui-btn layui-btn-warm" id="InsertData">返回</button>
</div>
</form>
<table class="layui-hide" lay-filter="userData" lay-data="{url:'${path}/user/selectUserTable.do',page:true,limit:10}">
<thead>
<tr>
<th lay-data="{type:'numbers',fixed: true,width:80,}">序号</th>
<th lay-data="{field:'name', sort: true, fixed: true}">用户名称</th>
<th lay-data="{field:'userImageStr', sort: true, fixed: true, templet: '#setUserImage'}">用户图片</th>
<th lay-data="{field:'sexName', sort: true, fixed: true}">性别</th>
<th lay-data="{field:'password', sort: true, fixed: true}">用户密码</th>
<th lay-data="{field:'loginTime', sort: true, fixed: true}">登录时间</th>
<th lay-data="{fixed: 'right', width:200, align:'center',fixed: true, toolbar: '#barDemo'}">数据操作</th>
</tr>
</thead>
</table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="setUserImage">
<div><img src="{{ d.userImageStr}}" style="height:30px;width:50px;"></div>
</script>
</div>
</div>
<script src="${pathweb}/content/layui/jquery-3.3.1.min.js"></script>
<script src="${pathweb}/content/layui/layui.all.js"></script>
<script type="text/javascript">
var userTable=layui.table;
function selectUserTable(name){
var index = layer.load(1); //添加laoding,0-2两种方式
userTable.init('userData',{
height:470,
page:true,
loading:true,
done:function (res) { //返回数据执行回调函数
layer.close(index); //返回数据关闭loading
},
where:{
name:name
}
});
}
selectUserTable(null);
//根据用户名称进行模糊查询
$("#selectbyCondition").click(function() {
var name = $("#name").val();
selectUserTable(name);
});
//设置弹窗样式
function showForestLayer(contentStr, title) {
var layer = layui.layer;
layer.open({
type : 2,
shade: false,
content : contentStr,
title : title,
offset : 'auto',
area : [ '800px', '550px' ],
maxmin: true,
zIndex: layer.zIndex, //重点1
success: function(layero){
layer.setTop(layero); //重点2
}
})
}
//新增弹出
$("#InsertUser").click(function() {
var contentStr, title;
contentStr = ["${path}/user/insertUser.do", "no" ];
title = "新增用户";
showForestLayer(contentStr, title);
});
//点击删除/编辑操作
userTable.on('tool(userData)',function(obj){
var userId=obj.data.id;
if(obj.event=="edit"){
var contentStr,title;
contentStr=["${path}/user/selectUpdateUserById.do?userId="+userId];
title="修改用户";
showForestLayer(contentStr,title);
}
else if(obj.event=="del"){
deleteUser(obj);
}
});
//删除用户数据的方法
function deleteUser(obj){
var layer=layui.layer;
layer.confirm('您确定要删除【'+obj.data.name+'】吗?',{
btn:['确定','取消'],
},function(){
var userId=obj.data.id;
$.ajax({
url:'${path}/user/deleteUserById.do',
data:{userId:userId},
dataType:'json',
type:'post',
success:function(result){
console.log(result.message);
if(result){
obj.del();
layer.msg("删除成功",{icon:1});
}
else{
layer.msg("删除失败",{icon:2});
}
}
});
},function(){
});
}
</script>
</body>
</html>
4、新增数据的jsp页面(insertUser.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>新增用户</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="${pathweb}/content/layui/css/layui.css" media="all">
</head>
<body>
<form class="layui-form" action="" style="margin-top: 20px" id="userForm" name="userForm" enctype="multipart/form-data" method="post">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">用户名称</label>
<div class="layui-input-inline">
<input type="text" lay-verify="required" name="name" id="name" placeholder="请输入用户名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="password" id="password" name="password" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">角色类型</label>
<div class="layui-input-inline">
<select name="roleTypeId" lay-verify="required" lay-search="" id="roleTypeId">
<option value="0">---请选择---</option>
<c:forEach var="listRole" items="${listRole}">
<option value="${listRole.roleTypeId}">${listRole.roleTypeName}</option>
</c:forEach>
</select>
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">出生日期</label>
<div class="layui-input-inline">
<input type="text" name="loginTimeStr" id="loginTimeStr" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">性别</label>
<div class="layui-input-inline">
<input type="radio" name="sex" value="0" title="男" checked>
<input type="radio" name="sex" value="1" title="女" >
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">用户照片</label>
<div class="layui-upload-drag">
<img class="layui-upload-img" src="" alt="" id="userImageShow" style="height:170px;width:290px;border-style: dotted">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline" style="margin-left:210px">
<button type="button" class="layui-btn " id="selectUserImage"><i class="layui-icon"></i>选择用户图片</button>
</div>
<div class="layui-inline" style="margin-left:190px">
<button class="layui-btn" lay-submit="" lay-filter="insertUserBtn" id="insertUserBtn">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<script src="${pathweb}/content/layui/jquery-3.3.1.min.js"></script>
<script src="${pathweb}/content/layui/layui.all.js"></script>
<script type="text/javascript">
layui.use('laydate', function(){
var laydate = layui.laydate;
//执行一个laydate实例 110 216 326 345
laydate.render({
elem: '#loginTimeStr' //指定元素
});
});
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
elem: '#selectUserImage' /*根据绑定id,打开本地图片*/
,auto: false /*true为选中图片直接提交,false为不提交根据bindAction属性上的id提交*/
,bindAction: '#insertUserBtn' /*提交图片*/
,choose:function(obj){
//预读本地文件示例,不支持ie8 36
obj.preview(function(index, file, result){
$('#userImageShow').attr('src', result); //图片链接(base64)
});
}
});
});
/*数据新增方法*/
$("#insertUserBtn").click(function(){
var fd = new FormData();
var formData = new FormData($("#userForm")[0]);
console.log(formData);
$.ajax({
cache : true,
type : "post",
url : "${path}/user/insertUserSubmit.do",
data : formData, // 你的formid
async : false,
contentType: false, //jax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件
processData: false, //当设置为true的时候,jquery ajax 提交的时候不会序列化 data,而是直接使用data
error : function(request) {
parent.layer.alert("网络超时");
},
success : function(data) {
if (data) {
parent.layer.msg("操作成功",{icon:1});
//parent.location.reload();刷新父页面的所有信息
//单纯只是刷新table
$(window.parent.document).find('.layui-laypage-btn').click();
//注意这两句
var index = parent.layer.getFrameIndex(window.name);///先得到当前iframe层的索引
parent.layer.close(index);//再执行关闭,保存、修改页面完成时要获取当前页面并关闭回到上级页面(list页面)起到刷新返回功能
} else {
parent.layer.alert("操作失败!",{icon:2});
}
}
});
});
</script>
</body>
</html>
5、修改用户数据的jsp页面(updateUser.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>修改用户</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="${pathweb}/content/layui/css/layui.css" media="all">
</head>
<body>
<form class="layui-form" action="" style="margin-top: 20px" id="userForm" name="userForm" enctype="multipart/form-data" method="post">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">用户名称</label>
<div class="layui-input-inline">
<input type="text" lay-verify="required" name="name" id="name" value="${updateUser.name }" autocomplete="off" class="layui-input">
<input type="hidden" name="id" value="${updateUser.id}" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="password" id="password" name="password" lay-verify="required" value="${updateUser.password }" autocomplete="off" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">角色类型</label>
<div class="layui-input-inline">
<select name="roleTypeId" lay-verify="required" lay-search="" id="roleTypeId">
<option value="0">---请选择---</option>
<c:forEach var="listRole" items="${listRole}">
<option value="${listRole.roleTypeId}" ${updateUser.roleTypeId eq listRole.roleTypeId ? 'selected="selected"':''}>${listRole.roleTypeName}</option>
</c:forEach>
</select>
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">出生日期</label>
<div class="layui-input-inline">
<input type="text" name="loginTimeStr" value="${updateUser.loginTimeStr }" id="loginTimeStr" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">性别</label>
<div class="layui-input-inline">
<input type="radio" name="sex" <c:if test="${updateUser.sex==0 }">checked</c:if> value="0" title="男" >
<input type="radio" name="sex" <c:if test="${updateUser.sex==1 }">checked</c:if> value="1" title="女" >
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">用户照片</label>
<div class="layui-upload-drag">
<img class="layui-upload-img" src="${updateUser.userImageStr }" alt="" id="userImageShow" style="height:170px;width:290px;border-style: dotted">
<input type="hidden" name="userImage" id="userImage" value="${updateUser.userImage }">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline" style="margin-left:210px">
<button type="button" class="layui-btn " id="selectUserImage"><i class="layui-icon"></i>选择用户图片</button>
</div>
<div class="layui-inline" style="margin-left:190px">
<button class="layui-btn" lay-submit="" lay-filter="updateUserBtn" id="updateUserBtn">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<script src="${pathweb}/content/layui/jquery-3.3.1.min.js"></script>
<script src="${pathweb}/content/layui/layui.all.js"></script>
<script type="text/javascript">
layui.use([ 'form', 'layedit', 'laydate' ], function() {
var form = layui.form, laydate = layui.laydate;
//日期
laydate.render({
elem : '#loginTimeStr'
});
});
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
elem: '#selectUserImage' /*根据绑定id,打开本地图片*/
,auto: false /*true为选中图片直接提交,false为不提交根据bindAction属性上的id提交*/
,bindAction: '#updateUserBtn' /*提交图片*/
,choose:function(obj){
//预读本地文件示例,不支持ie8 36
obj.preview(function(index, file, result){
$("#userImage").val("");//清空图片
$('#userImageShow').attr('src', result); //图片链接(base64)
});
}
});
});
/*数据修改方法 enctype="multipart/form-data"*/
$("#updateUserBtn").click(function(){
var fd = new FormData();
var formData = new FormData($("#userForm")[0]);
console.log(formData);
$.ajax({
cache : true,
type : "post",
url : "${path}/user/updateUserSubmit.do",
data : formData, // 你的formid
async : false,
contentType: false, //jax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件
processData: false, //当设置为true的时候,jquery ajax 提交的时候不会序列化 data,而是直接使用data
error : function(request) {
parent.layer.alert("网络超时");
},
success : function(data) {
if (data) {
parent.layer.msg("操作成功",{icon:1});
//parent.location.reload();刷新父页面的所有信息
//单纯只是刷新table
$(window.parent.document).find('.layui-laypage-btn').click();
//注意这两句
var index = parent.layer.getFrameIndex(window.name);///先得到当前iframe层的索引
parent.layer.close(index);//再执行关闭,保存、修改页面完成时要获取当前页面并关闭回到上级页面(list页面)起到刷新返回功能
} else {
parent.layer.alert("操作失败!",{icon:2});
}
}
});
});
</script>
</body>
</html>
web里面的文件都是一些layui前端框架的文件,可以自己下载
下载网址:https://www.layui.com/(打开之后点击立即下载按钮即可)
另外还需要引用一个js文件(jquery-3.3.1.min.js)
下载网址:http://down.chinaz.com/soft/30789.htm