【j2ee spring】41、巴巴运动网的产品查询

巴巴运动网的产品查询

1、项目图解

这里写图片描述

这里写图片描述

2、我们开始做我们的相应的功能模块
页面的素材我会上传的,链接是:http://download.csdn.net/detail/cutter_point/8803985

产品的查询界面query_product.jsp

<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>查询产品</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../css/vip.css" type="text/css">
<SCRIPT language=JavaScript src="../js/FoshanRen.js"></SCRIPT>
</head>

<body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<s:form action="productlist" method="post">
<s:hidden name="typeid"/>
<s:hidden name="query" value="true" />
  <table width="98%" border="0" cellspacing="1" cellpadding="3" align="center">
    <tr bgcolor="6f8ac4"> 
      <td colspan="2" ><font color="#FFFFFF">查询产品:</font></td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">产品名称  :</div></td>
      <td width="75%"> <input name="name" size="50" maxlength="40" /> </td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">产品类别  :</div></td> 
      <td width="75%"> <input type="text" name="v_type_name" disabled="true" size="30" value="${typename}"/> 
        <input type="button" name="select" value="选择..." onClick="javaScript:winOpen('<s:url action="select-productmanage"/>','列表',600,400)">
      </td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">底(采购)价(元) :</div></td>
      <td width="75%"><input name="startbaseprice" size="10" maxlength="10" onkeypress="javascript:InputLongNumberCheck()" /><input name="endbaseprice" size="10" maxlength="10" onkeypress="javascript:InputLongNumberCheck()" /> 之间
</td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">销售价(元) :</div></td>
      <td width="75%"><input name="startsellprice" size="10" maxlength="10" onkeypress="javascript:InputLongNumberCheck()" /><input name="endsellprice" size="10" maxlength="10" onkeypress="javascript:InputLongNumberCheck()" />之间
      </td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">货号 :</div></td>
      <td width="75%"> <input name="code" size="20" maxlength="30" /> (注:供货商提供的便于产品查找的编号)</td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="25%"> <div align="right">品牌 :</div></td>
      <td width="75%"> 
        <select name="brandid">
            <option value="">***无***</option>
            <s:iterator value="#request.brands" var="brand">
                <option value="<s:property value="#brand.code" />"><s:property value="#brand.name" /> </option>
            </s:iterator>
        </select>
        </td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td colspan="2"> <div align="center"> 
          <input type="submit" value=" 确 认 " class="frm_btn">
          &nbsp;&nbsp;<input type="button" name="Button" value=" 返 回 " class="frm_btn" onclick="javascript:history.back()">
        </div></td>
    </tr>
  </table>
</s:form>
<br>
</body>
</html>

我们的页面控制器action

/**
 * 功能:这个是产品的管理动作
 * 时间:2015年5月27日17:17:45
 * 文件:ProductManageAction.java
 * 作者:cutter_point
 */
package com.cutter_point.web.action.product;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cutter_point.bean.QueryResult;
import com.cutter_point.bean.product.Brand;
import com.cutter_point.bean.product.ProductInfo;
import com.cutter_point.bean.product.ProductStyle;
import com.cutter_point.bean.product.ProductType;
import com.cutter_point.bean.product.Sex;
import com.cutter_point.service.product.BrandService;
import com.cutter_point.service.product.ProductInfoService;
import com.cutter_point.service.product.ProductTypeService;
import com.cutter_point.utils.SiteUrl;
import com.cutter_point.web.formbean.product.ProductForm;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
public class ProductManageAction extends ActionSupport implements ServletRequestAware, ModelDriven<ProductForm>
{
    private static final long serialVersionUID = 6647552432813142686L;
    @Resource
    private ProductInfoService pis; //注入产品服务类
    @Resource
    private BrandService bs;    //注入品牌服务类
    @Resource
    private ProductTypeService pts; //注入产品类型服务类
    private HttpServletRequest request;
    private ProductForm pf;

