你的位置:首页 > Java教程

[Java教程]易买网的一些增删改查


     正如题目所说的一样,今天就来说说易买网中的一些增删改查,主要的功能有注册、用户管理以及商品分类等!

     1.注册

     1.1 注册涉及到了一个ajax远端技术,主要是用来控制注册用户在数据库中是否存在:

 <script> $(function(){    //焦点移出表单时    $("#userId").blur(function(){      ajax();    });  });  function ajax(){     //获取用户名     var uname=$("#userId").val();     if(uname!=""){     $.ajax({      url:'<%=path%>/servlet/DuCheckDoc',      type:'POST',      data:'name='+uname,       //data是从servlet回送的内容      success:function(data){        if(data=="true"){          $("#msg").html("不能注册,该用户名已存在").addClass("error");        }else{          $("#msg").html("可以注册,用户名尚未被注册").addClass("error");        }        }      });     }        }</script>

     需要发送到下面这个servlet去判定是否存在

package servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import dao.impl.UserNameImpl_wjl;import entity.User;public class DuCheckDoc extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doPost(request, response);  }  //ajax的远端控制  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {      //解决中文乱码      request.setCharacterEncoding("utf-8");      //实现usernameimpl类的对象      UserNameImpl_wjl impl=new UserNameImpl_wjl();      String uName=request.getParameter("name");      //String uName="admin111";      String msg=null;      if (uName!=null) {        try {          List<User> list=impl.getUserName();          for (User user : list) {            if (uName.equals(user.getUserId())) {              msg="true";              break;            }else {              msg="false";            }          }                  } catch (Exception e) {          // 异常抓取          e.printStackTrace();        }     }      response.getWriter().print(msg);  }}

 

  1.2 注册还有一个自己的servlet

     

package servlet;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.sql.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import dao.impl.Registerimpl_wjl;import entity.User;public class RegisterServelt_wjl extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doPost(request, response);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    //处理乱码     request.setCharacterEncoding("utf-8");    Registerimpl_wjl rdao=new Registerimpl_wjl();    String userId=request.getParameter("userId");    String userName=request.getParameter("userName");    String password=request.getParameter("password");    //String confirmPassword=request.getParameter("confirmPassword");    String sex=request.getParameter("sex");    String flag="T";    if (sex.equals("male")){      flag="F";    }    String btime=request.getParameter("birthday");    //转化为日期    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");    Date date = null;      try {        date=new Date(format.parse(btime).getTime());      } catch (ParseException e1) {        // TODO Auto-generated catch block        e1.printStackTrace();      }    String identityCode=request.getParameter("identityCode");    String email=request.getParameter("email");    String mobile=request.getParameter("mobile");    String address=request.getParameter("address");    User user=new User();    user.setAddress(address);    user.setUserId(userId);    user.setUserName(userName);    user.setEmail(email);    user.setMale(flag);    user.setIdentityCode(identityCode);    user.setPassword(password);    user.setMobile(mobile);    user.setBirthday(date);    boolean result=rdao.addRegister(user);    if (result) {      request.getRequestDispatcher("/reg-result.jsp").forward(request, response);    }else{      response.sendRedirect("/EasyBuy_H/register.jsp");    }          }}

   注册sql语句

public boolean addRegister(User user) {    //insert into EASYBUY_USER values    //('杰克','普通用户','ss','T','1983-02-14','130406198302141869',    //'hello@bdqn.com','15812345678','北京市海淀区成府路207号','1',DEFAULT)    String sql="insert into EASYBUY_USER values(?,?,?,?,?,?,?,?,?,?,default)";    Object[] paras={user.getUserId(),user.getUserName(),user.getPassword(),        user.getMale(),user.getBirthday(),user.getIdentityCode(),user.getEmail(),user.getMobile(),        user.getAddress(),user.getStatus()};    return executeUpdate(sql, paras);  }

     2.用户管理

     2.1 根据上面的注册用户,新注册用户就会添加到用户管理中,

     2.2 用户管理的增删改查sql语句

 //利用分页进行查询出整个表  public List<User> getAllUser(int pageIndex,int pageSize) throws Exception {    List<User> list=new ArrayList<User>();    String sql="select top "+pageSize+" * from EASYBUY_USER where identity_ID not in(select top "+(pageIndex-1)*pageSize+" identity_ID from EASYBUY_USER)";         ResultSet rs=executeSelect(sql);    if (rs!=null) {      while(rs.next()){        User user=new User();        user.setId(rs.getInt("identity_ID"));        user.setUserId(rs.getString("EU_USER_ID"));        user.setUserName(rs.getString("EU_USER_NAME"));        user.setMale(rs.getString("EU_SEX"));        user.setEmail(rs.getString("EU_EMAIL"));        user.setMobile(rs.getString("EU_MOBILE"));        user.setBirthday(rs.getDate("EU_BIRTHDAY"));        user.setAddress(rs.getString("EU_ADDRESS"));        user.setPassword(rs.getString("EU_PASSWORD"));        list.add(user);      }    }    return list;  }  //按用户id查询  public List<User> getAllUserToUserId(int id) throws Exception {    List<User> list=new ArrayList<User>();    String sql="select * from EASYBUY_USER where identity_ID=?";    Object[] paras={id};    ResultSet rs=executeSelect(sql,paras);    if (rs!=null) {      while(rs.next()){        User user=new User();        user.setUserId(rs.getString("EU_USER_ID"));        user.setUserName(rs.getString("EU_USER_NAME"));        user.setMale(rs.getString("EU_SEX"));        user.setEmail(rs.getString("EU_EMAIL"));        user.setMobile(rs.getString("EU_MOBILE"));        user.setBirthday(rs.getDate("EU_BIRTHDAY"));        user.setAddress(rs.getString("EU_ADDRESS"));        user.setPassword(rs.getString("EU_PASSWORD"));        list.add(user);      }    }    return list;  }     //修改用户信息  public boolean getAllToUpdate(User user) throws Exception {    String sql="update EASYBUY_USER set EU_USER_ID=?,EU_USER_NAME=?,EU_SEX=?,EU_MOBILE=?,EU_ADDRESS=?,EU_PASSWORD=?,EU_BIRTHDAY=? where identity_ID=?";    Object[] paras={user.getUserId(),user.getUserName(),user.getMale(),user.getMobile(),user.getAddress(),user.getPassword(),user.getBirthday(),user.getId()};    return executeUpdate(sql,paras);  }  //按用户编号删除用户  public boolean getAllToDelete(int id) {    String sql="delete from EASYBUY_USER where identity_ID=?";    Object[] paras={id};    return executeUpdate(sql, paras);  }  //总记录数  public int getAllCount() throws Exception {    String sql="select COUNT(1) as num from EASYBUY_USER";    ResultSet rs=executeSelect(sql);    int result=0;    if (rs!=null) {      while(rs.next()){        result=rs.getInt("num");      }    }    return result;  }

    2.3 用户管理的servlet

package servlet;import java.io.IOException;import java.text.DateFormat;import java.util.Date;import java.util.List;import java.util.Locale;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import util.Page_hyj;import dao.impl.Registerimpl_wjl;import entity.News;import entity.User;public class UpdateUserServlet extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doPost(request, response);  }  /**   * 修改用户信息 */  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {        //处理乱码     request.setCharacterEncoding("utf-8");     Registerimpl_wjl impl=new Registerimpl_wjl();     String opr=request.getParameter("opr");     if (opr.equals("list")) {       try{      // 开始分页        // 实例化Page对象        Page_hyj page_hyj = new Page_hyj();        // .给定每页要显示几条数据        int pagesize=3;        page_hyj.setPageSize(pagesize);        // .给总页数赋值         int pageSum=0;        //总记录数        int total=impl.getAllCount();        if (total%pagesize==0) {          pageSum=total/pagesize;        }else {          pageSum=total/pagesize+1;        }        page_hyj.setPageCount(pageSum);        // 当用户还没有点击下一页是默认显示第一页数据        int pageIndex = 1;        // 获取下一页超链接设置的pageIndex的值        String uindex = request.getParameter("pageIndex");        if (uindex != null) {          // 给page类中的pageIndex赋值:(uindex不为空的时候就证明了用户点击了下一页,随之页面显示的数据也就改变了)          pageIndex = Integer.parseInt(uindex);        }        //判断是否符合显示条件        if (pageIndex<1) {          pageIndex=1;        }else if (pageIndex>page_hyj.getPageCount()) {          pageIndex=page_hyj.getPageCount();        }        //当前页数        page_hyj.setPageIndex(pageIndex);        // 给集合赋值        page_hyj.setListu(impl.getAllUser(page_hyj.getPageIndex(),page_hyj.getPageSize()));        // 设置作用域        request.setAttribute("pageIndex", pageIndex);        request.setAttribute("page", page_hyj);        request.getRequestDispatcher("/manage/user.jsp").forward(request, response);        } catch (Exception e) {        // 异常抓取        e.printStackTrace();        }     }                            //点击修改将数据加载到用户修改界面     if (opr.equals("update")) {       String userid=request.getParameter("id");       int id=0;       if (!userid.equals("")&&userid!=null) {        id=Integer.parseInt(userid);      }       List<User> listf = null;       try {        listf = impl.getAllUserToUserId(id);        request.setAttribute("id",id);        request.setAttribute("listf",listf);       } catch (Exception e) {        // 异常抓取        e.printStackTrace();       }       request.getRequestDispatcher("/manage/user-modify.jsp").forward(request, response);      }   }}

package servlet;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.sql.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import dao.impl.Registerimpl_wjl;import entity.User;public class UpdateUserInfoServlet extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doPost(request, response);  }  /**   * 修改用户信息 */  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {     //处理乱码     request.setCharacterEncoding("utf-8");    //调度 实例化 对象    Registerimpl_wjl impl=new Registerimpl_wjl();        String opr=request.getParameter("opr");    //修改    if (opr.equals("update")) {      String id=request.getParameter("sid");      //用户名      String nameid=request.getParameter("userName");      //真实姓名      String name=request.getParameter("name");      //密码      String passWord=request.getParameter("passWord");      //性别      String male=request.getParameter("sex");      //出生日期      String byear=request.getParameter("birthday");             //转化为日期       SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");        Date date =null;        User us=new User();        try {          date=new Date(sim.parse(byear).getTime());          us.setBirthday(date);        } catch (ParseException e1) {          // 抓取异常          e1.printStackTrace();        }      //手机      String mobile=request.getParameter("mobile");      //地址      String address=request.getParameter("address");      us.setId(Integer.parseInt(id));      us.setUserId(nameid);      us.setUserName(name);      us.setPassword(passWord);      us.setMale(male);      us.setMobile(mobile);      us.setAddress(address);      us.setStatus(1);      try {        boolean flag=impl.getAllToUpdate(us);        if (flag) {          //转到更新界面         request.getRequestDispatcher("/manage/manage-result.jsp").forward(request, response);        }else {          //重定向到用户管理界面在重新选择          response.sendRedirect("/EasyBuy_H/manage/user.jsp");        }      } catch (Exception e) {        // 异常抓取        e.printStackTrace();      }    }        //获取当前页数    int pageIndex=1;    String uindex=request.getParameter("pageIndex");    if (uindex!=null) {          pageIndex = Integer.parseInt(uindex);            }    //删除    if (opr.equals("del")) {      String userid=request.getParameter("id");      int uid=0;      if (userid!=null&&!(userid.equals(""))) {        uid=Integer.parseInt(userid);      }      boolean flag=impl.getAllToDelete(uid);      if (flag) {        //成功转发      request.getRequestDispatcher("/servlet/UpdateUserServlet?opr=list&pageIndex="+pageIndex).forward(request, response);        }else{        //失败转发        response.getWriter().print("<script type='text/javascript'>"            + "alert('删除失败');"            +"location.href='"+request.getContextPath() + "/servlet/UpdateUserServlet?opr=list&pageIndex="+pageIndex+"';"            + "</script>");       }    }      }}

     2.4 在jsp中通过作用域转发过来的数据

     2.4.1 用户管理的显示界面、删除界面

<div class="main">      <h2>用户管理</h2>      <div class="manage">        <table class="list">          <tr>            <th>用户名</th>            <th>真实姓名</th>            <th>性别</th>            <th>Email</th>            <th>手机</th>            <th>操作</th>          </tr>          <c:forEach items="${page.listu}" var="item">          <tr>            <td class="first w4 c">${item.userId}</td>            <td class="w1 c">${item.userName}</td>            <td class="w2 c">            <c:choose>            <c:when test="${item.male eq 'T'}">              男            </c:when>            <c:when test="${item.male eq 'F'}">              女            </c:when>            </c:choose>            </td>            <td>${item.email}</td>            <td class="w4 c">${item.mobile}</td>            <td class="w1 c"><a href="<%=path %>/servlet/UpdateUserServlet?opr=update&id=${item.id}">修改</a> <a id="manageDel" href="<%=path %>/servlet/UpdateUserInfoServlet?id=${item.id}&opr=del&pageIndex=${pageIndex}">删除</a></td>          </tr>          </c:forEach>        </table>      </div>    </div>    <div class="clear"></div>     <div class="pager">          <ul class="clearfix">                      <li><a href="<%=path%>/servlet/UpdateUserServlet?opr=list&pageIndex=1">首页</a></li>            <li class="current"><a href="<%=path%>/servlet/UpdateUserServlet?opr=list&pageIndex=${page.pageIndex-1}">上一页</a></li>            <li>${page.pageIndex}/${page.pageCount}</li>            <li class="current"><a href="<%=path%>/servlet/UpdateUserServlet?opr=list&pageIndex=${page.pageIndex+1}">下一页</a></li>            <li><a href="<%=path%>/servlet/UpdateUserServlet?opr=list&pageIndex=${page.pageCount}">尾页</a></li>          </ul>      </div>  </div>

 

     2.4.2 修改界面

<form action="<%=path %>/servlet/UpdateUserInfoServlet?opr=update&sid=${id}" method="post">        <c:forEach items="${listf}" var="item">          <table class="form">            <tr>              <td class="field">用户名(*):</td>              <td><input type="text" class="text" name="userName" value="${item.userId}" readonly="readonly" /></td>            </tr>            <tr>              <td class="field">真实姓名(*):</td>              <td><input type="text" class="text" name="name" value="${item.userName}" /></td>            </tr>            <tr>              <td class="field">登录密码(*):</td>              <td><input type="text" class="text" name="passWord" value="${item.password}" /></td>            </tr>            <tr>              <td class="field">确认密码(*):</td>              <td><input type="text" class="text" name="passWord" value="${item.password}" /></td>            </tr>            <tr>              <td class="field">性别(*):</td>              <td>              <c:choose>                <c:when test="${item.male eq 'T'}">                <input type="radio" name="sex" value="T" checked="checked" />男                <input type="radio" name="sex" value="F" />女                </c:when>                <c:otherwise>                <input type="radio" name="sex" value="T" />男                 <input type="radio" name="sex" value="F" checked="checked"/>女                </c:otherwise>              </c:choose>              </td>             </tr>            <tr>            <td class="field">出生日期:</td>            <td><input id="birthday" class="text" type="text" name="birthday" value="${item.birthday}"/><span></span></td>          </tr>            <tr>              <td class="field">手机(*):</td>              <td><input type="text" class="text" name="mobile" value="${item.mobile}" /></td>            </tr>            <tr>              <td class="field">地址(*):</td>              <td><input type="text" class="text" name="address" value="${item.address}" /></td>            </tr>                      <tr>              <td></td>              <td><label class="ui-blue"><input type="submit" name="submit" value="更新" /></label></td>            </tr>          </table>          </c:forEach>        </form>

    

       3. 商品分类

        3.1 用于显示

    //解决中文乱码问题    request.setCharacterEncoding("utf-8");    //查询商品分类的对象    ProoductCategoryDaoImpl_hyj impl=new ProoductCategoryDaoImpl_hyj();    ProductImpl_wjl dao=new ProductImpl_wjl();    String opr=request.getParameter("opr");    if (opr.equals("listinfo")) {      try {        //List<ProductCategory> listfrist=impl.getAllOneLeveInfo(0);        List<ProductCategory> listsecond=impl.getAllTowLeveInfo(0);        //request.setAttribute("levellist",listfrist);        request.setAttribute("levelslist",listsecond);        // 开始分页        // 实例化Page对象        Page_hyj page_hyj = new Page_hyj();        // .给定每页要显示几条数据        int pagesize=1;        page_hyj.setPageSize(pagesize);        // .给总页数赋值         int pageSum=0;        //总记录数        int total=dao.getAllCount();        if (total%pagesize==0) {          pageSum=total/pagesize;        }else {          pageSum=total/pagesize+1;        }        page_hyj.setPageCount(pageSum);        // 当用户还没有点击下一页是默认显示第一页数据        int pageIndex = 1;        // 获取下一页超链接设置的pageIndex的值        String uindex = request.getParameter("pageIndex");        if (uindex != null) {          // 给page类中的pageIndex赋值:(uindex不为空的时候就证明了用户点击了下一页,随之页面显示的数据也就改变了)          pageIndex = Integer.parseInt(uindex);        }        //判断是否符合显示条件        if (pageIndex<1) {          pageIndex=1;        }else if (pageIndex>page_hyj.getPageCount()) {          pageIndex=page_hyj.getPageCount();        }        //当前页数        page_hyj.setPageIndex(pageIndex);        // 给集合赋值        page_hyj.setListc(dao.getAllTowLeveInfo(page_hyj.getPageIndex(),page_hyj.getPageSize()));        // 设置作用域        request.setAttribute("pageIndex",pageIndex);        request.setAttribute("page", page_hyj);        request.getRequestDispatcher("/manage/productClass.jsp").forward(request,response);      } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();      }    }    //修改将数据加载到修改页面      if (opr.equals("update")) {        String id=request.getParameter("id");        String epcid=request.getParameter("epcid");        try {          List<ProductCategory> listfrist=impl.getAllOneLeveInfo(0);          request.setAttribute("levellist",listfrist);                request.setAttribute("rid",id);          List<ProductCategory> listsecond = impl.getAllTowLeveInfo(0);          request.setAttribute("levelslist",listsecond);          request.setAttribute("epcid",epcid);          request.getRequestDispatcher("/manage/productClass-modify.jsp").forward(request,response);        } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }            //新增二级分类      if (opr.equals("add")) {        try {          List<ProductCategory> listfrist=impl.getAllOneLeveInfo(0);          request.setAttribute("levellist",listfrist);                request.getRequestDispatcher("/manage/productClass-add.jsp").forward(request,response);        } catch (Exception e) {          // 错误异常          e.getMessage();        }      }

 

      3.2 返回list泛型的dao方法

  

public List<ProductCategory> getAllTowLeveInfo(int epcid)      throws Exception {    List<ProductCategory> list=new ArrayList<ProductCategory>();    String sql="";    ResultSet rs=null;    if(epcid==0){       sql+="select EPC_ID,EPC_NAME ,EPC_PARENT_ID from EASYBUY_PRODUCT_CATEGORY where EPC_ID!=EPC_PARENT_ID";      rs= executeSelect(sql);    }else{       sql+="select * from EASYBUY_PRODUCT_CATEGORY where EPC_ID=?";      Object[] paObjects={epcid};      rs= executeSelect(sql,paObjects);    }      if(rs!=null){        while(rs.next()){          ProductCategory pc=new ProductCategory();          pc.setId(rs.getInt("EPC_ID"));          pc.setName(rs.getString("EPC_NAME"));          pc.setParentId(rs.getInt("EPC_PARENT_ID"));          list.add(pc);        }      }      closeAll();      return list;  }

    

   3.3  执行具体的修改以及删除

public class ProductSonServlet extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    doPost(request, response);  }  /**   * 修改单个选中商品分类*/  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {        //解决中文乱码问题        request.setCharacterEncoding("utf-8");        response.setContentType("text/html; charset=utf-8");                //查询商品分类的对象        ProductImpl_wjl dao=new ProductImpl_wjl();        String opr=request.getParameter("opr");        //点击修改 将数据加载到商品分类中        if (opr.equals("updateName")) {          System.out.println(opr);        String name=request.getParameter("className"); //获取商品分类名称        String parentId=request.getParameter("parentId");//一级分类的选中数据        //二级分类        String sid=request.getParameter("sid");        int parentid=0;        if (parentId!=null&&(!parentId.equals(""))){          parentid=Integer.parseInt(parentId);         }       ProductCategory pro=new ProductCategory();       pro.setId(Integer.parseInt(sid));       pro.setName(name);       pro.setParentId(parentid);       boolean flag=dao.getProductToEpcid(pro);       if (flag) {        request.getRequestDispatcher("/manage/manage-result.jsp").forward(request,response);       }      }       //获取选中条的epcid         String id=request.getParameter("epcid");         int epcid=0;         if (id!=null&&(!id.equals(""))) {           epcid=Integer.parseInt(id);        }         //获取当前页数         int pageIndex=1;         String uindex=request.getParameter("pageIndex");         if (uindex != null) {           pageIndex = Integer.parseInt(uindex);          }        //删除子类        if (opr.equals("delete")) {          try {          int count=dao.getCountTwo(epcid);          String name=dao.twoName(epcid);          if (count<1) {            boolean flag=dao.delProductToEpcid(epcid);             if (flag) {               request.getRequestDispatcher("/servlet/ProductServletInfo_wjl?opr=listinfo&pageIndex="+pageIndex).forward(request,response);            }          }else{            response.getWriter().print("<script type='text/javascript'>"                + "alert('当前"+name+"二级分类下还有商品,暂时不能删除该类');"                +"location.href='"+request.getContextPath() + "/servlet/ProductServletInfo_wjl?opr=listinfo&pageIndex="+pageIndex+"';"                + "</script>");             }                  } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }                 }       //点击删除父类       if (opr.equals("del")) {         try {          int count=dao.getHaveSons(epcid);          String name=dao.parentName(epcid);          if (count>1) {            System.out.println(name);                      response.getWriter().print("<script type='text/javascript'>"                + "alert('当前"+name+"分类下还有子类');"                +"location.href='"+request.getContextPath() + "/servlet/ProductServletInfo_wjl?opr=listinfo&pageIndex="+pageIndex+"';"                + "</script>");             }else{            boolean flag=dao.delAllProduct(epcid);             if (flag) {               request.getRequestDispatcher("/servlet/ProductServletInfo_wjl?opr=listinfo&pageIndex="+pageIndex).forward(request,response);            }          }        } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }               }             //新增二级分类       if (opr.equals("addinfo")) {        String parentId=request.getParameter("parentId");        String className=request.getParameter("className");        //一级分类id        int pid=0;        //二级分类id        int sid=0;        try {           if (parentId!=null&&(!parentId.equals(""))) {             pid=Integer.parseInt(parentId);          }           ProductCategory pro=new ProductCategory();            pro.setName(className);            pro.setParentId(pid);            boolean flag=dao.addOneClass(pro);            if (pid==0) {              System.out.println("新增一级分类");              List<ProductCategory> list=dao.getAllTowLeveInfo();              for (ProductCategory item : list) {                sid=item.getId();              }              pro.setId(sid);              flag=dao.addParentClass(pro);             }           if (flag) {            request.getRequestDispatcher("/manage/manage-result.jsp").forward(request,response);           }                  } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }  }}

 

      3.4  jsp界面转发回来

      3.4.1 显示、删除的jsp

<div class="main">      <h2>分类管理</h2>      <div class="manage">        <table class="list">          <tr>            <th>编号</th>            <th>分类名称</th>            <th>操作</th>          </tr>          <c:forEach items="${page.listc}" var="item">          <tr>            <td class="first w4 c">${item.id}</td>            <td>${item.name}</td>            <td class="w1 c"><a href="<%=path %>/servlet/ProductServletInfo_wjl?opr=update&&id=${item.id}&epcid=${item.id}">修改</a>             <a class="manageDel" href="<%=path %>/servlet/ProductSonServlet?opr=del&epcid=${item.parentId}&pageIndex=${pageIndex}">删除</a></td>          </tr>          <c:forEach items="${levelslist}" var="itemSon">          <c:choose>        <c:when test="${item.parentId eq itemSon.parentId }">        <tr>            <td class="first w4 c">${itemSon.id}</td>            <td class="childClass">${itemSon.name}</td>            <td class="w1 c"><a href="<%=path %>/servlet/ProductServletInfo_wjl?opr=update&id=${itemSon.parentId}&epcid=${itemSon.id}">修改</a>             <a class="manageDel" href="<%=path %>/servlet/ProductSonServlet?opr=delete&epcid=${itemSon.id}&pageIndex=${pageIndex}">删除</a></td>          </tr>        </c:when>          </c:choose>          </c:forEach>          </c:forEach>        </table>      </div>      <div></div>    </div>    <div class="clear"></div>    <div class="pager">          <ul class="clearfix">                       <li><a href="<%=path%>/servlet/ProductServletInfo_wjl?opr=listinfo&&pageIndex=1">首页</a></li>            <li><a href="<%=path%>/servlet/ProductServletInfo_wjl?opr=listinfo&&pageIndex=${page.pageIndex-1}">上一页</a></li>             <li>${page.pageIndex}/${page.pageCount}</li>            <li><a href="<%=path%>/servlet/ProductServletInfo_wjl?opr=listinfo&&pageIndex=${page.pageIndex+1}">下一页</a></li>            <li><a href="<%=path%>/servlet/ProductServletInfo_wjl?opr=listinfo&&pageIndex=${page.pageCount}">尾页</a></li>          </ul>      </div>  </div>

 

     3.4.2 执行修改

<div class="main">      <h2>修改分类</h2>      <div class="manage">        <form action="<%=path %>/servlet/ProductSonServlet?opr=updateName&sid=${epcid}" method="post">          <table class="form">            <tr>              <td class="field">父分类:</td>                <td>                <select name="parentId">                <c:forEach items="${levellist}" var="item">                  <c:if test="${item.id eq rid}">                  <option value="${item.id}" selected="selected">${item.name}</option>                  </c:if>                  <c:if test="${item.id != rid}">                  <option value="${item.id}">${item.name}</option>                  </c:if>                </c:forEach>                </select>              </td>            </tr>            <tr>            <td class="field">分类名称:</td>              <c:forEach items="${levellist}" var="item">              <c:if test="${item.id eq epcid}">              <td><input type="text" class="text" name="className" value="${item.name}" /></td>               </c:if>              </c:forEach>              <c:forEach items="${levelslist}" var="items">              <c:if test="${items.parentId eq rid}">              <c:if test="${items.id eq epcid}">              <td><input type="text" class="text" name="className" value="${items.name}" /></td>              </c:if>              </c:if>            </c:forEach>            </tr>            <tr>              <td></td>              <td><label class="ui-blue"><input type="submit" name="submit" value="更新" /></label></td>            </tr>          </table>        </form>      </div>    </div>    <div class="clear"></div>  </div>

   3.4.3 执行新增的jsp界面

 

<div class="main">      <h2>添加分类</h2>      <div class="manage">        <form action="<%=path %>/servlet/ProductSonServlet?opr=addinfo" method="post">          <table class="form">            <tr>              <td class="field">父分类:</td>              <td>                <select name="parentId">                <option value="0" selected="selected">根栏目</option>                  <c:forEach items="${levellist}" var="item">                                  <option value="${item.parentId}">${item.name}</option>                </c:forEach>                </select>              </td>            </tr>            <tr>              <td class="field">分类名称:</td>              <td><input type="text" class="text" name="className" value="" /></td>            </tr>            <tr>              <td></td>              <td><label class="ui-blue"><input type="submit" name="submit" value="新增" /></label></td>            </tr>          </table>        </form>      </div>    </div>    <div class="clear"></div>  </div>

   好了,功能暂时就这么多了,如有不足之处,请多多提出你的建议,谢谢。