首页 > 易买网的一些增删改查

易买网的一些增删改查

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

     1.注册

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

 

     需要发送到下面这个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 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 getAllUser(int pageIndex,int pageSize) throws Exception {List list=new ArrayList();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 getAllUserToUserId(int id) throws Exception {List list=new ArrayList();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 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(""); }}}}

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

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

class="main">

用户管理

class="manage">class="list">"${page.listu}" var="item">
用户名真实姓名性别Email手机操作
class="first w4 c">${item.userId}class="w1 c">${item.userName}class="w2 c">"${item.male eq 'T'}">"${item.male eq 'F'}">${item.email}class="w4 c">${item.mobile}class="w1 c">"<%=path %>/servlet/UpdateUserServlet?opr=update&id=${item.id}">修改 "manageDel" href="<%=path %>/servlet/UpdateUserInfoServlet?id=${item.id}&opr=del&pageIndex=${pageIndex}">删除
class="clear">

 

     2.4.2 修改界面

"<%=path %>/servlet/UpdateUserInfoServlet?opr=update&sid=${id}" method="post">"${listf}" var="item">class="form">
class="field">用户名(*):"text" class="text" name="userName" value="${item.userId}" readonly="readonly" />
class="field">真实姓名(*):"text" class="text" name="name" value="${item.userName}" />
class="field">登录密码(*):"text" class="text" name="passWord" value="${item.password}" />
class="field">确认密码(*):"text" class="text" name="passWord" value="${item.password}" />
class="field">性别(*):"${item.male eq 'T'}">"radio" name="sex" value="T" checked="checked" />"radio" name="sex" value="F" />"radio" name="sex" value="T" />"radio" name="sex" value="F" checked="checked"/>
class="field">出生日期:"birthday" class="text" type="text" name="birthday" value="${item.birthday}"/>
class="field">手机(*):"text" class="text" name="mobile" value="${item.mobile}" />
class="field">地址(*):"text" class="text" name="address" value="${item.address}" />

    

       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 listfrist=impl.getAllOneLeveInfo(0);List 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 listfrist=impl.getAllOneLeveInfo(0);request.setAttribute("levellist",listfrist);            request.setAttribute("rid",id);List 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 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 getAllTowLeveInfo(int epcid)throws Exception {List list=new ArrayList();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);}} //获取选中条的epcidString 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(""); }} 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(""); }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");//一级分类idint pid=0;//二级分类idint 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 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

 

     3.4.2 执行修改

class="main">

修改分类

class="manage">
"<%=path %>/servlet/ProductSonServlet?opr=updateName&sid=${epcid}" method="post">class="form">"${levellist}" var="item">if test="${item.id eq epcid}">if>"${levelslist}" var="items">if test="${items.parentId eq rid}">if test="${items.id eq epcid}">if>if>
class="field">父分类: <select name="parentId">"${levellist}" var="item">if test="${item.id eq rid}">if>if test="${item.id != rid}">if>select>
class="field">分类名称:"text" class="text" name="className" value="${item.name}" />"text" class="text" name="className" value="${items.name}" />
class="clear">

   3.4.3 执行新增的jsp界面

 

class="main">

添加分类

class="manage">
"<%=path %>/servlet/ProductSonServlet?opr=addinfo" method="post">class="form">
class="field">父分类:<select name="parentId">"${levellist}" var="item"> select>
class="field">分类名称:"text" class="text" name="className" value="" />
class="clear">

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

      

    

转载于:https://www.cnblogs.com/bdpsc/p/5714096.html

更多相关: