单品页查询
 

当点击某个商品的时候,查看该商品的详细信息:

移动商城第六篇【单品查询、静态化页面】_移动商城

修改每个商品的超链接:

                <a href="${path}/item/toProductDetail.do?itemId=${item.itemId}" title="张同来" target="_blank" class="pic"><img                        src="${file_path}${item.imgs}" alt="摩托罗拉XT319"/></a><img
                       src="${file_path}${item.imgs}" alt="摩托罗拉XT319"/>
</a>

提供对应的controller方法

    /**     * 查看商品的单品页信息     *     * @return     */    @RequestMapping("/toProductDetail.do")    public String toProductDetail() {        return "productDetail";    }
   @RequestMapping("/toProductDetail.do")
   public String toProductDetail() {



       return "productDetail";
   }

进入到页面上,我们来查看一下有什么属性要展示出来的:

移动商城第六篇【单品查询、静态化页面】_移动商城_02移动商城第六篇【单品查询、静态化页面】_移动商城_03

我们发现这些数据涉及到了多张表的查询,下面就来分析一下吧:

我们主要查询的是商品的信息,因此商品需要联合上边那些关联关系一次查询出来!

编写SQL

SELECT *FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv,EB_ITEM_CLOB icWHERE eb.ITEM_ID = sku.ITEM_ID      AND fe.FEATURE_ID = pa.FEATURE_ID      AND ic.ITEM_ID = eb.ITEM_ID         AND pa.ITEM_ID = eb.ITEM_ID      AND sku.SKU_ID = sv.SKU_ID      AND eb.ITEM_ID = 3100
FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv,EB_ITEM_CLOB ic
WHERE eb.ITEM_ID = sku.ITEM_ID
     AND fe.FEATURE_ID = pa.FEATURE_ID
     AND ic.ITEM_ID = eb.ITEM_ID  
     AND pa.ITEM_ID = eb.ITEM_ID
     AND sku.SKU_ID = sv.SKU_ID
     AND eb.ITEM_ID = 3100

上面就是我们的sql语句。联合了6张表进行查询。

在联合查询的时候需要注意,如果某一张表的数据不存在,在联合的时候另一张表的数据就查询不出来了。因此,我们是需要考虑是否需要外连接把数据查询出来的。!

经过我们的分析得出,商品是可以没有最小销售单元的特殊值的。因此用到了外连接

SELECT *FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv, EB_ITEM_CLOB icWHERE eb.ITEM_ID = sku.ITEM_ID      AND fe.FEATURE_ID = pa.FEATURE_ID      AND ic.ITEM_ID = eb.ITEM_ID      AND pa.ITEM_ID = eb.ITEM_ID      AND sku.SKU_ID = sv.SKU_ID(+)      AND eb.ITEM_ID = 3100
FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv, EB_ITEM_CLOB ic
WHERE eb.ITEM_ID = sku.ITEM_ID
     AND fe.FEATURE_ID = pa.FEATURE_ID
     AND ic.ITEM_ID = eb.ITEM_ID
     AND pa.ITEM_ID = eb.ITEM_ID
     AND sku.SKU_ID = sv.SKU_ID(+)
     AND eb.ITEM_ID = 3100

实体关联数据

在Item实体中,我们需要关联对应的数据!

    //对应大字段关系    private EbItemClob clob;    //对应最小销售单元关系    private List<EbSku> ebSkus;    //参数值数据    private List<EbParaValue> paraList;    //set\get方法
   private EbItemClob clob;

   //对应最小销售单元关系
   private List<EbSku> ebSkus;

   //参数值数据
   private List<EbParaValue> paraList;

   //set\get方法

在参数值实体表中关联属性表的名称:

    //关联与属性表的关系,由于通过featureId已经能够体现一对一的,我们这里就可以直接使用名称了。    //当然了,我们在这里也是可以直接使用对象的,但是为了方便就使用属性而已。    private String featureName;
   //当然了,我们在这里也是可以直接使用对象的,但是为了方便就使用属性而已。
   private String featureName;

编写dao、service、mapper、controller

mapper:

 <resultMap id="itemDetailMap" type="com.rl.ecps.model.EbItem" extends="BaseResultMap">        <!--与大字段的关系-->        <association property="clob" javaType="com.rl.ecps.model.EbItemClob">            <id column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />            <result column="ITEM_DESC" jdbcType="CLOB" property="itemDesc" />            <result column="PACKING_LIST" jdbcType="CLOB" property="packingList" />        </association>        <collection property="paraList" ofType="com.rl.ecps.model.EbParaValue">            <id column="PARA_ID" jdbcType="DECIMAL" property="paraId" />            <result column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />            <result column="FEATURE_ID" jdbcType="DECIMAL" property="featureId" />            <result column="PARA_VALUE" jdbcType="VARCHAR" property="paraValue" />            <result column="FEATURE_NAME" property="featureName"/>        </collection>        <!--与最小销售单元的关系-->        <collection property="ebSkus" ofType="com.rl.ecps.model.EbSku">            <id column="SKU_ID" jdbcType="DECIMAL" property="skuId" />            <result column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />            <result column="SKU" jdbcType="VARCHAR" property="sku" />            <result column="SKU_PRICE" jdbcType="DECIMAL" property="skuPrice" />            <result column="SHOW_STATUS" jdbcType="DECIMAL" property="showStatus" />            <result column="STOCK_INVENTORY" jdbcType="DECIMAL" property="stockInventory" />            <result column="SKU_UPPER_LIMIT" jdbcType="DECIMAL" property="skuUpperLimit" />            <result column="LOCATION" jdbcType="VARCHAR" property="location" />            <result column="SKU_IMG" jdbcType="VARCHAR" property="skuImg" />            <result column="SKU_SORT" jdbcType="DECIMAL" property="skuSort" />            <result column="SKU_NAME" jdbcType="VARCHAR" property="skuName" />            <result column="MARKET_PRICE" jdbcType="DECIMAL" property="marketPrice" />            <result column="CREATE_TIME" jdbcType="TIMESTAMP" property="createTime" />            <result column="UPDATE_TIME" jdbcType="TIMESTAMP" property="updateTime" />            <result column="CREATE_USER_ID" jdbcType="DECIMAL" property="createUserId" />            <result column="UPDATE_USER_ID" jdbcType="DECIMAL" property="updateUserId" />            <result column="ORIGINAL_SKU_ID" jdbcType="DECIMAL" property="originalSkuId" />            <result column="LAST_STATUS" jdbcType="DECIMAL" property="lastStatus" />            <result column="MERCHANT_ID" jdbcType="DECIMAL" property="merchantId" />            <result column="SKU_TYPE" jdbcType="DECIMAL" property="skuType" />            <result column="SALES" jdbcType="DECIMAL" property="sales" />            <result column="RES_CODE" jdbcType="VARCHAR" property="resCode" />            <result column="PACK_ID" jdbcType="DECIMAL" property="packId" />            <collection property="specList" ofType="com.rl.ecps.model.EbSpecValue">                <id column="SPEC_ID" jdbcType="DECIMAL" property="specId" />                <result column="SKU_ID" jdbcType="DECIMAL" property="skuId" />                <result column="FEATURE_ID" jdbcType="DECIMAL" property="featureId" />                <result column="SPEC_VALUE" jdbcType="VARCHAR" property="specValue" />            </collection>        </collection>    </resultMap>    <select id="selectItemDetail" parameterType="long" resultMap="itemDetailMap">        SELECT *        FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv, EB_ITEM_CLOB ic        WHERE eb.ITEM_ID = sku.ITEM_ID              AND fe.FEATURE_ID = pa.FEATURE_ID              AND ic.ITEM_ID = eb.ITEM_ID              AND pa.ITEM_ID = eb.ITEM_ID              AND sku.SKU_ID = sv.SKU_ID(+)              AND eb.ITEM_ID = #{itemId}    </select>

       <!--与大字段的关系-->
       <association property="clob" javaType="com.rl.ecps.model.EbItemClob">
           <id column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />
           <result column="ITEM_DESC" jdbcType="CLOB" property="itemDesc" />
           <result column="PACKING_LIST" jdbcType="CLOB" property="packingList" />
       </association>


       <collection property="paraList" ofType="com.rl.ecps.model.EbParaValue">
           <id column="PARA_ID" jdbcType="DECIMAL" property="paraId" />
           <result column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />
           <result column="FEATURE_ID" jdbcType="DECIMAL" property="featureId" />
           <result column="PARA_VALUE" jdbcType="VARCHAR" property="paraValue" />
           <result column="FEATURE_NAME" property="featureName"/>
       </collection>

       <!--与最小销售单元的关系-->
       <collection property="ebSkus" ofType="com.rl.ecps.model.EbSku">
           <id column="SKU_ID" jdbcType="DECIMAL" property="skuId" />
           <result column="ITEM_ID" jdbcType="DECIMAL" property="itemId" />
           <result column="SKU" jdbcType="VARCHAR" property="sku" />
           <result column="SKU_PRICE" jdbcType="DECIMAL" property="skuPrice" />
           <result column="SHOW_STATUS" jdbcType="DECIMAL" property="showStatus" />
           <result column="STOCK_INVENTORY" jdbcType="DECIMAL" property="stockInventory" />
           <result column="SKU_UPPER_LIMIT" jdbcType="DECIMAL" property="skuUpperLimit" />
           <result column="LOCATION" jdbcType="VARCHAR" property="location" />
           <result column="SKU_IMG" jdbcType="VARCHAR" property="skuImg" />
           <result column="SKU_SORT" jdbcType="DECIMAL" property="skuSort" />
           <result column="SKU_NAME" jdbcType="VARCHAR" property="skuName" />
           <result column="MARKET_PRICE" jdbcType="DECIMAL" property="marketPrice" />
           <result column="CREATE_TIME" jdbcType="TIMESTAMP" property="createTime" />
           <result column="UPDATE_TIME" jdbcType="TIMESTAMP" property="updateTime" />
           <result column="CREATE_USER_ID" jdbcType="DECIMAL" property="createUserId" />
           <result column="UPDATE_USER_ID" jdbcType="DECIMAL" property="updateUserId" />
           <result column="ORIGINAL_SKU_ID" jdbcType="DECIMAL" property="originalSkuId" />
           <result column="LAST_STATUS" jdbcType="DECIMAL" property="lastStatus" />
           <result column="MERCHANT_ID" jdbcType="DECIMAL" property="merchantId" />
           <result column="SKU_TYPE" jdbcType="DECIMAL" property="skuType" />
           <result column="SALES" jdbcType="DECIMAL" property="sales" />
           <result column="RES_CODE" jdbcType="VARCHAR" property="resCode" />
           <result column="PACK_ID" jdbcType="DECIMAL" property="packId" />
           <collection property="specList" ofType="com.rl.ecps.model.EbSpecValue">
               <id column="SPEC_ID" jdbcType="DECIMAL" property="specId" />
               <result column="SKU_ID" jdbcType="DECIMAL" property="skuId" />
               <result column="FEATURE_ID" jdbcType="DECIMAL" property="featureId" />
               <result column="SPEC_VALUE" jdbcType="VARCHAR" property="specValue" />
           </collection>
       </collection>
   </resultMap>

   <select id="selectItemDetail" parameterType="long" resultMap="itemDetailMap">

       SELECT *
       FROM EB_ITEM eb, EB_SKU sku, EB_PARA_VALUE pa, EB_FEATURE fe, EB_SPEC_VALUE sv, EB_ITEM_CLOB ic
       WHERE eb.ITEM_ID = sku.ITEM_ID
             AND fe.FEATURE_ID = pa.FEATURE_ID
             AND ic.ITEM_ID = eb.ITEM_ID
             AND pa.ITEM_ID = eb.ITEM_ID
             AND sku.SKU_ID = sv.SKU_ID(+)
             AND eb.ITEM_ID = #{itemId}
   </select>

dao:

    public EbItem selectItemDetail(Long itemId) {        return this.getSqlSession().selectOne(nameSpace + "selectItemDetail", itemId);    }
       return this.getSqlSession().selectOne(nameSpace + "selectItemDetail", itemId);
   }

service:

    public EbItem selectItemDetail(Long itemId) {        return itemDao.selectItemDetail(itemId);    }
       return itemDao.selectItemDetail(itemId);
   }

controller:

    /**     * 查看商品的单品页信息     *     * @return     */    @RequestMapping("/toProductDetail.do")    public String toProductDetail(Long itemId,Model model) {        EbItem ebItem = itemService.selectItemDetail(itemId);        model.addAttribute("item", ebItem);        return "productDetail";    }
   @RequestMapping("/toProductDetail.do")
   public String toProductDetail(Long itemId,Model model) {

       EbItem ebItem = itemService.selectItemDetail(itemId);
       model.addAttribute("item", ebItem);
       return "productDetail";
   }
移动商城第六篇【单品查询、静态化页面】_移动商城_04
移动商城第六篇【单品查询、静态化页面】_移动商城_05同步价钱、规格、库存

当我们点击16g、32G、64G的时候,价钱和库存应该要同步起来。

移动商城第六篇【单品查询、静态化页面】_移动商城_06

