IT@程序员猿媛读书紫水晶书院•文思飞扬(散文、随笔、杂文、评论、科普、日记……

Maven分布式工程-分页查询(一)

2019-03-16  本文已影响18人  您好简书

第一步:
在foreknow-manager-web 包下 WEB-INF/web.xml
配置web.xml 中央控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>foreknow-manager-web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 解决post乱码 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>foreknow-manager</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>foreknow-manager</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

然后在 WEB-INF 下面 导入静态资源 JS CSS JSP

配置 src/main/resources 下的spring 里的配置文件

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.foreknow.controller" />
    <mvc:annotation-driven />
    <!-- 定义文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
<!-- 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources location="/WEB-INF/css/" mapping="/css/**" />
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**" />
</beans>

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 数据库连接池 -->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.foreknow.mapper"></property>
    </bean>
</beans>

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 扫描包加载Service实现类 -->
    <context:component-scan base-package="com.foreknow.service"></context:component-scan>
</beans>

applicationContext-trans.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.foreknow.service.*.*(..))" />
    </aop:config>
</beans>

其中 Java bean 和java dao 和 javadao 的实现类 都在generatorSqlmapCustom 自动生成工具自动生成

配置 generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/taobao" userId="root"
            password="root">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.foreknow.pojo"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.foreknow.mapper" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.foreknow.dao" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 tableName 有几张表 就写几张表的表名-->
        <table schema="taobao" tableName="tb_user"></table>
        <table schema="taobao" tableName="tb_content"></table>
        <table schema="taobao" tableName="tb_content_category"></table>
        <table schema="taobao" tableName="tb_item"></table>
        <table schema="taobao" tableName="tb_item_cat"></table>
        <table schema="taobao" tableName="tb_item_desc"></table>
        <table schema="btaobao" tableName="tb_item_param"></table>
        <table schema="taobao" tableName="tb_item_param_item"></table>
        <table schema="taobao" tableName="tb_order"></table>
         <table schema="taobao" tableName="tb_order_item"></table>
        <table schema="taobao" tableName="tb_order_shipping"></table>
    </context>
</generatorConfiguration>

src包下log4j.properties

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

生成java GeneratorSqlmap.java


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件
        File configFile = new File("generatorConfig.xml"); 
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                callback, warnings);
        myBatisGenerator.generate(null);

    } 
    public static void main(String[] args) throws Exception {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }

}

然后 在 分布式中

把生成的pojo 也就是java bean 放入foreknow-manager-pojo

image

把生成的dao 接口 和 实现类 放入foreknow-manager-mapper中

image

首先我们会发现在java bean 中没生成一个表对应的就有一个XXXXExample.java
这个是对查询的条件

然后我们要写的 service 层的代码 ItemService.java
根据ID 查询

package com.foreknow.service;

import com.foreknow.common.pojo.EUDataGridResult;
import com.foreknow.pojo.TbItem;

public interface ItemService {
    /**
     * 根据id 查询商品信息
     * @param id
     * @return
     */

   /**
    * 查询数据   返回值 EUDataGridResult.java  封装好的json 
    */
   public TbItem getItemById(long itemId);

 /*  2.请求的参数:?page=1&rows=30*/
   public EUDataGridResult getItemList(int page,int rows);
}

ItemServiceImpl.java

package com.foreknow.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.foreknow.common.pojo.EUDataGridResult;
import com.foreknow.mapper.TbItemMapper;
import com.foreknow.pojo.TbItem;
import com.foreknow.pojo.TbItemExample;
import com.foreknow.pojo.TbItemExample.Criteria;
import com.foreknow.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
    private  TbItemMapper itemMapper;
    /**
     * 根据ID 查商品
     */
    @Override
    public TbItem getItemById(long itemId) {
        // TbItem item = itemMapper.selectByPrimaryKey(itemId);
        // 添加查询条件
        TbItemExample example = new TbItemExample();
        Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(itemId);// and id=?
        List<TbItem> list = itemMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            TbItem item = list.get(0);
            return item;
        }
        return null;
    }
    @Override
    public EUDataGridResult getItemList(int page, int rows) {
        TbItemExample example=new TbItemExample();
        //页面处理   用PageHelper
        PageHelper.startPage(page, rows);
        List<TbItem> list=itemMapper.selectByExample(example);
        //把list  传到EUDataGridResult.java的集合中
        EUDataGridResult result=new EUDataGridResult();
        result.setRows(list);
        //获取总数
        PageInfo<TbItem> pageInfo=new PageInfo<>(list);
        result.setTotal(pageInfo.getTotal());

        return result;
    }

}

