crm模块的设计与实现

本文档介绍了如何在SpringBoot项目中去除内嵌Tomcat,前端调用后端接口进行数据展示,实现分页查询,以及添加导出和导入Excel功能。同时,详细说明了实体类的注解使用、控制器的方法实现,以及全局异常处理。
摘要由CSDN通过智能技术生成

5.1前端与后端

SpringBoot去除内嵌tomcat

<exclusions>

    <exclusion>

        <artifactId>spring-boot-starter-tomcat</artifactId>

        <groupId>org.springframework.boot</groupId>

    </exclusion>

</exclusions>

1、前端调用封装好的方法$.table.init,传入后台url。

  1. var options = {

  1. url: prefix + "/list",

  1. columns: [{

  1. field: 'id',

  1. title: '主键'

  1. },

  1. {

  1. field: 'name',

  1. title: '名称'

  1. }]

  1. };

  1. $.table.init(options);

2、自定义查询条件参数(特殊情况提前设置查询条件下使用)

  1. var options = {

  1. url: prefix + "/list",

  1. queryParams: queryParams,

  1. columns: [{

  1. field: 'id',

  1. title: '主键'

  1. },

  1. {

  1. field: 'name',

  1. title: '名称'

  1. }]

  1. };

  1. $.table.init(options);

14.

  1. function queryParams(params) {

  1. var search = $.table.queryParams(params);

  1. search.userName = $("#userName").val();

  1. return search;

  1. }

3、后台实现查询逻辑,调用startPage()方法即可自动完成服务端分页。

@PostMapping("/list")

@ResponseBody

public TableDataInfo list(User user)

{

本文档使用 NumberOne构建

分页实现

startPage();  // 此方法配合前端完成自动分页

List<User> list = userService.selectUserList(user);

return getDataTable(list);

}

4、前端调用封装好的方法$.table.init,传入后台

  1. var options = {

  1. exportUrl: prefix + "/export",

  1. columns: [{

  1. field: 'id',

  1. title: '主键'

  1. },

  1. {

  1. field: 'name',

  1. title: '名称'

  1. }]

  1. };

  1. $.table.init(options);

5、添加导出按钮事件

  1. <a class="btn btn-warning" onclick="$.table.exportExcel()">

  1. <i class="fa fa-download"></i> 导出

  1. </a>

6、在实体变量上添加@Excel注解

  1. @Excel(name = "用户序号", prompt = "用户编号")
  2. private Long userId;
  1. @Excel(name = "用户名称")
  2. private String userName;
  3. @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
  4. private String sex;
  1. @Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
  2. private Date loginDate;

7、在Controller添加导出方法

  1. @PostMapping("/export")
  2. @ResponseBody
  3. public AjaxResult export(User user)
  4. {
  5. List<User> list = userService.selectUserList(user);
  6. ExcelUtil<User> util = new ExcelUtil<User>(User.class);
  7. return util.exportExcel(list, "用户数据");
  8. }

8、添加导入前端代码,form默认id为importForm,也可指定importExcel(id)

1.  <form id="importForm" enctype="multipart/form-data" class="mt20 mb10" style="display: none;

  1. <div class="col-xs-offset-1">
  2. <input type="file" id="file" name="file"/>
  3. <div class="mt10 pt5">

<input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经在,更新这条数据。"> 

  1. 是否更新已经存在的用户数据 

<a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>

  1. </div>
  2. <font color="red" class="pull-left mt10">
  3. 提示:仅允许导入“xls”或“xlsx”格式文件!
  4. </font>
  5. </div>
  6. </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、参考示例修改代码。

  1. <input id="filePath" name="filePath" class="form-control" type="file">

  1. function submitHandler() {

  1. if ($.validate.form()) {

  1. uploadFile();

  1. }

  1. }

  1. function uploadFile() {

  1. var formData = new FormData();

  1. if ($('#filePath')[0].files[0] == null) {

  1. $.modal.alertWarning("请先选择文件路径");

  1. return false;

  1. }

  1. formData.append('fileName', $("#fileName").val());

  1. formData.append('file', $('#filePath')[0].files[0]);

  1. $.ajax({

  1. url: prefix + "/add",

  1. type: 'post',

  1. cache: false,

  1. data: formData,

  1. processData: false,

  1. contentType: false,

  1. dataType: "json",

  1. success: function(result) {

  1. $.operate.successCallback(result);

  1. }

  1. });

  1. }

12、上传成功后需要预览可以对该属性格式化处理

  1. {
  2. field : 'filePath',
  3. title: '文件预览',
  4. formatter: function(value, row, index) {

return '<a href="javascript:downloadFile(' + row.fileId + ')"><img style="width:30;height:30px;"

  1. src="/profile/upload/' + row.filePath + '"/></a>';
  2. }
  3. },