因此,我们需要用到ajax

首先,为每个a标签绑定单机事件

  <div class="pre spec" id="skuChange">        .....a标签    </div>
       .....a标签
   </div>

ajax:

            //为每个a标签绑定事件            $("#skuChange a").click(function () {                //点击某一个时,样式发生改变                $(this).attr("class", "here");                //其他的样式去除掉                $(this).siblings().attr("class","");                //得到a标签的自定义属性skuId                var skuId = $(this).attr("skuId");                $.ajax({                    url: "${path}/item/updatePriceAndStock",                    type: "post",                    data:{skuId:skuId},                    success: function (responseText) {                    },                    error:function () {                    }                });
           $("#skuChange a").click(function () {

               //点击某一个时,样式发生改变
               $(this).attr("class", "here");
               //其他的样式去除掉
               $(this).siblings().attr("class","");

               //得到a标签的自定义属性skuId
               var skuId = $(this).attr("skuId");

               $.ajax({

                   url: "${path}/item/updatePriceAndStock",
                   type: "post",
                   data:{skuId:skuId},
                   success: function (responseText) {

                   },
                   error:function () {
                   }
               });

controller:

    /**     * 更新页面上的库存和价钱     *     * @return     */    @RequestMapping("/updatePriceAndStock.do")    public void updatePriceAndStock(Long skuId, HttpServletResponse response) {        if (skuId != null) {            //得到具体的库存对象            EbSku ebSku = skuService.selectByPrimaryKey(skuId);            //将对象写成JSON返回出去            JSONObject jsonObject = new JSONObject();            jsonObject.accumulate("sku", ebSku);            String result = jsonObject.toString();            ResourcesUtils.printJSON(result,response);        }    }
   @RequestMapping("/updatePriceAndStock.do")
   public void updatePriceAndStock(Long skuId, HttpServletResponse response) {

       if (skuId != null) {

           //得到具体的库存对象
           EbSku ebSku = skuService.selectByPrimaryKey(skuId);

           //将对象写成JSON返回出去
           JSONObject jsonObject = new JSONObject();
           jsonObject.accumulate("sku", ebSku);
           String result = jsonObject.toString();

           ResourcesUtils.printJSON(result,response);
       }
   }

ajax补全:

            //为每个a标签绑定事件            $("#skuChange a").click(function () {                //点击某一个时,样式发生改变                $(this).attr("class", "here");                //其他的样式去除掉                $(this).siblings().attr("class","");                //得到a标签的自定义属性skuId                var skuId = $(this).attr("skuId");                $.ajax({                    url: "${path}/item/updatePriceAndStock.do",                    type: "post",                    data:{skuId:skuId},                    success: function (responseText) {                        var parseJSON = $.parseJSON(responseText);                        //将价钱设置为当前库存的                        $("#skuPrice").html(parseJSON.sku.skuPrice);                        $("#marketPrice").html(parseJSON.sku.marketPrice);                        //判断是否有货                        var stock = parseJSON.sku.stockInventory;                        console.log(stock);                        if(stock>0) {                            $("#stock").html("有货");                        }else {                            $("#stock").html("无货");                        }                    },                    error:function () {                    }                });            });
           $("#skuChange a").click(function () {

               //点击某一个时,样式发生改变
               $(this).attr("class", "here");
               //其他的样式去除掉
               $(this).siblings().attr("class","");

               //得到a标签的自定义属性skuId
               var skuId = $(this).attr("skuId");

               $.ajax({

                   url: "${path}/item/updatePriceAndStock.do",
                   type: "post",
                   data:{skuId:skuId},
                   success: function (responseText) {


                       var parseJSON = $.parseJSON(responseText);

                       //将价钱设置为当前库存的

                       $("#skuPrice").html(parseJSON.sku.skuPrice);
                       $("#marketPrice").html(parseJSON.sku.marketPrice);

                       //判断是否有货
                       var stock = parseJSON.sku.stockInventory;
                       console.log(stock);
                       if(stock>0) {
                           $("#stock").html("有货");
                       }else {
                           $("#stock").html("无货");

                       }
                   },
                   error:function () {
                   }
               });


           });

到目前为止,我们已经能够联动更新了…

还有值得注意的是:想要一进去就联动更新我们的库存和价钱。我们可以使用jquery的trigger方法:

    $("#skuChange a:first").trigger("click");"click");
静态化页面

首先,我们要知道为什么使用静态化页面???

静态页面= 模版+数据

我们的单品页面会经常被访问到,而每次我们都是需要去访问数据库来查询具体的数据。这样很耗费性能

移动商城第六篇【单品查询、静态化页面】_移动商城_07

那么能不能不访问数据库就能够查询出数据的数据呢??

当用户访问单品页面的之前,我们就可以把页面静态化(模版+数据),那么用户访问被静态化的页面,也就是html就行了。这样一来,查看单品页就不用访问数据库了。。

那怎么使用呢??

将我们的单品页弄成是静态页:

移动商城第六篇【单品查询、静态化页面】_移动商城_08

我们的静态页到最后是变成HTML格式的,因此是不能用半点的JAVA语法的。因此要把动态的数据改成是freemaker所熟悉的语法来更替掉

常用的语法

使用frermarker语法 定义path的变量

<#assign path="http://localhost:8080/ecps-portal">

这种不用改,我们只要将item传入map中就行了。

移动商城第六篇【单品查询、静态化页面】_移动商城_09

forEach和if标签都要修改

修改前:

  <c:forEach items="${item.ebSkus }" var="sku" varStatus="state">                                    <c:choose>                                        <c:when test="${state.index == 0 }">                                            <a href="javascript:void(0);" class="here" skuId="${sku.skuId}">                                                <c:forEach items="${sku.specList }" var="spec">                                                    ${spec.specValue }                                                </c:forEach>                                            </a>                                        </c:when>                                        <c:otherwise>                                            <a href="javascript:void(0);" skuId="${sku.skuId }">                                                <c:forEach items="${sku.specList }" var="spec">                                                    ${spec.specValue }                                                </c:forEach>                                            </a>                                        </c:otherwise>                                    </c:choose>                                </c:forEach>
                                   <c:choose>
                                       <c:when test="${state.index == 0 }">
                                           <a href="javascript:void(0);" class="here" skuId="${sku.skuId}">
                                               <c:forEach items="${sku.specList }" var="spec">
                                                   ${spec.specValue }
                                               </c:forEach>
                                           </a>
                                       </c:when>
                                       <c:otherwise>
                                           <a href="javascript:void(0);" skuId="${sku.skuId }">
                                               <c:forEach items="${sku.specList }" var="spec">
                                                   ${spec.specValue }
                                               </c:forEach>
                                           </a>
                                       </c:otherwise>
                                   </c:choose>

                               </c:forEach>

修改后:

                        <#list item.skuList as sku>                                <#if sku_index == 0>                                    <a href="javascript:void(0);" class="here" skuId="${sku.skuId?c }">                                        <#list sku.specList as spec>                                            ${spec.specValue }                                        </#list>                                    </a>                                <#else>                                    <a href="javascript:void(0);" skuId="${sku.skuId?c }">                                        <#list sku.specList as spec>                                            ${spec.specValue }                                        </#list>                                    </a>                                </#if>                        </#list>
                               <#if sku_index == 0>
                                   <a href="javascript:void(0);" class="here" skuId="${sku.skuId?c }">
                                       <#list sku.specList as spec>
                                           ${spec.specValue }
                                       </#list>
                                   </a>

                               <#else>
                                   <a href="javascript:void(0);" skuId="${sku.skuId?c }">
                                       <#list sku.specList as spec>
                                           ${spec.specValue }
                                       </#list>
                                   </a>
                               </#if>

                       </#list>

freemarker语法自动带有,号的数值类型,我们一般不使用。于是使用?c来格式化

skuId="${sku.skuId?c }

时间的转换:

${sendTime?string("yyyy-MM-dd HH:mm:ss")}"yyyy-MM-dd HH:mm:ss")}

freemarker工具类

package com.rl.ecps.utils;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;public class FMutil {    /**     *      * @param ftlName:模板名     * @param fileName:生成的html名字     * @param map 数据库中的数据     * @throws Exception     */    public void ouputFile(String ftlName, String fileName,  Map<String, Object> map) throws Exception{        //创建fm的配置        Configuration config = new Configuration();        //指定默认编码格式        config.setDefaultEncoding("UTF-8");        //设置模板的包路径        config.setClassForTemplateLoading(this.getClass(), "/com/rl/ecps/ftl");        //获得包的模板        Template template = config.getTemplate(ftlName);        //指定文件输出的路径        String path = "X:\\Users\\ozc\\Desktop\\parent1\\portal\\src\\main\\webapp\\static";        //定义输出流,注意的必须指定编码        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path+"/"+fileName)),"UTF-8"));        //生成模板        template.process(map, writer);    }}

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FMutil {

   /**
    *
    * @param ftlName:模板名
    * @param fileName:生成的html名字
    * @param map 数据库中的数据
    * @throws Exception
    */

   public void ouputFile(String ftlName, String fileName,  Map<String, Object> map) throws Exception{
       //创建fm的配置
       Configuration config = new Configuration();
       //指定默认编码格式
       config.setDefaultEncoding("UTF-8");
       //设置模板的包路径
       config.setClassForTemplateLoading(this.getClass(), "/com/rl/ecps/ftl");
       //获得包的模板
       Template template = config.getTemplate(ftlName);
       //指定文件输出的路径
       String path = "X:\\Users\\ozc\\Desktop\\parent1\\portal\\src\\main\\webapp\\static";
       //定义输出流,注意的必须指定编码
       Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path+"/"+fileName)),"UTF-8"));
       //生成模板
       template.process(map, writer);
   }


}

测试

    @Test    public void TestFreemarker() throws Exception {        EbItem ebItem = itemService.selectItemDetail((long) 3100);        Map map = new HashMap();        map.put("item", ebItem);        FMutil fMutil = new FMutil();        fMutil.ouputFile("productDetail.ftl", ebItem.getItemId() + ".html", map);    }
   public void TestFreemarker() throws Exception {
       EbItem ebItem = itemService.selectItemDetail((long) 3100);

       Map map = new HashMap();
       map.put("item", ebItem);
       FMutil fMutil = new FMutil();
       fMutil.ouputFile("productDetail.ftl", ebItem.getItemId() + ".html", map);

   }

最终生成我们的静态页面:

移动商城第六篇【单品查询、静态化页面】_移动商城_10

访问静态页面:

移动商城第六篇【单品查询、静态化页面】_移动商城_11发布静态页面

我们上边是通过test的方式来生成我们的静态页面的。明显地,我们生成静态页面就不是在portal进行处理的。应该是交由console来进行处理的。

那现在问题来了,怎么将console处理后的页面交由到portal中呢??

由于IP地址不同,是两台不同的机器,我们就可以想到webservice!

编写webService代码:

@WebServicepublic interface EbWSItemService {    public String publishItem(Long itemId, String password) throws Exception;}
public interface EbWSItemService {