    /**
     * 设置产品推荐
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String commend() throws Exception
    {
        pis.setCommendStatus(pf.getProductids(), true); //上架就是可见
        request.setAttribute("message", "产品推荐成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    /**
     * 设置产品不推荐
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String uncommend() throws Exception
    {
        pis.setCommendStatus(pf.getProductids(), false);    //下架就是不可见
        request.setAttribute("message", "产品不推荐成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    /**
     * 设置产品上架
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String visible() throws Exception
    {
        pis.setVisibleStatus(pf.getProductids(), true); //上架就是可见
        request.setAttribute("message", "产品上架成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    /**
     * 设置产品下架
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String disable() throws Exception
    {
        pis.setVisibleStatus(pf.getProductids(), false);    //下架就是不可见
        request.setAttribute("message", "产品下架成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    /**
     * 显示产品查询界面
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String queryUI() throws Exception
    {
        //类别名称显示出来
        request.setAttribute("brands", bs.getScrollData(Brand.class).getResultList());  //吧品牌显示出来
        return "query";
    }

    /**
     * 显示产品修改界面
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String editUI() throws Exception
    {
        //从数据库中获取相应的产品信息,根据id号获取相应的信息
        ProductInfo product = pis.find(ProductInfo.class, pf.getProductid());
        //获取产品名称
        pf.setName(product.getName());
        //设置类别id
        pf.setTypeid(product.getType().getTypeid());
        //底(采购)价
        pf.setBaseprice(product.getBaseprice());
        //市场价
        pf.setMarketprice(product.getMarketprice());
        //销售价 
        pf.setSellprice(product.getSellprice());
        //货号 
        pf.setCode(product.getCode());
        //品牌 
        if(product.getBrand() != null)
        {
            //如果对应的品牌不为空
            pf.setBrandid(product.getBrand().getCode());
        }
        //适用性别 
        pf.setSex(product.getSexrequest().toString());
        //型号 
        pf.setModel(product.getModel());
        //重量 :
        pf.setWeight(product.getWeight());
        //购买说明
        pf.setBuyexplain(product.getBuyexplain());
        //产品简介
        pf.setDescription(product.getDescription());
        //性别合适的人群
        request.setAttribute("sexname", product.getSexrequest().getName());
        //吧当前选择的品牌传出去
        request.setAttribute("brand", product.getBrand());
        //类别名称显示出来
        request.setAttribute("typename", product.getType().getName());  //吧类型显示出来
        request.setAttribute("brands", bs.getScrollData(Brand.class).getResultList());  //吧品牌显示出来
        return "edit";
    }

    /**
     * 产品修改
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String edit() throws Exception
    {
        ProductInfo product = pis.find(ProductInfo.class, pf.getProductid());   //查询出这个产品
        product.setName(pf.getName());  //获取产品名称
        product.setBaseprice(pf.getBaseprice());        //设置基础价格
        product.setSellprice(pf.getSellprice());        //设置销售价格
        product.setMarketprice(pf.getMarketprice());    //市场价
        if(pf.getBrandid() != null && !"".equals(pf.getBrandid().trim()))
        {
            product.setBrand(new Brand(pf.getBrandid()));       //设置品牌的id
        }
        product.setBuyexplain(pf.getBuyexplain());  //购买说明
        product.setCode(pf.getCode());      //货号
        product.setDescription(pf.getDescription());        //产品描述
        product.setModel(pf.getModel()); //设置型号
        product.setWeight(pf.getWeight()); //重量
        product.setSexrequest(Sex.valueOf(pf.getSex())); //性别要求
        product.setType(new ProductType(pf.getTypeid()));   //设置产品类型

        /***************************************************************************************************************
         *                  产品信息保存到数据库                                                                          ****
         ***************************************************************************************************************/
        pis.update(product);    //保存这个产品,当保存完了之后hibernate会吧这个产品的id号赋值给product


