易买网的一些增删改查,增删改

by admin on 2019年9月12日

在上一部分简单的了解了一下资源PHAsset、相册PHAssetCollection、相册文件夹PHCollectionList,顺便简单的了解了一下通过PHPhotoLibrary判断和请求访问权限,这一部分将在上一部分的基础上进一步学习和了解其他的内容。

易买网的一些增删改查,增删改

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

     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%20%>/servlet/UpdateUserServlet?opr=update&id=${item.id}">修改</a> <a id="manageDel" href="<%=path%20%>/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}"/></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%20%>/servlet/ProductServletInfo_wjl?opr=update&&id=${item.id}&epcid=${item.id}">修改</a>
                         <a class="manageDel" href="<%=path%20%>/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%20%>/servlet/ProductServletInfo_wjl?opr=update&id=${itemSon.parentId}&epcid=${itemSon.id}">修改</a> 
                        <a class="manageDel" href="<%=path%20%>/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>

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

      

    

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

JDBC案例
今日内容介绍
案例:删除选中商品
案例:条件查询
案例:分页查询

,,,

  1. 创建元素
    以tagName创建一个新的元素

var div1 = document.createElement('div')
  1. 在某个节点前插入一个子节点

var insertElement = node.insertBefore(newElement, referenceElement)

其实,如果从分类上来说,上一部分的内容主要是解决了数据的访问问题,有了数据,就可以开始增删改查等一系列操作了。对于单个资源的操作主要有三种:

 

@interface ViewController
()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (nonatomic,strong) NSMutableArray *array;
@property (nonatomic,strong) UITableView *tableViews;
@property (nonatomic,strong) UIAlertView *alert;
@end

  1. 删除一个子节点child,返回被删除的节点

var oldChild = node.removeChild(child)
typedef NS_ENUM(NSInteger, PHAssetEditOperation) { PHAssetEditOperationDelete = 1, // 删除 PHAssetEditOperationContent = 2, // 修改内容 PHAssetEditOperationProperties = 3, //修改属性} 

今日内容学习目标
删除选中商品
条件查询
分页查询

@implementation ViewController

  1. 用指定的节点替换某个节点,返回被替换掉的节点

var replaceChild = node.replaceChild(newChild, oldChild)

在该类的刚开始的地方,有一句绿色英文,如下:

第1章案例:删除选中商品

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a
    nib.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.tableViews];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem
    alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
    target:self action:@selector(edit)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem
    alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
    target:self action:@selector(add)];
    }

  • (void)edit{
    if (self.tableViews.isEditing == NO) {
    self.tableViews.editing = YES;
    }else if (self.tableViews.isEditing == YES){
    self.tableViews.editing = NO;
    }
    }

  • (void)alertView:(UIAlertView *)alertView
    clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
    UITextField *tf = [self.alert textFieldAtIndex:0];
    [self.array addObject:tf.text];
    [self.tableViews reloadData];
    }
    }

  • (void)add{
    self.alert = [[UIAlertView alloc]initWithTitle:@”提示框”
    message:@”输入您的姓名” delegate:self cancelButtonTitle:@”取消”
    otherButtonTitles:@”确认”, nil];
    self.alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [self.alert show];
    }

  • (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
    }

  • (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    forRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.array removeObject:self.array[indexPath.row]];
    [self.tableViews reloadData];
    }

  • (UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *tableIdentfier = @”table”;
    UITableViewCell *cell = [tableView
    dequeueReusableCellWithIdentifier:tableIdentfier];
    if (!cell) {
    cell = [[UITableViewCell
    alloc]initWithStyle:UITableViewCellStyleDefault
    reuseIdentifier:tableIdentfier];
    }
    cell.textLabel.text = self.array[indexPath.row];
    return cell;
    }

  • (NSMutableArray *)array{
    if (!_array) {
    _array = [[NSMutableArray
    alloc]initWithObjects:@”张三”,@”李四”,@”王五”, nil];
    }
    return _array;
    }

  • (UITableView *)tableViews{
    if (!_tableViews) {
    _tableViews = [[UITableView alloc]initWithFrame:self.view.bounds
    style:UITableViewStylePlain];
    [_tableViews setDelegate:self];
    [_tableViews setDataSource:self];
    }
    return _tableViews;
    }
    ,,,

  1. 判断当前节点是否包含子节点,返回一个布尔值

element.haschildNodes()
  1. 查找第一个名为xxx的元素

类名为'xxx'
var class1 = document.querySelector('.xxx')
id名为'xxx'
var id1 = document.querySelector('#xxx')
xxx属性
var a = document.querySelector([xxx])
  1. 查找所有名为xxx的元素

类名为'xxx'
var class1 = document.querySelectorAll('.xxx')
id名为'xxx'
var id1 = document.querySelectorAll('#xxx')
xxx属性
var a = document.querySelectorAll([xxx])

// PHAssetChangeRequest can only be created or used within a
-[PHPhotoLibrary performChanges:] or -[PHPhotoLibrary
performChangesAndWait:] block.

1.1案例分析

这句话是说,该类只能在[PHPhotoLibrary performChanges:] 或者
-[PHPhotoLibrary
performChangesAndWait:]中使用。该类用来创建一个请求,用来给相册添加、删除或者编辑asset。

1.2案例实现
步骤1:修改jsp,完善checkbox,name为pid,value为商品id

  • 创建和添加图片和视频

<input type=”checkbox” name=”pid” value=”${product.pid}” />
步骤2:编写js代码,获得所有的pid
添加id属性:<a id=”deleteAllId”
href=”javascript:void(0)”>删除选中</a>
<script type=”text/javascript”>
$(function(){
//绑定点击事件
$(“#deleteAllId”).click(function(){
//所有选中的checkbox
var all = $(“input[name=’pid’]:checked”);
if(all.length == 0){
alert(“请选择需要上传的商品”);
return false;
}
//
if(window.confirm(“您确定要删除所选”+all.length+”个商品吗?”)){
//获得所有的id串
//注:serialize()为jquery的方法 将元素序列化成 id=xx&id=yy的格式
var ids = all.serialize();
location.href=”${pageContext.request.contextPath}/productDeleteServlet?”

  • ids;
    } else {
    $(“input[name=’pid’]”).removeProp(“checked”);
    }
    });
    });
    </script>
+ (instancetype)creationRequestForAssetFromImage:(UIImage *)image;+ (nullable instancetype)creationRequestForAssetFromImageAtFileURL:fileURL;+ (nullable instancetype)creationRequestForAssetFromVideoAtFileURL:fileURL;

步骤3:编写servlet
public class ProductDeleteAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

这里有三个创建和添加方法,通俗易懂,不再做更多的说明了。

public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//1 获得所有的id
String[] pids = request.getParameterValues(“pid”);
//2 删除
ProductService productService = new ProductService();
productService.deleteAll(pids);

- toCreateAndAndAsset:sender {// [identifierArr removeAllObjects]; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ NSLog(@"ggggggggg"); PHAssetChangeRequest * request = [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageNamed:@"girl.jpg"]]; if (request.placeholderForCreatedAsset.localIdentifier) { [identifierArr addObject:request.placeholderForCreatedAsset.localIdentifier]; } } completionHandler:^(BOOL success, NSError * _Nullable error) { NSLog(@"ffffffff"); if  { NSLog; } else { NSLog; } }];// NSLog(@"hhhhhhh");// BOOL isSuccess = [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{// [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageNamed:@"girl.jpg"]];// } error:nil];// if (isSuccess) {// NSLog;// } else {// NSLog;// }// NSLog(@"iiiiiiii");}

//3重定向查询所有
response.sendRedirect(request.getContextPath() +
“/productFindAllServlet”);
}

除此之外,PHAssetChangeRequest还有个子类PHAssetCreationRequest也可以用来添加,该子类丰富了父类的可添加方式。举个例子就好:

步骤4:编写service
/**
* 删除所有
* @param pids
*/
public void deleteAll(String… pids) {
productDao.delete(pids);
}