然后写controller foreknow-manager-web下的 创建com.foreknow.controller

package com.foreknow.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreknow.common.pojo.EUDataGridResult;
import com.foreknow.pojo.TbItem;
import com.foreknow.service.ItemService;

@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;

    //@PathVariable表示从url中获取到参数
    //如果这个参数和url里面{itemId}名字是一样的话就不需要写value
    //如果不一致的话就需要添加value:@PathVariable("id")
    //向前台返回Json     @ResponseBody
    @RequestMapping("/item/{itemId}")
    @ResponseBody
    public TbItem getItemById(@PathVariable Long itemId) {
        TbItem tbItem =itemService.getItemById(itemId);

        return tbItem;
    }

    @RequestMapping("/item/list")
    @ResponseBody
    public EUDataGridResult getItemList(Integer page,Integer rows) {
        EUDataGridResult result = itemService.getItemList(page, rows);
        return result;
    }
}

写出一个跳转到主页的controller PageController.java

package com.foreknow.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
   @RequestMapping("/index")
   public  String showIndex(){
    return "index";

   }
   @RequestMapping("/{page}")
   public String showPage(@PathVariable String page){
    return page;

   }
}

写分页查询功能

写jsp 在foreknow-manager-web 里
用的框架是query easyui
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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">
<title>EShop商城后台管理系统</title>
<link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.4.1/themes/default/easyui.css" />
<link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.4.1/themes/icon.css" />
<link rel="stylesheet" type="text/css" href="css/taotao.css" />
<script type="text/javascript" src="js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-easyui-1.4.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="js/jquery-easyui-1.4.1/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<style type="text/css">
    .content {
        padding: 10px 10px 10px 10px;
    }
</style>
</head>
<body class="easyui-layout">
    <div data-options="region:'west',title:'菜单',split:true" style="width:180px;">
        <ul id="menu" class="easyui-tree" style="margin-top: 10px;margin-left: 5px;">
            <li>
                <span>商品管理</span>
                <ul>
<!--                attributes: 页面跳转       url':'item-add'   json格式的 -->
                    <li data-options="attributes:{'url':'item-add'}">新增商品</li>
