Java育儿园约架专栏

智能销售系统(三)高级查询/CRUD

2019-09-30  本文已影响0人  磨陀货_

1.高级查询

employee.js中高级查询

1.1 引入JQuery的扩展包jsp中 ---- 返回JSON对象

    <%--引入jQuery的扩展包--%>
    <script src="/easyui/plugin/jquery.jdirk.js"></script>

1.2 jsp中查询标签

<a href="#" data-cmd="search" class="easyui-linkbutton" iconCls="icon-search">查询</a>

1.3 js中添加

$(function(){
    //常用的组件先获取到
    var searchForm = $("#searchForm");
    //所有带来data-cmd属性的元素都加上方法
    $("*[data-cmd]").on("click",function(){
        //谁点击,this就是谁
        var methodName = $(this).data("cmd");
        //执行这个方法(动态调用)
        zx[methodName]();
    })
zx = {
        //用于高级查询
        search(){
            //load ---- 调用这个方法就会重行新去数据库拿数据
            //1.序列化获取值  获取的是name。但是这能那套字符串
            var params = $("#searchForm").serializeObject();
            employeeDatagrid.datagrid("load",params);
        }
}

2.Jsp抽取

2.1公共的 新建head.jsp(建在views包下面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--easyui的css样式--%>
<link rel="stylesheet" type="text/css" href="/easyui/themes/default/easyui.css">
<%--easyui的图标支持--%>
<link rel="stylesheet" type="text/css" href="/easyui/themes/icon.css">
<%--jQuery的支持--%>
<script type="text/javascript" src="/easyui/jquery.min.js"></script>
<%--easyui的核心功能--%>
<script type="text/javascript" src="/easyui/jquery.easyui.min.js"></script>
<%--中文支持--%>
<script src="/easyui/locale/easyui-lang-zh_CN.js"></script>
<%--引入jQuery的扩展包--%>
<script src="/easyui/plugin/jquery.jdirk.js"></script>

2.2在jsp中引入head.jsp

<include > ----- 包含

    <%--引入head.jsp 公共包--%>
    <%@ include file="/WEB-INF/views/head.jsp" %>

2.3 js中获取常用主键

    private String headImage;//图片  头像

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "department_id")
    private Department department;//部门

3.搞部门

3.1完善Department

@Entity
@Table(name = "department")
public class Department extends BaseDomain{   
    private String name;//省略get/set ,toString
public class DepartmentQuery extends BaseQuery{
    private String name;
    //创建查询规则
    @Override
    public Specification createSpec() {
        //Specifications记得选wenhao的包
        //gt -- 大于
        final Specification<Department> spect = Specifications.<Department>and()
                .like(StringUtils.isNotBlank(name), "name", "%" + name + "%")
                .build();
        return spect;
    }
public interface DepartmentRepository extends BaseRepository<Department,Long>{
}
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,Long> implements IDepartmentService {
}
public interface IDepartmentService extends IBaseService<Department,Long>{
}
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController{
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("/index")
    public String index(){
        return "department/department";
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Department> list(){
        return departmentService.getAll();
    }

    @RequestMapping("/page")
    @ResponseBody
    public UIPage<Department> page(DepartmentQuery query){
        return new UIPage<>(departmentService.queyPage(query));
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%@ include file="/WEB-INF/views/head.jsp" %>
    <%--引入当前页面对应的js--%>
    <script src="/js/model/department.js"></script>
</head>
<body>
<%--工具栏(增删改查)--%>
<div id="tb" style="padding:5px;height:auto">
    <div style="margin-bottom:5px">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true"></a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true"></a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true"></a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true"></a>
    </div>
    <%--高级查询部分--%>
    <form id="searchForm" action="" method="post">
        名称: <input  type="text" name="name" class="easyui-textbox" style="width:80px">
        <a href="#" class="easyui-linkbutton" data-method="search" iconCls="icon-search">查询</a>
    </form>
</div>

<%--展示当前页数据的代码--%>
<table id="departmentDatagrid" class="easyui-datagrid" fit="true"
       data-options="url:'/department/page',fitColumns:true,singleSelect:true,pagination:true,toolbar:'#tb'">
    <thead>
    <tr>
        <th data-options="field:'id',width:100">编码</th>
        <th data-options="field:'name',width:100">名称</th>
    </tr>
    </thead>
</table>
</body>
</html>

$(function () {

    //获取到常用的组件
    var departmentDatagrid = $("#departmentDatagrid");
    var searchForm = $("#searchForm");

    //为咱们的页面按钮注册事件
    $("*[data-cmd]").on("click",function () {
        //拿到方法名
        var method = $(this).data("cmd");
        zx[method]();//执行方法
    })

    zx ={
        //用于做高级查询的方法
        search(){
            //序列化获取值用的是name -> username=1&email=2
            //原生的serialize方式只能够拿到普通字符串,但是我们这里要的是json数据
            var params = searchForm.serializeObject();
            //把高级查询做出来...
            //1.把用户名和邮件的值传到后台
            //var username = $("#username").val();
            //var email = $("#email").val();
            //2.datagrid根据条件重新展示
            departmentDatagrid.datagrid("load",params);
        }
    }
})

3.2导入图片当头像

3.2.1修改数据库头像路径
数据库修改图片路径
把图片存入imaages-head中

3.2.2jsp页面展示还是字符串 --- 格式不符 所以要改属性(employee.js)

/**
 *                 方法中返回什么,那么在页面就显示什么
 *                  图片的格式化方法
 * @param value         当前这个位置的值
 * @param row           这一行的所有数据
 * @param index         代表第几行(索引)
 */
function imgFormat(value,row,index) {
    return `<img src="${value}" width="80px" height="60px" alt="没有图">`;
}

function objFormat(value) {
    return value ? value.name : "无部门";
}
看一下前台返回的参数

3.2.3效果图

3.3展示部门

3.3.1 在employee中添加上
    private String headImage;//图片  头像

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "department_id")
    private Department department;//部门
//省略get/set/toString
3.3.12 在jsp中加上部门(目前前台显示的是整个对象Object) ---- formatter:objFormat【在你的jsp-xxxxDatagrid中】
<%--这里使用formatter  在js中获取功能,比如无图片和无部门--%>
        <th data-options="field:'headImage',width:80,formatter:imgFormat">头像</th>
        <th data-options="field:'department',width:80,formatter:objFormat">部门</th>
3.3.3 js中也要加上部门的格式化(记得判断一下 不然null的话就报错) --- 用三目
function objFormat(value) {
    return value ? value.name : "无部门";
}

3.4在高级查询中填上部门

3.4.1 首先部门高级查询的话 我们就需要下拉框(API中查询)---在你的searchForm
       部门:<input class="easyui-combobox" name="departmentId"
                 data-options="valueField:'id',textField:'name',url:'/department/list',panelHeight:'auto'" />
3.4.2EmployeeQuery 添加部门的数据(记得条件上也要添加)
    //接收部门的数据
    private Long departmentId;
3.4.3效果演示

4.BUG解决

解决方法:
  1. 方式一 把懒加载改成立刻加载
  2. 方式二 使用Spring给我们提供的过滤器,可以在web环境中解决no-session的问题
4.1这里演示方式二:
1.准备类: CustomMapper --- 在公共包中 commen
//重写了原生的映射关系
public class CustomMapper extends ObjectMapper {
    public CustomMapper() {
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
}
2.修改 applicatonContext‐mvc.xml 中的配置
    <!--mvc的注解支持-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json; charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded; charset=UTF-8</value>
                    </list>
                </property>
                <!-- No serializer:配置 objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 -->
                <property name="objectMapper">
                    <bean class="cn.zx.aisell.common.CustomMapper"></bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
3. web.xml 中
<-- web.xml -->
  <!--Spring wei为咋们准备的过滤器,可以在web环境中解决no-session的问题-->
  <!--把会话关闭放到整个页面都展示完在做-->
  <filter>
    <filter-name>openEntityManager</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>openEntityManager</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

加上这个之后错误就不是no-session了 变成了no-serializer

5.增删改

5.1添加按钮的风格--- 作用就是在按钮上上色

(在head.js中添加)

<%--引入jQuery的扩展包--%>
<script src="/easyui/plugin/jquery.jdirk.js"></script>
<%----%>
<link rel="stylesheet" type="text/css" href="/easyui/demo/demo.css">

(在employee.jsp中添加)

<div>
    <form id="searchForm">
        <a href="#" data-cmd="add" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a>
        <a href="#" data-cmd="edit" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">修改</a>
        <a href="#" data-cmd="delete" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">删除</a>
    </form>
</div>

5.2 删除

5.2.0 给删除按钮添加事件
    //常用的组件先获取到
    var employeeDatagrid = $("#employeeDatagrid");
    var searchForm = $("#searchForm");
    var employeeDialog = $("#employeeDialog");
    var employeeForm =$("#employeeForm");
    //所有带来data-cmd属性的元素都加上方法
    $("*[data-cmd]").on("click",function(){
        //谁点击,this就是谁
        var methodName = $(this).data("cmd");
        //执行这个方法(动态调用)
        zx[methodName]();
    })
5.2.1employee.js
delete(){
            //1.获取选中的行(第一个参数是方法名) row -- 每一行
            var row = employeeDatagrid.datagrid("getSelected");
            //2.如果没有这一行,给出提示
            if(!row){//判断 如果没有行 那么。。
                $.messager.alert('温馨提示','<span style="color: #CC2222;font-size: 20px; ">傻屌</span>请选择后再操作',"info");
                return;
            }
            //3.如果有这一行,给出提示
            $.messager.confirm('确认','您真的要狠心删除我嘛?',function(r){
                if (r){
                    //4.如果确定要删除,发送(Ajax)请求进行删除   --- 使用Ajax删除
                    $.post("/employee/delete",{id:row.id},function(result){
                        //5.删除完成后,成功就删除,失败就给提示
                        if(result.success){
                            //成功了  ---  重新加载页面
                            employeeDatagrid.datagrid("reload");
                        }else{//reload --- 保持当前页
                            //失败了 ---  给出错误信息
                            $.messager.alert("提示",`兄台,以后努力!! 原因:${result.msg}`,"error");
                        }
                    })
                }
            });
        },
EmployeeController
    //删除
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            employeeService.delete(id);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            //失败给出错误信息
            return new JsonResult(e.getMessage());
        }

    }
5.2.3 创建的一个工具类(存成功还是失败/错误提示)
public class JsonResult {
    //成功还是失败
    private boolean success = true;
    //错误提示
    private String msg;

    public JsonResult() {}
    public JsonResult(String msg) {
        this.success = false;
        this.msg = msg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

5.3 增

5.3.1 在js中加
        add(){
            employeeForm.form("clear");
            //打开对话框
            employeeDialog.dialog("center").dialog("open");
        },
            //保存
        save(){
            //根据id确定是添加路径还是修改路径
            //默认是添加的数据
            var url = "/employee/save";
            //拿到id的值
            var id = $("#employeeId").val();
            if(id){
                url = "/employee/update";
            }

            employeeForm.form('submit',{
                url:url,
                //提交表单前的方法
                onSubmit:function () {
                    return $(this).form('validate');
                },

                //操作成功后的回调
                success:function (data) {
                    //返回的是JSON字符串,我们需要把转换成一个JSON对象
                    var result = JSON.parse(data);
                    if (result.success){
                        //成功后刷新
                        employeeDatagrid.datagrid("reload");
                        //关闭窗口
                        employeeDialog.dialog("close");
                    }else {
                        //把失败原因 给一个提示
                        $.messager.alert('提示',`兄台,以后努力!! 原因:${result.msg}`,"error")
                    }
                }
            });
        },
5.3.2 在jsp中加from表单
<%--表单弹出框--%>
<div id="employeeDialog" class="easyui-dialog" title="功能操作"
     data-options="iconCls:'icon-save',closed:true,modal:true,buttons:'#formBtns'"
     style="padding:10px">
    <form id="employeeForm" method="post">
        <input id="employeeId" type="hidden" name="id" />
        <table cellpadding="5">
            <tr>
                <td>用户名:</td>
                <td><input class="easyui-validatebox"  type="text" name="username" data-options="required:true,validType:'checkName'"></input></td>
            </tr>
            <tr data-show="false">
                <td>密码:</td>
                <td><input id="password" class="easyui-validatebox" type="password" name="password" data-options="required:true"></input></td>
            </tr>
            <tr data-show="false">
                <td>确认密码:</td>
                <td><input class="easyui-validatebox" type="password" name="repassword" validType="equals['password','id']" data-options="required:true"></input></td>
            </tr>
            <tr>
                <td>邮箱:</td>
                <td><input class="easyui-validatebox" type="text" name="email" data-options="required:true,validType:'email'"></input></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input class="easyui-validatebox" type="text" name="age" data-options="required:true,validType:'integerRange[18,60]'"></input></td>
            </tr>
            <tr>
                <td>部门:</td>
                <td>
                    <%--400 类型转换错误--%>
                    <input class="easyui-combobox" name="department.id"
                           data-options="valueField:'id',textField:'name',url:'/department/list',panelHeight:'auto'" />
                </td>
            </tr>
        </table>
    </form>
</div>

<%--弹出框(表单)操作--%>
<div id="formBtns">
    <a href="javascript:;" data-cmd="save"  class="easyui-linkbutton c1">确认</a>
    <a href="javascript:;" onclick="$('#employeeDialog').dialog('close')" class="easyui-linkbutton c5">取消</a>
</div>
5.3.3 在后台Controller中添加
    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(Employee employee){
        return saveOrUpdate(employee);
    }

5.4 改

5.4.1 在js中
       edit(){
            //1.获取选中的行
            var row = employeeDatagrid.datagrid("getSelected");

            //2.判断如果这一行不存在,给出提示
            if (!row){
                //style="color:red  红色
                $.messager.alert('警告','<span style="color:red;font-size: 20px;">亲爱的</span>,选中一个'
                ,"warning");
                return;
            }

            //把表单中的数据清空
            employeeForm.form("clear");//.form("clear")  清空表单

            //如果在这一行中有department属性 ,我们就给row department.id属性
            if (row.department){
                row["department.id"] = row.department.id;
            }

            console.debug(row);

            //进行数据回显
            employeeForm.form("load",row);

            //弹出相应的表单
            employeeDialog.dialog("center").dialog("open");
        },
5.4.2 在Controller中加上
    @RequestMapping("/update")
    @ResponseBody
    public JsonResult update(Employee employee){
        return saveOrUpdate(employee);
    }

效果图

目前整体页面 点击新增按钮 点击修改按钮 选中行之后点击修改 没有选中行点击删除 选中行进行删除 高级查询 就不演示了 功能都是完成的

注解讲解

单词讲解

Session --- 会话

Js常用

上一篇 下一篇

猜你喜欢

热点阅读