        /***************************************************************************************************************
         *                              跳转成功之后页面传值                                                                **
         ***************************************************************************************************************/
        request.setAttribute("message", "产品修改成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    /**
     * 显示类别选择界面
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String selectUI() throws Exception
    {
        String sql = "o.parentid is null and o.visible = 1";    //如果是顶级目录的话
        Object[] parems = new Object[0];    //设定相应的id号
        if(pf.getTypeid() != null && pf.getTypeid() > 0)
        {
            sql = " o.parentid = ? ";
            parems = new Object[]{pf.getTypeid()};
        }
        QueryResult<ProductType> qr = pts.getScrollData(ProductType.class, -1, -1, sql, parems);
        request.setAttribute("types", qr.getResultList());
        return "typeselect";
    }

    /**
     * 显示产品添加界面
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String addUI() throws Exception
    {
        request.setAttribute("brands", bs.getScrollData(Brand.class).getResultList());
        return "add";
    }

    /**
     * 产品添加
     * @return String struts2的返回跳转result
     * @throws Exception
     */
    public String add() throws Exception
    {
        ProductInfo product = new ProductInfo();    //新建一个产品
        product.setName(pf.getName());  //获取产品名称
        product.setBaseprice(pf.getBaseprice());        //设置基础价格
        product.setSellprice(pf.getSellprice());        //设置销售价格
        product.setMarketprice(pf.getMarketprice());    //市场价
        if(pf.getBrandid() != null && !"".equals(pf.getBrandid().trim()))
        {
            product.setBrand(new Brand(pf.getBrandid()));       //设置品牌的id
        }
        product.setBuyexplain(pf.getBuyexplain());  //购买说明
        product.setCode(pf.getCode());      //货号
        product.setDescription(pf.getDescription());        //产品描述
        product.setModel(pf.getModel()); //设置型号
        product.setWeight(pf.getWeight()); //重量
        product.setSexrequest(Sex.valueOf(pf.getSex())); //性别要求
        product.setType(new ProductType(pf.getTypeid()));   //设置产品类型

        //用来保存图片路径
        //再上传之前判断上传图片类型是不是符合要求
        if(!pf.validateFileType("logofile"))
        {
            request.setAttribute("message", "图片格式不对");
            request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
            return "message";
        }
        //得到图片后缀
        //String ext = pf.getImagefileFileName().substring(pf.getImagefileFileName().lastIndexOf('.'));
        if(pf.getImagefile().length() > 409600)
        {
            request.setAttribute("message", "图片不能大于400k");
            request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
            return "message";
        }

        /***************************************************************************************************************
         *                  产品信息保存到数据库                                                                          ****
         ***************************************************************************************************************/
        product.addProductStyle(new ProductStyle(pf.getStylename(), pf.getImagefileFileName()));    //这个里面放文件存放的名字和路径
        pis.save(product);  //保存这个产品,当保存完了之后hibernate会吧这个产品的id号赋值给product

        /***************************************************************************************************************
         *                              文件上传                                                                          **
         ***************************************************************************************************************/
        //G:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\ 这个就是realpath
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        ProductForm.saveProductImageFile(pf.getImagefile(), pf.getImagefileFileName(), pf.getTypeid(), product.getId(), realpath);

        /***************************************************************************************************************
         *                              跳转成功之后页面传值                                                                **
         ***************************************************************************************************************/
        request.setAttribute("message", "产品添加成功");
        request.setAttribute("urladdress", SiteUrl.readUrl("control.product.list"));
        return "message";
    }

    //管理文件流
    protected void close(FileOutputStream fos, FileInputStream fis)
    {
        if(fis != null)
        {
            try
            {
                fis.close();
            } 
            catch (Exception e)
            {
                System.out.println("关闭文件输入流失败");
                e.printStackTrace();
            }
        }

        if(fos != null)
        {
            try
            {
                fos.close();
            } 
            catch (Exception e)
            {
                System.out.println("关闭文件输出流失败");
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setServletRequest(HttpServletRequest arg0)
    {
        this.request = arg0;
    }

    public ProductInfoService getPis()
    {
        return pis;
    }

    public void setPis(ProductInfoService pis)
    {
        this.pis = pis;
    }

    public BrandService getBs()
    {
        return bs;
    }

    public void setBs(BrandService bs)
    {
        this.bs = bs;
    }

    public ProductForm getPf()
    {
        return pf;
    }

    public void setPf(ProductForm pf)
    {
        this.pf = pf;
    }

    @Override
    public ProductForm getModel() 
    {
        if(pf == null)
            pf = new ProductForm();

        return pf;
    }
}

然后我们得适当修改一下另外一个action
确定是从query页面来的 显示

/**
 * 功能:这个是实现产品类和web层的交互
 * 时间:2015年5月27日10:19:42
 * 文件:ProductAction.java
 * 作者:cutter_point
 */
package com.cutter_point.web.action.product;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cutter_point.bean.PageView;
import com.cutter_point.bean.QueryResult;
import com.cutter_point.bean.product.ProductInfo;
import com.cutter_point.service.product.ProductInfoService;
import com.cutter_point.web.formbean.product.ProductForm;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
public class ProductAction extends ActionSupport implements ServletRequestAware, ModelDriven<ProductForm>
{
    private static final long serialVersionUID = -1041016333626692241L;
    @Resource
    private ProductInfoService productInfoService;  //业务注入
    //request
    private HttpServletRequest request;
    private int page;
    private String query;       //判断是从那个页面来的
    private ProductForm pf; //一个表单bean

    @Override
    public String execute() throws Exception
    {
        PageView<ProductInfo> pageview = new PageView<ProductInfo>(12, this.getPage());
        int firstindex = (pageview.getCurrentpage() - 1) * pageview.getMaxresult(); //得到从哪个开始索引的值
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("visible", "desc"); //倒序,也就是1排前面了,也就是在售的牌前面
        orderby.put("id", "asc");
        QueryResult<ProductInfo> qr = null;
        //判断来的页面是那个
        if("true".equals(this.getQuery()))
        {
            StringBuilder hsql = new StringBuilder("1 = 1");    //免得后面还要确定是不是要加“and”
            List<Object> params = new ArrayList<Object>();  //这个用来存放需要的排序方式
            //是从查询页面来的需求
            //如果是查询的话,那么我们判定一下name是不是为空的
            if(pf.getName() != null && !"".equals(pf.getName().trim())) //后面那个trim是去掉空格的作用
            {
                //模糊查询一下,代表按照名称进行查询
                hsql.append(" and o.name like ?");
                params.add("%" + pf.getName() + "%");       //给问号赋值
            }

            //还有产品的类别判断
            if(pf.getTypeid() != null && pf.getTypeid() > 0)
            {
                //组装sql语句
                hsql.append(" and o.typeid = ?");
                params.add(pf.getTypeid());
            }

            //低价查询区间
            if(pf.getStartbaseprice() != null && pf.getStartbaseprice() > 0)
            {
                //组装sql语句
                hsql.append(" and o.baseprice >= ?");
                params.add(pf.getStartbaseprice());
            }
            if(pf.getEndbaseprice() != null && pf.getEndbaseprice() > 0)
            {
                //组装sql语句
                hsql.append(" and o.baseprice <= ?");
                params.add(pf.getEndbaseprice());
            }

            //销售价(元)区间
            if(pf.getStartsellprice() != null && pf.getStartsellprice() > 0)
            {
                //组装sql语句
                hsql.append(" and o.sellprice >= ?");
                params.add(pf.getStartbaseprice());
            }
            if(pf.getEndsellprice() != null && pf.getEndsellprice() > 0)
            {
                //组装sql语句
                hsql.append(" and o.sellprice <= ?");
                params.add(pf.getEndsellprice());
            }

            //货号查询
            if(pf.getCode() != null && !"".equals(pf.getCode()))
            {
                hsql.append(" and o.code = ?");
                params.add(pf.getCode());
            }

            //按品牌查询
            if(pf.getBrandid() != null && !"".equals(pf.getBrandid()))
            {
                hsql.append(" and o.brandid = ?");
                params.add(pf.getBrandid());
            }

            //这个里面是有params的时候执行的方法
            qr = productInfoService.getScrollData(ProductInfo.class, firstindex, pageview.getMaxresult(), hsql.toString(), 
                    params.toArray(), orderby);
        }
        else
        {
            qr = productInfoService.getScrollData(ProductInfo.class, firstindex, pageview.getMaxresult(), orderby);
        }


        pageview.setQueryResult(qr);
        request.setAttribute("pageView", pageview);
        return "list";
    }

    @Override
    public void setServletRequest(HttpServletRequest arg0)
    {
        this.request = arg0;
    }

    public ProductInfoService getProductInfoService()
    {
        return productInfoService;
    }

    public void setProductInfoService(ProductInfoService productInfoService)
    {
        this.productInfoService = productInfoService;
    }

    public Integer getPage()
    {
        return page < 1 ? 1 : page;
    }

    public void setPage(Integer page)
    {
        this.page = page;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    @Override
    public ProductForm getModel() 
    {
        //从页面获取表单值
        if(pf == null)
            pf = new ProductForm();

        return pf;
    }

}

3、struts2的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <include file="struts-default.xml" />
    <constant name="struts.ObjectFactory" value="spring" /> <!--    表示这里面的action由spring进行创建 -->
    <constant name="struts.devMode" value="true" />
    <!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />

    <package name="control" namespace="/control" extends="struts-default">
        <global-results>
            <result name="message">/page/share/message.jsp</result>
        </global-results>
        <action name="center-*"><!-- 直接跳转,不需要经过class的验证,默认返回success -->
            <result name="success">/page/controlcenter/{1}.jsp</result>
        </action>
        <!-- 产品类别展示 -->
        <action name="producttypelist" class="productTypeAction" method="execute">
            <result name="list">/page/product/producttypelist.jsp</result>
        </action>
        <!-- 产品类别管理 -->
        <action name="*-producttypemanage" class="productTypeManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_productType.jsp</result>
        </action>
        <action name="producttypemanage-*" class="productTypeManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_productType.jsp</result>
        </action>
        <!-- 品牌类别展示 -->
        <action name="brandlist" class="brandAction" method="execute">
            <result name="list">/page/product/brandlist.jsp</result>
        </action>
        <!-- 品牌类别管理 -->
        <action name="*-brandmanage" class="brandManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_brand.jsp</result>
        </action>
        <action name="brandmanage-*" class="brandManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_brand.jsp</result>
        </action>
        <!-- 文件展示 -->
        <action name="uploadfilelist" class="uploadFileAction" method="execute">
            <result name="list">/page/uploadfile/uploadfilelist.jsp</result>
        </action>
        <!-- 文件上传管理 -->
        <action name="*-filemanage" class="uploadfileManageAction" method="{1}">
            <result name="{1}">/page/uploadfile/{1}.jsp</result>
            <result name="fileuploadfinish">/page/uploadfile/fileuploadfinish.jsp</result>
            <result name="error">/page/uploadfile/error.jsp</result>
        </action>
        <!-- 产品分页展示 -->
        <action name="productlist" class="productAction" method="execute">
            <result name="list">/page/product/productlist.jsp</result>
        </action>
        <!-- 产品管理 -->
        <action name="*-productmanage" class="productManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_product.jsp</result>
            <result name="type{1}">/page/product/productTypeSelect.jsp</result>
        </action>
        <action name="productmanage-*" class="productManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_product.jsp</result>
        </action>
    </package>
</struts>

4、接下来我们测试一下页面的效果

我们访问这个网站

http://localhost:8080/ babaSport_1400_productinfo/control/center-main

初始界面

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

6、总结

产品的查询就是在查询界面添加一个个查询条件,然后在回调的时候还是显示界面,但是我们加上了一些查询条件,这样重数据库里面出来的数据就是筛选之后的数据了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值