如需对文件格式控制,设置application.yml中的multipart属性

  1. # 文件上传
  2. servlet:
  3. multipart:
  4. # 单个文件大小
  5. max-file-size:  10MB
  6. # 设置总上传的文件大小
  7. max-request-size:  20MB

注意:如果只是单纯的上传一张图片没有其他参数可以使用通用方法/common/upload请求处理方法

com.numberone.web.controller.common.CommonController

13、在Controller添加对应上传方法

1.  @GetMapping("/downloadFile/{fileId}")

  1. public void downloadFile(@PathVariable("fileId") Integer fileId, HttpServletResponse response,
  2. HttpServletRequest request) throws Exception
  3. {
  4. FileInfo sysFile = fileInfoService.selectFileInfoById(fileId);
  5. String filePath = sysFile.getFilePath();
  6. String realFileName = sysFile.getFileName() + filePath.substring(filePath.indexOf("."));
  7. String path = NumberOneConfig.getUploadPath() + sysFile.getFilePath();
  8. response.setCharacterEncoding("utf-8");
  9. response.setContentType("multipart/form-data");
  10. response.setHeader("Content-Disposition",
  11. "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
  12. FileUtils.writeBytes(path, response.getOutputStream());
  13. }

14、统一返回实体定义

  1. package com.numberone.common.core.domain;
  2. import java.util.HashMap;
  1. /**
  2. * 操作消息提醒
  3. *
  4. * @author numberone
  5. */
  6. public class AjaxResult extends HashMap<String, Object>
  7. {
  8. private static final long serialVersionUID = 1L;
  1. /**
  2. * 返回错误消息
  3. *
  4. * @param code 错误码
  5. * @param msg 内容
  6. * @return 错误消息
  7. */
  8. public static AjaxResult error(String msg)
  9. {
  10. AjaxResult json = new AjaxResult();
  11. json.put("msg", msg);
  12. json.put("code", 500);
  13. return json;
  14. }
  1. /**
  2. * 返回成功消息
  3. *
  4. * @param msg 内容
  5. * @return 成功消息
  6. */
  7. public static AjaxResult success(String msg
  8. {
  9.       AjaxResult json = new AjaxResult();
  10.       json.put("msg", msg)
  1. json.put("code", 0);
  2. return json;
  3. }
  4. }

15、定义登录异常定义

  1. package com.numberone.common.exception;
  1. /**
  2. * 登录异常
  3. *
  4. * @author numberone
  5. */
  6. public class LoginException extends RuntimeException
  7. {
  8. private static final long serialVersionUID = 1L;
  1. protected final String message;
  1. public LoginException(String message)
  2. {
  3. this.message = message;
  4. }

18.

  1. @Override
  2. public String getMessage()
  3. {
  4. return message;
  5. }
  6. }

16、基于@ControllerAdvice注解的Controller层的全局异常统一处理

  1. package com.numberone.framework.web.exception;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.web.bind.annotation.ExceptionHandler;
  5. import org.springframework.web.bind.annotation.RestControllerAdvice;
  6. import com.numberone.common.core.domain.AjaxResult;
  7. import com.numberone.common.exception.LoginException;
  1. /**
  2. * 全局异常处理器
  3. *
  4. * @author numberone
  5. */
  6. @RestControllerAdvice
  7. public class GlobalExceptionHandler
  8. {
  9. private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class

  1. /**
  2. * 登录异常
  3. */
  4. @ExceptionHandler(LoginException.class)
  5. public AjaxResult loginException(LoginException e)
  6. {
  7. log.error(e.getMessage(), e);
  8. return AjaxResult.error(e.getMessage());
  9. }
  10. }

17、测试访问请求

  1. @Controller
  2. public class SysIndexController
  3. {
  4. /**
  5. * 首页方法
  6. */
  7. @GetMapping("/index")
  8. public String index(ModelMap mmap)
  9. {
  10. /**
  11. * 模拟用户未登录,抛出业务逻辑异常
  12. */
  13. SysUser user = ShiroUtils.getSysUser();
  14. if (StringUtils.isNull(user))
  15. {
  16. throw new LoginException("用户未登录,无法访问请求。");
  17. }
  18. mmap.put("user", user);
  19. return "index";
  20. }
  21. }

18、日期插件精确到时分秒

1界面设置时间格式 data-format

  1. <li class="select-time">

  1. <label>创建时间: </label>

<input type="text" class="time-input" id="startTime" placeholder="开始时间" name="params[beginTime]" data-

  1. format="yyyy-MM"/>

  1. <span>-</span>

<input type="text" class="time-input" id="endTime" placeholder="结束时间" name="params[endTime]" data-

  1. format="yyyy-MM"/>

  1. </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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值