- toUseAssetCreationRequestAdd:sender { BOOL isSupport = [PHAssetCreationRequest supportsAssetResourceTypes:@[@(PHAssetResourceTypeFullSizePhoto)]]; // 不支持 if (isSupport) { NSLog; } NSURL * url1 = [[NSBundle mainBundle] URLForResource:@"girl" withExtension:@"jpg"];// NSURL * url2 = [[NSBundle mainBundle] URLForResource:@"code" withExtension:@"png"]; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetCreationRequest * request = [PHAssetCreationRequest creationRequestForAsset]; request.favorite = YES; [request addResourceWithType:PHAssetResourceTypePhoto fileURL:url1 options:nil]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if  { NSLog; } else { NSLog; } }];}

步骤5:编写dao
/**
* 删除所有
* @param pids
*/
public void deleteAll(String… pids) {
try {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//删除sql语句
String sql = “delete from product where pid = ?”;
//将所有的pid拼凑一个二维数组,列表示id,行表示个数
Object[][] params = new Object[pids.length][];
for (int i = 0; i < pids.length; i++) {
params[i] = new Object[]{pids[i]};
}
queryRunner.batch(sql, params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

这里需要注意的是,经过检查发现,这里支持的ResourceType类型只有PHAssetResourceTypePhoto和PHAssetResourceTypeVideo。

第2章案例:分页查询
2.1案例介绍
实际开发中,条件查询时非常常见的一种功能,上一个案例中我们已经完成。接着我们再来学习另一种也非常常见的功能:分页查询。

  • 删除图片和视频调用方法+ deleteAssets:(id<NSFastEnumeration>)assets;删除,这里的参数是包含PHAsset对象的遵循NSFastEnumeration协议的对象。除此之外,更安全的操作是应先使用PHAsset的方法- canPerformEditOperation:(PHAssetEditOperation)editOperation;判断一下该资源是否可以被删除。

2.2相关知识:sql分页
格式:select * from 表 limit ?,?;
参数1:开始索引 startIndex ,默认值:0。必须是正数。
参数2:每页显示个数 pageSize
例如:
select * from products limit 0,5; #第一页,每页显示5条。
select * from products limit 5,5; #第二页,每页显示5条。
select * from products limit 10,5; #第三页,每页显示5条。
select * from products limit ?,5; #第pageNumber页,每页显示5条。
startIndex = (pageNumber – 1) * pageSize;

2.3案例分析

- toDeleteAsset:sender { if (identifierArr.count == 0) { UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有要删除的目标,请先添加资源!" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alertVC addAction:okAction]; [self presentViewController:alertVC animated:YES completion:nil]; return; } [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 查找set PHFetchResult<PHAsset *> * result = [PHAsset fetchAssetsWithLocalIdentifiers:identifierArr options:nil]; [PHAssetChangeRequest deleteAssets:result]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if  { NSLog; } else { NSLog(@"删除失败:%@", error); } }];}

2.4案例实现
步骤1:编写PageBean,提供构造方法,统一算法的编写。

这里的删除是可交互式的,如下图所示:图片 1image.png

public class PageBean<T> {
private int pageNumber; //当前页(浏览器传递)
private int pageSize; //每页显示个数(固定值,也可以是浏览器传递)
private int totalRecord; //总记录数(数据库查询)
private int totalPage; //总分页数
private int startIndex; //开始索引
private List<T> data; //分页数据(数据库查询)

  • 更新图片和视频属性名义上是更新,但是也只能更新四个内容:创建日期、拍照地点、是否收藏、是否隐藏。同样的,在做这些属性修改之前,应先做一次判断最为合适。这里以修改是否已收藏属性为例。

/**
* 为了约束使用者,必须传递两个参数,不提供无参构造
* @param pageNumber
* @param pageSize
*/
public PageBean(int pageNumber, int pageSize) {
super();
this.pageNumber = pageNumber;
this.pageSize = pageSize;

}
public int getStartIndex() {
//开始索引计算
startIndex = (pageNumber – 1) * pageSize;
return startIndex;
}
public int getTotalPage() {
//总页数计算
if(totalRecord % pageSize == 0){
//整除
totalPage = totalRecord / pageSize ;
} else {
//有余数 + 1 (半页)
totalPage = totalRecord / pageSize + 1;
}

- toModifyAsset:sender { if (identifierArr.count == 0) { UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有要更新的目标,请先添加资源!" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alertVC addAction:okAction]; [self presentViewController:alertVC animated:YES completion:nil]; return; } [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHFetchResult<PHAsset *> * fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:identifierArr options:nil]; if (fetchResult.count > 0) { PHAsset * firstAsset = fetchResult.firstObject; PHAssetChangeRequest * changeRequest = [PHAssetChangeRequest changeRequestForAsset:firstAsset]; changeRequest.favorite = YES; } } completionHandler:^(BOOL success, NSError * _Nullable error) { if  { NSLog; } else { NSLog; } }];}

return totalPage;
}
//其他getter和setter方法省略

  • 编辑图片和视频的内容通过类方法+ (instancetype)changeRequestForAsset:(PHAsset *)asset;获取到PHAssetChangeRequest对象,然后修改其中的属性contentEditingOutput即可,当想恢复原来的样子的时候,调用方法- revertAssetContentToOriginal;即可。在操作修改内容之前,还是有必要先检查一下是否可以修改内容。对于编辑的相关步骤如下:图片 2image.png简单来说就四步:1、查找到资源PHAsset2、调用方法去获取PHContentEditingInput对象3、通过申请你要对asset做的修改4、初始化PHContentEditingOutput对象或者PHLivePhotoEditingContext对象5、使用PHPhotoLibrary的block,在该block中创建PHAssetChangeRequest对象,并把上面的PHContentEditingOutput对象赋值给PHAssetChangeRequest对象的contentEditingOutput属性具体的代码如下:

步骤2:确定入口

步骤3:编写servlet,获得参数
public class ProductFindAllServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//1 获得分页参数
String pageNumberStr = request.getParameter(“pageNumber”);
Integer pageNumber = 1 ;//处理没有传递参数的情况
try {
pageNumber = Integer.parseInt(pageNumberStr);
} catch (Exception e) {
}
Integer pageSize = 2;
//固定值,Integer.parseInt(request.getParameter(“pageSize”));

- toEditAssetContent:sender { // 1、根据identifier查找到asset PHFetchResult<PHAsset *> * fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:identifierArr options:nil]; if (fetchResult.count > 0) { PHAsset * firstAsset = fetchResult.firstObject; if ([firstAsset canPerformEditOperation:PHAssetEditOperationContent]) { NSLog; } // 2、获取PHContentEditingInput对象 PHContentEditingInputRequestOptions * requestOptions = [[PHContentEditingInputRequestOptions alloc] init]; // 该方法只有在已经存在PHAdjustmentData的情况下才会被调用 requestOptions.canHandleAdjustmentData = ^BOOL(PHAdjustmentData * _Nonnull adjustmentData) { NSLog(@"formatIdentifier:%@,formatVersion:%@", adjustmentData.formatIdentifier, adjustmentData.formatVersion); return YES; };// PHContentEditingInputRequestID requestId = [firstAsset requestContentEditingInputWithOptions:requestOptions completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) { // 3、创建PHAdjustmentdata,可以在data参数里设置要做的操作,比如过滤等,可以是一个序列串,但是这里的长度是有限制的 PHAdjustmentData * adjustData = [[PHAdjustmentData alloc] initWithFormatIdentifier:firstAsset.localIdentifier formatVersion:@"1.0" data:[@"ceshi" dataUsingEncoding:NSUTF8StringEncoding]]; // 4、初始化PHContentEditingOutput对象 PHContentEditingOutput * output = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput]; output.adjustmentData = adjustData; // 通过PHContentEditingInput可以获取到想要的信息,处理图片:修改图片整体颜色 NSURL * imageUrl = [contentEditingInput fullSizeImageURL]; // 包含图片数据的文件 NSData * originalImageData = [NSData dataWithContentsOfURL:imageUrl]; UIImage * originalImage = [UIImage imageWithData:originalImageData]; CGImageRef imageRef = originalImage.CGImage; size_t width = CGImageGetWidth; size_t height = CGImageGetHeight; size_t bitsPerComponent = CGImageGetBitsPerComponent; size_t bytesPerRow = CGImageGetBytesPerRow; uint32_t bitmapInfo = CGImageGetBitmapInfo; CGColorSpaceRef space = CGImageGetColorSpace; //获取每个像素的字节数据集合 CGDataProviderRef dataProviderRef = CGImageGetDataProvider; CFDataRef dataRef = CGDataProviderCopyData(dataProviderRef); CFMutableDataRef mutableDataRef = CFDataCreateMutableCopy(kCFAllocatorDefault, 0, dataRef); // const UInt8 * constBytesPtr = CFDataGetBytePtr; UInt8 * bytesPtr = CFDataGetMutableBytePtr(mutableDataRef); NSUInteger length = CFDataGetLength(mutableDataRef); // 一个像素由四个字节byte组成 for (int i = 0; i < length; i += 4) { UInt8 red = bytesPtr[I]; UInt8 green = bytesPtr[i + 1]; UInt8 blue = bytesPtr[i + 2]; UInt8 average = (red + green + blue) / 3; bytesPtr[i] = average; bytesPtr[i + 1] = average; bytesPtr[i + 2] = average; } CGContextRef imageContextRef = CGBitmapContextCreate(bytesPtr, width, height, bitsPerComponent, bytesPerRow, space, bitmapInfo); CGImageRef finalImageRef = CGBitmapContextCreateImage(imageContextRef); UIImage * finalImage = [UIImage imageWithCGImage:finalImageRef]; _finalImageView.image = finalImage; // ⚠️这里为什么一定要用UIImageJPEGRepresentation才能成功,而UIImagePNGRepresentation会失败,生成的数据是正确的,但是相册相应的资源无法更新??? // 因为这个和renderedContentURL有关,图片的输出只能是JPEG格式,video只能是.mov格式输出 // 对于Live Photo,调用saveLivePhotoToOutput:options:completionHandler:方法保存和更新 BOOL isSuccess = [UIImageJPEGRepresentation(finalImage, 1) writeToURL:output.renderedContentURL atomically:NO]; if (isSuccess) { NSLog; } else { NSLog; } CGImageRelease(finalImageRef); CGContextRelease(imageContextRef); CFRelease(mutableDataRef); CFRelease; // 5、赋值更新 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 使用PHAssetChangeRequest PHAssetChangeRequest * changeRequest = [PHAssetChangeRequest changeRequestForAsset: firstAsset]; changeRequest.contentEditingOutput = output; } completionHandler:^(BOOL success, NSError * _Nullable error) { if  { NSLog(@"编辑内容成功"); } else { NSLog(@"编辑内容失败:%@", error); } }]; }]; }}

//2 通知service,查询所有商品
ProductService productService = new ProductService();
PageBean<Product> pageBean =
productService.findAll(pageNumber,pageSize);

结果如下:

//3 选择jsp
//3.1 将查询结果存放在request作用域
request.setAttribute(“pageBean”, pageBean);
//3.2 请求转发
request.getRequestDispatcher(“/admin/product/product_list.jsp”)
.forward(request, response);
}

图片 3image.png

步骤4:编写service,进行分页查询,将所有的数据封装到PageBean中。
/**
* 查询所有,分页
* @return
*/
public PageBean<Product> findAll(int pageNumber , int pageSize){
//1 总分页数、开始索引,已经在PageBean中处理了
PageBean<Product> pageBean = new
PageBean<Product>(pageNumber, pageSize);

这一过程涉及到了很多前面没有提到的类,分别如下:

//2 查询总记录数
int totalRecord = productDao.getTotalRecord();
//将总记录数封装到pageBean中
pageBean.setTotalRecord(totalRecord );

  • PHAdjustmentData该类的初始化使用如下方式:- (instancetype)initWithFormatIdentifier:(NSString *)formatIdentifier formatVersion:(NSString *)formatVersion data:data;,这三个参数分别对应三个只读属性,从其命名可以看出在这里面记录了每次修改的信息。尤其是data,这里记录了该次的操作,比如设置了滤镜等等。
  • PHContentEditingInputRequestOptions该option主要用来判断从哪个版本操作,比较有用的是下面的方法:

//3 查询分页数据
List<Product> data =
productDao.findAll(pageBean.getStartIndex(),pageBean.getPageSize());
// * 将分页数据封装到PageBean中
pageBean.setData(data);

//4 返回封装好的数据
return pageBean;
}

@property (nonatomic, copy) BOOL (^canHandleAdjustmentData)(PHAdjustmentData *adjustmentData);

步骤5:编写dao,查询总记录数和分页数据
/**
* 查询总记录数
* @return
*/
public int getTotalRecord() {
try {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = “select count(*) from product”;
Object[] params = {};
Long numLong = (Long) queryRunner.query(sql, new ScalarHandler(),
params);
return numLong.intValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

这是一个带返回值的block,如果该block返回YES,那么接下来操作的资源是原来的纯净的资源的最后一次操作,否则,会选择最原始的资源即没有进行过操作的做操作。这一切都取决于PHAdjustmentData。

/**
* 分页查询所有
* @return
*/
public List<Product> findAll(int startIndex, int pageSize) {
try {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = “select * from product limit ?,?”;
Object[] params = {startIndex ,pageSize};
return queryRunner.query(sql, new
BeanListHandler<Product>(Product.class), params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

  • PHContentEditingInput当前要操作的资源,这里记录了图片、视频和Live
    Photo的一些操作的必须信息,比如图片的地址属性fullSizeImageURL,通用属性创建时间creationDate等等。主要是用来获取资源的一些比较隐秘的信息的。
  • PHContentEditingOutput最后的要更新的信息都在这个类里了,该类的初始化需要依靠PHContentEditingInput对象,其中的adjustmentData用来标记这次的操作;而属性renderedContentURL是获取进行资源存储地址用的,对于图片和视频是必须调用这一步去存储资源到零时文件中的,而对于Live
    Photo,需要调用saveLivePhotoToOutput:options:completionHandler:去存储。需要注意的是,使用renderedContentURL方法,会将所有的图片都存储为jpeg格式的,所以需要使用UIImageJPEGRepresentation(finalImage,
    1)方法来写入;会将所有的视频修改为.mov格式。

步骤6:修改jsp页面,显示分页数据
位置:/day14_page/WebContent/admin/product/product_list.jsp

另外,在该方法中,还使用了一些额外的框架,来操作图片的每个点,获取每个像素的数据,生成图片等。

步骤7:显示分页信息

  • 一键清除操作这个很简单,只要我有了PHAsset,然后就可以通过PHAssetChangeRequest来调用方法revertAssetContentToOriginal清除即可。

第${ pageBean.pageNumber }/${ pageBean.totalPage }页  
总记录数:${pageBean.totalRecord } 每页显示:${ pageBean.pageSize
}  
<c:if test=”${ pageBean.pageNumber gt 1 }”>
<a href=”${ pageContext.request.contextPath
}/productListPageServlet?pageNumber=1″>[首页]</a> |  
<a href=”${ pageContext.request.contextPath
}/productListPageServlet?pageNumber=${pageBean.pageNumber-1}”>[上一页]</a>| 
</c:if>
 
<c:forEach var=”i” begin=”1″ end=”${pageBean.totalPage }”>
<c:if test=”${ pageBean.pageNumber == i }”>
${ i }
</c:if>
<c:if test=”${ pageBean.pageNumber != i }”>
<a href=”${ pageContext.request.contextPath
}/productListPageServlet?pageNumber=${ i}”>${ i }</a>
</c:if>
</c:forEach>
 
<c:if test=”${ pageBean.pageNumber lt pageBean.totalPage }”>
<a href=”${ pageContext.request.contextPath
}/productListPageServlet?pageNumber=${pageBean.pageNumber+1}”>[下一页]</a>| 
<a href=”${ pageContext.request.contextPath
}/productListPageServlet?pageNumber=${pageBean.totalPage}”>[尾页]</a>
</c:if>

第3章案例:条件查询
3.1案例介绍
我们已经完成了“查询所有商品”功能,如果我们希望从所有数据中筛选出需要的部分数据,会发现通过肉眼比较困难,且没有必要。在开发中,我们采用“条件查询”来解决此类问题。

- toResetAsset:sender { PHFetchResult<PHAsset *> * result = [PHAsset fetchAssetsWithLocalIdentifiers:@[@"421C93B7-E05A-41FF-9983-02C1B8B41902/L0/001"] options:nil]; if (result.count == 0) { return; } PHAsset * firstAsset = result.firstObject; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetChangeRequest * request = [PHAssetChangeRequest changeRequestForAsset:firstAsset]; [request revertAssetContentToOriginal]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if  { NSLog; } else { NSLog; } }];}

3.2案例分析
“条件查询”和“查询所有”,两个功能非常相似,不同出就在条件的筛选上,通过页面将分类和商品名称传递给服务器,服务器获得查询条件,然后通知service拼凑sql语句进行具体查询。
我们发现如果要完成“条件查询”,必须在之前的“查询所有”时,查询所有的分类,从而可以进行条件的选择。

上面提到的增删改查都是从资源自身层面上去处理的,后面会发现在相册等层面也可以做这些处理,具体的下一节再写。

3.3案例实现
步骤2:确定JavaBean,在商品Product对象中,使用的“category_id”字段存放分类id。

至此,关于单个资源的增删改查基本完毕,后面碰到这里漏了的再做补充!

步骤2:修改Servlet,查询所有时,查询所有分类(条件查询使用)
修改:/day14_condition/src/cn/itcast/web/servlet/ProductFindAllServlet.java

public class ProductFindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//1

//2.1 通知service,查询所有商品
ProductService productService = new ProductService();
List<Product> allProduct = productService.findAll();
//2.2 通过分类service,查询所有分类
CategoryService categoryService = new CategoryService();
List<Category> allCategory = categoryService.findAll();

//3 选择jsp
//3.1 将查询结果,所有商品,存放在request作用域
request.setAttribute(“allProduct”, allProduct);
//3.2 将查询结果,所有分类,存放在request作用域
request.setAttribute(“allCategory”, allCategory);
//3.3 请求转发
request.getRequestDispatcher(“/admin/product/product_list.jsp”)
.forward(request, response);

}

步骤3:修改product.jsp,显示所有分类
修改:/day14_condition/WebContent/admin/product/product_list.jsp

<c:forEach items=”${allCategory}” var=”category”>
<option value=”${category.cid}”>${category.cname}</option>
</c:forEach>

步骤4:修改product.jsp,完善表单。概览如下:
<form
action=”${pageContext.request.contextPath}/productFindAllServlet”
method=”post”>
分类 <select name=”category_id” class=”form-control”>
商品名称:<input type=”text” name=”pname” size=”15″
class=”form-control”/>
<button type=”submit” value=”查询”
class=”button_view”>查询</button>

步骤5:完善servlet,获得查询条件,并封装到javabean,然后传递给service
位置:/day14_condition/src/cn/itcast/web/servlet/ProductFindAllServlet.java

此时ProductService的findAll(product) 不存在所以抛异常。
public class ProductFindAllServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//1 获得请求参数
Product product = MyBeanUtils.populate(Product.class,
request.getParameterMap());

//2.1 通知service,查询所有商品
ProductService productService = new ProductService();
List<Product> allProduct = productService.findAll(product);
//2.2 …省略
步骤6:完善service,接收条件,并拼凑sql查询条件。
/**
* 查询所有(含条件)
* @return
*/
public List<Product> findAll(Product product) throws SQLException
{
return productDao.findAll(product);
}

步骤7:完善dao,使用条件和参数

/**
* 查询所有
* @return
*/
public List<Product> findAll(Product product) throws SQLException
{
//1.1 拼凑sql语句,格式:and 属性 符号 ?
StringBuilder builder = new StringBuilder();
//1.2 拼凑实际参数。实际参数可重复、参数需要顺序,所以选择List集合
List<Object> paramsList = new ArrayList<Object>();

//2.1 分类不为空 ,添加分类条件
if(product.getCategory_id() != null &&
!””.equals(product.getCategory_id())){
builder.append(” and category_id = ? “);
paramsList.add(product.getCategory_id());
}

//2.2 商品名不为空,添加商品名条件
if(product.getPname() != null && !””.equals(product.getPname())){
builder.append(” and pname like ? “);
//商品名需要模糊查询即可,需要手动的添加%
paramsList.add(“%”+product.getPname()+”%”);
}

//3 转换成需要的类型
String condition = builder.toString();
Object[] params = paramsList.toArray();

QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = “select * from product where 1=1 ” + condition;
return queryRunner.query(sql, new
BeanListHandler<Product>(Product.class), params);
}

3.4查询条件回显

步骤1:修改servlet,将封装好的查询条件,添加到request作用域
/day14_condition/src/cn/itcast/web/servlet/ProductFindAllServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//1 获得请求参数
Product product = MyBeanUtils.populate(Product.class,
request.getParameterMap());

//2.1 通知service,查询所有商品
ProductService productService = new ProductService();
List<Product> allProduct = productService.findAll(product);
//2.2 通过分类service,查询所有分类
CategoryService categoryService = new CategoryService();
List<Category> allCategory = categoryService.findAll();

//3 选择jsp
//3.1 将查询结果,所有商品,存放在request作用域
request.setAttribute(“allProduct”, allProduct);
//3.2 将查询结果,所有分类,存放在request作用域
request.setAttribute(“allCategory”, allCategory);
//3.3 存放条件
request.setAttribute(“product”, product);
//3.4 请求转发
request.getRequestDispatcher(“/admin/product/product_list.jsp”).forward(request,
response);

}

步骤2:使用“条件product”进行标签回显
/day14_condition/WebContent/admin/product/product_list.jsp
分类
<c:forEach items=”${allCategory}” var=”category”>
<option value=”${category.cid}”
${product.category_id == category.cid ? “selected=’selected'” : “”}
>
${category.cname}
</option>
</c:forEach>
商品名称:
<input type=”text” name=”pname” size=”15″ value=”${product.pname}”
class=”form-control”/>

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图