   public String publishItem(Long itemId, String password) throws Exception;

}
@Servicepublic class EbWSItemServiceImpl implements EbWSItemService {    @Autowired    private EbItemDao itemDao;    public String publishItem(Long itemId, String password) throws Exception {        String pass = ResourcesUtils.readProp("ws_pass");        if(StringUtils.equals(password, pass)){            EbItem item  = itemDao.selectItemDetail(itemId);            Map<String,Object> map = new HashMap<String,Object>();            map.put("item", item);            FMutil fm = new FMutil();            fm.ouputFile("productDetail.ftl", item.getItemId()+".html", map);            return "success";        }else{            return "pass_error";        }    }}
public class EbWSItemServiceImpl implements EbWSItemService {

   @Autowired
   private EbItemDao itemDao;

   public String publishItem(Long itemId, String password) throws Exception {
       String pass = ResourcesUtils.readProp("ws_pass");
       if(StringUtils.equals(password, pass)){
           EbItem item  = itemDao.selectItemDetail(itemId);
           Map<String,Object> map = new HashMap<String,Object>();
           map.put("item", item);
           FMutil fm = new FMutil();
           fm.ouputFile("productDetail.ftl", item.getItemId()+".html", map);
           return "success";
       }else{
           return "pass_error";
       }
   }

}

使用CXF框架将我们的webService服务在portal端发布

cxf-servlet.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:jaxws="http://cxf.apache.org/jaxws"    xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"    xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans.xsd            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">    <!-- 引入CXF Bean定义如下,早期的版本中使用 -->    <import resource="classpath:META-INF/cxf/cxf.xml" />    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />    <!--         address:        http://localhost:8080/ecps-portal/[url-partten]/address     -->    <jaxws:server id="publishItem" address="/publishItem" serviceClass="com.rl.ecps.webservice.EbWSItemService">        <jaxws:serviceBean>            <bean class="com.rl.ecps.webservice.EbWSItemServiceImpl"></bean>        </jaxws:serviceBean>    </jaxws:server></beans>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
   xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
           http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
           http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
           http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"
