程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 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',
        //'[email protected]','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>

   好了,功能暫時就這麼多了,如有不足之處,請多多提出你的建議,謝謝。

      

    

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved