5.1前端与后端
SpringBoot去除内嵌tomcat
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
1、前端调用封装好的方法$.table.init,传入后台url。
- var options = {
- url: prefix + "/list",
- columns: [{
- field: 'id',
- title: '主键'
- },
- {
- field: 'name',
- title: '名称'
- }]
- };
- $.table.init(options);
2、自定义查询条件参数(特殊情况提前设置查询条件下使用)
- var options = {
- url: prefix + "/list",
- queryParams: queryParams,
- columns: [{
- field: 'id',
- title: '主键'
- },
- {
- field: 'name',
- title: '名称'
- }]
- };
- $.table.init(options);
14.
- function queryParams(params) {
- var search = $.table.queryParams(params);
- search.userName = $("#userName").val();
- return search;
- }
3、后台实现查询逻辑,调用startPage()方法即可自动完成服务端分页。
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(User user)
{
本文档使用 NumberOne构建
分页实现
startPage(); // 此方法配合前端完成自动分页
List<User> list = userService.selectUserList(user);
return getDataTable(list);
}
4、前端调用封装好的方法$.table.init,传入后台
- var options = {
- exportUrl: prefix + "/export",
- columns: [{
- field: 'id',
- title: '主键'
- },
- {
- field: 'name',
- title: '名称'
- }]
- };
- $.table.init(options);
5、添加导出按钮事件
- <a class="btn btn-warning" onclick="$.table.exportExcel()">
- <i class="fa fa-download"></i> 导出
- </a>
6、在实体变量上添加@Excel注解
- @Excel(name = "用户序号", prompt = "用户编号")
- private Long userId;
- @Excel(name = "用户名称")
- private String userName;
- @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
- private String sex;
- @Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
- private Date loginDate;
7、在Controller添加导出方法
- @PostMapping("/export")
- @ResponseBody
- public AjaxResult export(User user)
- {
- List<User> list = userService.selectUserList(user);
- ExcelUtil<User> util = new ExcelUtil<User>(User.class);
- return util.exportExcel(list, "用户数据");
- }
8、添加导入前端代码,form默认id为importForm,也可指定importExcel(id)
1. <form id="importForm" enctype="multipart/form-data" class="mt20 mb10" style="display: none;
- <div class="col-xs-offset-1">
- <input type="file" id="file" name="file"/>
- <div class="mt10 pt5">
<input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经在,更新这条数据。">
- 是否更新已经存在的用户数据
<a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>
- </div>
- <font color="red" class="pull-left mt10">
- 提示:仅允许导入“xls”或“xlsx”格式文件!
- </font>
- </div>
- </form>
9、在实体变量上添加@Excel注解,默认为导出导入,也可以单独设置仅导入Type.IMPORT
@Excel(name = "用户序号")
private Long id;
@Excel(name = "部门编号", type = Type.IMPORT)
private Long deptId;
@Excel(name = "用户名称")
private String userName;
/** 导出部门多个对象 */
@Excels({
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
})
private SysDept dept;
/** 导出部门单个对象 */
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT)
private SysDept dept;
10、在Controller添加导入方法,updateSupport属性为是否存在则覆盖(可选)
@PostMapping("/importData")
@ResponseBody
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class); List<SysUser> userList = util.importExcel(file.getInputStream()); String operName = ShiroUtils.getSysUser().getLoginName();
String message = userService.importUser(userList, updateSupport, operName); return AjaxResult.success(message);
}
11、参考示例修改代码。
- <input id="filePath" name="filePath" class="form-control" type="file">
- function submitHandler() {
- if ($.validate.form()) {
- uploadFile();
- }
- }
- function uploadFile() {
- var formData = new FormData();
- if ($('#filePath')[0].files[0] == null) {
- $.modal.alertWarning("请先选择文件路径");
- return false;
- }
- formData.append('fileName', $("#fileName").val());
- formData.append('file', $('#filePath')[0].files[0]);
- $.ajax({
- url: prefix + "/add",
- type: 'post',
- cache: false,
- data: formData,
- processData: false,
- contentType: false,
- dataType: "json",
- success: function(result) {
- $.operate.successCallback(result);
- }
- });
- }
12、上传成功后需要预览可以对该属性格式化处理
- {
- field : 'filePath',
- title: '文件预览',
- formatter: function(value, row, index) {
return '<a href="javascript:downloadFile(' + row.fileId + ')"><img style="width:30;height:30px;"
- src="/profile/upload/' + row.filePath + '"/></a>';
- }
- },
如需对文件格式控制,设置application.yml中的multipart属性
- # 文件上传
- servlet:
- multipart:
- # 单个文件大小
- max-file-size: 10MB
- # 设置总上传的文件大小
- max-request-size: 20MB
注意:如果只是单纯的上传一张图片没有其他参数可以使用通用方法/common/upload请求处理方法
com.numberone.web.controller.common.CommonController
13、在Controller添加对应上传方法
1. @GetMapping("/downloadFile/{fileId}")
- public void downloadFile(@PathVariable("fileId") Integer fileId, HttpServletResponse response,
- HttpServletRequest request) throws Exception
- {
- FileInfo sysFile = fileInfoService.selectFileInfoById(fileId);
- String filePath = sysFile.getFilePath();
- String realFileName = sysFile.getFileName() + filePath.substring(filePath.indexOf("."));
- String path = NumberOneConfig.getUploadPath() + sysFile.getFilePath();
- response.setCharacterEncoding("utf-8");
- response.setContentType("multipart/form-data");
- response.setHeader("Content-Disposition",
- "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
- FileUtils.writeBytes(path, response.getOutputStream());
- }
14、统一返回实体定义
- package com.numberone.common.core.domain;
- import java.util.HashMap;
- /**
- * 操作消息提醒
- *
- * @author numberone
- */
- public class AjaxResult extends HashMap<String, Object>
- {
- private static final long serialVersionUID = 1L;
- /**
- * 返回错误消息
- *
- * @param code 错误码
- * @param msg 内容
- * @return 错误消息
- */
- public static AjaxResult error(String msg)
- {
- AjaxResult json = new AjaxResult();
- json.put("msg", msg);
- json.put("code", 500);
- return json;
- }
- /**
- * 返回成功消息
- *
- * @param msg 内容
- * @return 成功消息
- */
- public static AjaxResult success(String msg
- {
- AjaxResult json = new AjaxResult();
- json.put("msg", msg)
- json.put("code", 0);
- return json;
- }
- }
15、定义登录异常定义
- package com.numberone.common.exception;
- /**
- * 登录异常
- *
- * @author numberone
- */
- public class LoginException extends RuntimeException
- {
- private static final long serialVersionUID = 1L;
- protected final String message;
- public LoginException(String message)
- {
- this.message = message;
- }
18.
- @Override
- public String getMessage()
- {
- return message;
- }
- }
16、基于@ControllerAdvice注解的Controller层的全局异常统一处理
- package com.numberone.framework.web.exception;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import com.numberone.common.core.domain.AjaxResult;
- import com.numberone.common.exception.LoginException;
- /**
- * 全局异常处理器
- *
- * @author numberone
- */
- @RestControllerAdvice
- public class GlobalExceptionHandler
- {
- private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class
- /**
- * 登录异常
- */
- @ExceptionHandler(LoginException.class)
- public AjaxResult loginException(LoginException e)
- {
- log.error(e.getMessage(), e);
- return AjaxResult.error(e.getMessage());
- }
- }
17、测试访问请求
- @Controller
- public class SysIndexController
- {
- /**
- * 首页方法
- */
- @GetMapping("/index")
- public String index(ModelMap mmap)
- {
- /**
- * 模拟用户未登录,抛出业务逻辑异常
- */
- SysUser user = ShiroUtils.getSysUser();
- if (StringUtils.isNull(user))
- {
- throw new LoginException("用户未登录,无法访问请求。");
- }
- mmap.put("user", user);
- return "index";
- }
- }
18、日期插件精确到时分秒
(1)界面设置时间格式 data-format
- <li class="select-time">
- <label>创建时间: </label>
<input type="text" class="time-input" id="startTime" placeholder="开始时间" name="params[beginTime]" data-
- format="yyyy-MM"/>
- <span>-</span>
<input type="text" class="time-input" id="endTime" placeholder="结束时间" name="params[endTime]" data-
- format="yyyy-MM"/>
- </li>
(2)通过js函数设置datetimepicker日期控件可以设置 format
$('.input-group.date').datetimepicker({
format: 'yyyy-mm-dd hh:ii:ss',
autoclose: true,
minView: 0,
minuteStep:1
});
laydate 日期控件可以设置 common.js 配置type=datetime
layui.use('laydate', function() {
var laydate = layui.laydate;
var startDate = laydate.render({
elem: '#startTime',
max: $('#endTime').val(),
theme: 'molv',
trigger: 'click',
type : 'datetime',
done: function(value, date) {
- 结束时间大于开始时间
if (value !== '') {
endDate.config.min.year = date.year;
endDate.config.min.month = date.month - 1;
endDate.config.min.date = date.date;
} else {
endDate.config.min.year = '';
endDate.config.min.month = '';
endDate.config.min.date = '';
}
}
});
var endDate = laydate.render({
elem: '#endTime',
min: $('#startTime').val(),
theme: 'molv',
trigger: 'click',
type : 'datetime',
done: function(value, date) {
- 开始时间小于结束时间
if (value !== '') {
startDate.config.max.year = date.year;
startDate.config.max.month = date.month - 1;
startDate.config.max.date = date.date;
} else {
startDate.config.max.year = '';
startDate.config.max.month = '';
startDate.config.max.date = '';
}
}
});
});
(3)代码生成不显示新建表
默认条件需要表注释,特殊情况可在GenMapper.xml去除table_comment条件
<select id="selectTableByName"parameterType="String"resultMap="TableInfoResult">
<include refid="selectGenVo"/>
where table_comment <> '' and table_schema = (select database())
</select>