>

   <!-- 引入CXF Bean定义如下,早期的版本中使用 -->
   <import resource="classpath:META-INF/cxf/cxf.xml" />
   <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
   <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

   <!--
       address:
       http://localhost:8080/ecps-portal/[url-partten]/address
    -->

   <jaxws:server id="publishItem" address="/publishItem" serviceClass="com.rl.ecps.webservice.EbWSItemService">
       <jaxws:serviceBean>
           <bean class="com.rl.ecps.webservice.EbWSItemServiceImpl"></bean>
       </jaxws:serviceBean>
   </jaxws:server>
</beans>

portal端进行加载该配置文件:

    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <context-param>        <param-name>contextConfigLocation</param-name>        <!--加载cxf配置文件-->        <param-value>classpath*:beans.xml,classpath*:cxf-servlet.xml</param-value>    </context-param>    <!--cxf的Servlet-->    <servlet>        <servlet-name>cxf</servlet-name>        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>cxf</servlet-name>        <url-pattern>/services/*</url-pattern>    </servlet-mapping>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <context-param>
       <param-name>contextConfigLocation</param-name>

       <!--加载cxf配置文件-->
       <param-value>classpath*:beans.xml,classpath*:cxf-servlet.xml</param-value>
   </context-param>


   <!--cxf的Servlet-->
   <servlet>
       <servlet-name>cxf</servlet-name>
       <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>cxf</servlet-name>
       <url-pattern>/services/*</url-pattern>
   </servlet-mapping>

当访问portal端的services的时候,就可以看到服务进行发出去了!

移动商城第六篇【单品查询、静态化页面】_移动商城_12

使用IDEA的工具将WSDL地址转成是Java类

移动商城第六篇【单品查询、静态化页面】_移动商城_13

得出这么一堆对象

移动商城第六篇【单品查询、静态化页面】_移动商城_14

在service层调用这么一些对象(也就是portal发布的服务)

    public String publishItem(Long itemId, String password) throws Exception {        EbWSItemServiceService itemServiceService = new EbWSItemServiceService();        EbWSItemService ebWSItemServicePort = itemServiceService.getEbWSItemServicePort();        return ebWSItemServicePort.publishItem(itemId, password);    }

       EbWSItemServiceService itemServiceService = new EbWSItemServiceService();
       EbWSItemService ebWSItemServicePort = itemServiceService.getEbWSItemServicePort();
       return ebWSItemServicePort.publishItem(itemId, password);
   }

controller调用service

    @RequestMapping("/publishItem.do")    public void publishItem(Long itemId, PrintWriter out) throws Exception {        String password = ResourcesUtils.readProp("ws_pass");        String result = itemService.publishItem(itemId, password);        out.write(result);    }"/publishItem.do")
   public void publishItem(Long itemId, PrintWriter out) throws Exception {
       String password = ResourcesUtils.readProp("ws_pass");
       String result = itemService.publishItem(itemId, password);
       out.write(result);
   }

前台时候ajax进行调用:

        function publishItem(itemId) {            $.ajax({                url:"${path}/item/publishItem.do",                type:"post",                dataType:"text",                data:{                    itemId:itemId                },                success:function(responseText){                    if(responseText == "success"){                        alert("发布成功");                    }else{                        alert("密码错误");                    }                    tipHide("#importLoadDiv");                },                error:function(){                    alert("系统错误");                }            })        }
           $.ajax({
               url:"${path}/item/publishItem.do",
               type:"post",
               dataType:"text",
               data:{
                   itemId:itemId
               },
               success:function(responseText){
                   if(responseText == "success"){
                       alert("发布成功");
                   }else{
                       alert("密码错误");
                   }
                   tipHide("#importLoadDiv");
               },
               error:function(){
                   alert("系统错误");
               }
           })

       }

这样一来,console是调用portal发布的webservice程序。那么生成的静态页面就是portal上的。

总结

如果文章有错的地方欢迎指正,大家互相交流。习惯在微信看技术文章,想要获取更多的Java资源的同学,可以关注微信公众号:Java3y