<!--                    
                    1.请求的url:http://localhost:8088/item/list?page=1&rows=30
                    2.请求的参数:?page=1&rows=30
                    3.后台想前台相应的数据的格式Json
                    {total:"8",rows:[{"id":"1","name":"tom",{"id":"2","name":"haha"}]} 
                    -->
                    <li data-options="attributes:{'url':'item-list'}">查询商品</li>
                    <li data-options="attributes:{'url':'item-param-list'}">规格参数</li>
                </ul>
            </li>
            <li>
                <span>网站内容管理</span>
                <ul>
                    <li data-options="attributes:{'url':'content-category'}">内容分类管理</li>
                    <li data-options="attributes:{'url':'content'}">内容管理</li>
                </ul>
            </li>
         </ul>
    </div>
    <div data-options="region:'center',title:''">
        <div id="tabs" class="easyui-tabs">
            <div title="首页" style="padding:20px;">

            </div>
        </div>
    </div>

<script type="text/javascript">
$(function(){
    $('#menu').tree({
        onClick: function(node){
            if($('#menu').tree("isLeaf",node.target)){
                var tabs = $("#tabs");
                var tab = tabs.tabs("getTab",node.text);
                if(tab){
                    tabs.tabs("select",node.text);
                }else{
                    tabs.tabs('add',{
                        title:node.text,
                        href: node.attributes.url,
                        closable:true,
                        bodyCls:"content"
                    });
                }
            }
        }
    });
});
</script>
</body>
</html>

跳转新增商品Jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<table class="easyui-datagrid" id="itemList" title="商品列表" 
       data-options="singleSelect:false,collapsible:true,pagination:true,url:'/item/list',method:'get',pageSize:30,toolbar:toolbar">
<!--   data-options数据处理  pagination:true  分页开启      url:'/item/list' 通过url  向后台访问  pageSize:30 每页30条   toolbar:toolbar   分页的工具栏
  变种的ajax  -->
    <thead>
        <tr>
            <th data-options="field:'ck',checkbox:true"></th>
            <th data-options="field:'id',width:60">商品ID</th>
            <th data-options="field:'title',width:200">商品标题</th>
            <th data-options="field:'cid',width:100">叶子类目</th>
            <th data-options="field:'sellPoint',width:100">卖点</th>
            <th data-options="field:'price',width:70,align:'right',formatter:TAOTAO.formatPrice">价格</th>
            <th data-options="field:'num',width:70,align:'right'">库存数量</th>
            <th data-options="field:'barcode',width:100">条形码</th>
            <th data-options="field:'status',width:60,align:'center',formatter:TAOTAO.formatItemStatus">状态</th>
            <th data-options="field:'created',width:130,align:'center',formatter:TAOTAO.formatDateTime">创建日期</th>
            <th data-options="field:'updated',width:130,align:'center',formatter:TAOTAO.formatDateTime">更新日期</th>
        </tr>
    </thead>
</table>
<div id="itemEditWindow" class="easyui-window" title="编辑商品" data-options="modal:true,closed:true,iconCls:'icon-save',href:'/rest/page/item-edit'" style="width:80%;height:80%;padding:10px;">
</div>
<script>

    function getSelectionsIds(){
        var itemList = $("#itemList");
        var sels = itemList.datagrid("getSelections");
        var ids = [];
        for(var i in sels){
            ids.push(sels[i].id);
        }
        ids = ids.join(",");
        return ids;
    }

    var toolbar = [{
        text:'新增',
        iconCls:'icon-add',
        handler:function(){
            $(".tree-title:contains('新增商品')").parent().click();
        }
    },{
        text:'编辑',
        iconCls:'icon-edit',
        handler:function(){
            var ids = getSelectionsIds();
            if(ids.length == 0){
                $.messager.alert('提示','必须选择一个商品才能编辑!');
                return ;
            }
            if(ids.indexOf(',') > 0){
                $.messager.alert('提示','只能选择一个商品!');
                return ;
            }

            $("#itemEditWindow").window({
                onLoad :function(){
                    //回显数据
                    var data = $("#itemList").datagrid("getSelections")[0];
                    data.priceView = TAOTAO.formatPrice(data.price);
                    $("#itemeEditForm").form("load",data);

                    // 加载商品描述
                    $.getJSON('/rest/item/query/item/desc/'+data.id,function(_data){
                        if(_data.status == 200){
                            //UM.getEditor('itemeEditDescEditor').setContent(_data.data.itemDesc, false);
                            itemEditEditor.html(_data.data.itemDesc);
                        }
                    });

                    //加载商品规格
                    $.getJSON('/rest/item/param/item/query/'+data.id,function(_data){
                        if(_data && _data.status == 200 && _data.data && _data.data.paramData){
                            $("#itemeEditForm .params").show();
                            $("#itemeEditForm [name=itemParams]").val(_data.data.paramData);
                            $("#itemeEditForm [name=itemParamId]").val(_data.data.id);

                            //回显商品规格
                             var paramData = JSON.parse(_data.data.paramData);

                             var html = "<ul>";
                             for(var i in paramData){
                                 var pd = paramData[i];
                                 html+="<li><table>";
                                 html+="<tr><td colspan=\"2\" class=\"group\">"+pd.group+"</td></tr>";

                                 for(var j in pd.params){
                                     var ps = pd.params[j];
                                     html+="<tr><td class=\"param\"><span>"+ps.k+"</span>: </td><td><input autocomplete=\"off\" type=\"text\" value='"+ps.v+"'/></td></tr>";
                                 }

                                 html+="</li></table>";
                             }
                             html+= "</ul>";
                             $("#itemeEditForm .params td").eq(1).html(html);
                        }
                    });

                    TAOTAO.init({
                        "pics" : data.image,
                        "cid" : data.cid,
                        fun:function(node){
                            TAOTAO.changeItemParam(node, "itemeEditForm");
                        }
                    });
                }
            }).window("open");
        }
    },{
        text:'删除',
        iconCls:'icon-cancel',
        handler:function(){
            var ids = getSelectionsIds();
            if(ids.length == 0){
                $.messager.alert('提示','未选中商品!');
                return ;
            }
            $.messager.confirm('确认','确定删除ID为 '+ids+' 的商品吗?',function(r){
                if (r){
                    var params = {"ids":ids};
                    $.post("/rest/item/delete",params, function(data){
                        if(data.status == 200){
                            $.messager.alert('提示','删除商品成功!',undefined,function(){
                                $("#itemList").datagrid("reload");
                            });
                        }
                    });
                }
            });
        }
    },'-',{
        text:'下架',
        iconCls:'icon-remove',
        handler:function(){
            var ids = getSelectionsIds();
            if(ids.length == 0){
                $.messager.alert('提示','未选中商品!');
                return ;
            }
            $.messager.confirm('确认','确定下架ID为 '+ids+' 的商品吗?',function(r){
                if (r){
                    var params = {"ids":ids};
                    $.post("/rest/item/instock",params, function(data){
                        if(data.status == 200){
                            $.messager.alert('提示','下架商品成功!',undefined,function(){
                                $("#itemList").datagrid("reload");
                            });
                        }
                    });
                }
            });
        }
    },{
        text:'上架',
        iconCls:'icon-remove',
        handler:function(){
            var ids = getSelectionsIds();
            if(ids.length == 0){
                $.messager.alert('提示','未选中商品!');
                return ;
            }
            $.messager.confirm('确认','确定上架ID为 '+ids+' 的商品吗?',function(r){
                if (r){
                    var params = {"ids":ids};
                    $.post("/rest/item/reshelf",params, function(data){
                        if(data.status == 200){
                            $.messager.alert('提示','上架商品成功!',undefined,function(){
                                $("#itemList").datagrid("reload");
                            });
                        }
                    });
                }
            });
        }
    }];
</script>

后台向前台返Json 数据 的形式
如果你显示不出来,那么就参考下面的格式,一定要符合这种格式,一定要符合这种格式,一定要符合这种格式,重要事情说三遍

 1 {"total":8,"rows":[
 2   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 3   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 4   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 5   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 6   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 7   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 8   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"},
 9   {"id":"101","name":"正义无限公司","coding":"01","abbreviation":"正义","industryRegistrationId":"1123456","corporation":"张三"}
10 ],
11   "title":[
12     {
13       "field":"id",
14       "title":"公司自编码"
15     },
16     {
17       "field":"name",
18       "title":"公司名称"
19     },
20     {
21       "field":"coding",
22       "title":"编码"
23     },
24     {
25       "field":"abbreviation",
26       "title":"公司简称"
27     },
28     {
29       "field":"industryRegistrationId",
30       "title":"工商注册号"
31     },
32     {
33       "field":"corporation",
34       "title":"公司法人"
35     }
36   ]
37 }

我们会将这种形式的数据格式 封装成一个工具类 进行转换

在foreknow-common中 创建com.foreknow.common.pojo
EUDataGridResult.java

package com.foreknow.common.pojo;

import java.util.List;
/**
 * 
 * {total:"8",rows:[{"id":"1","name":"tom",{"id":"2","name":"haha"}]} 
 * @author Administrator
 *
 */
public class EUDataGridResult {
     private  long total;
     //?代表未知的泛型
     private List<?> rows;
     public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }

 }

最后 写Controller foreknow-manager-web下
ItemController.java

package com.foreknow.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreknow.common.pojo.EUDataGridResult;
import com.foreknow.pojo.TbItem;
import com.foreknow.service.ItemService;

@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;

    //@PathVariable表示从url中获取到参数
    //如果这个参数和url里面{itemId}名字是一样的话就不需要写value
    //如果不一致的话就需要添加value:@PathVariable("id")
    //向前台返回Json     @ResponseBody
    @RequestMapping("/item/{itemId}")
    @ResponseBody
    public TbItem getItemById(@PathVariable Long itemId) {
        TbItem tbItem =itemService.getItemById(itemId);

        return tbItem;
    }
    /**
     * 分页查询
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/item/list")
    @ResponseBody
    public EUDataGridResult getItemList(Integer page,Integer rows) {
        EUDataGridResult result = itemService.getItemList(page, rows);
        return result;
    }
}

测试页面

image
上一篇 下一篇

猜你喜欢

热点阅读