伙伴云客服论坛»论坛 S区 S客户管理 查看内容

0 评论

0 收藏

分享

【项目实战】JavaWeb订单管理系统smbms

项目搭建

1.搭建maven web项目

2.配置tomcat

3.测试项目能否胜利启动

4.导入项目中可能会遇到的jar包
  1. <dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.21</version></dependency><!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl --><dependency><groupId>javax.servlet.jsp.jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- https://mvnrepository.com/artifact/taglibs/standard --><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency></dependencies>
复制代码
5.创建项目包构造

【项目实战】JavaWeb订单管理系统smbms-1.png


6.编写实体类 ORM映射:表-类映射

User,Role,Bill,Provider
7.编写根底公共类

7.1 数据库配置文件database.properties
  1. driver=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true&user=root&password=123456
  3. user=root
  4. password=123456
复制代码
7.2 编写数据库公共类

主要的工作为:
    获取数据库连接编写增删改查公共方法关闭对应的资源
  1. packagexyz.yiui.dao;importjava.io.IOException;importjava.io.InputStream;importjava.sql.*;importjava.util.Properties;///操作数据库的公共类publicclassBaseDao{privatestaticString driver;privatestaticString url;privatestaticString username;privatestaticString password;///静态代码块,类加载的时候就初始化了static{Properties properties=newProperties();///通过类加载器读取对应的资源InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("database.properties");try{
  2.             properties.load(is);}catch(IOException e){
  3.             e.printStackTrace();}
  4.         driver=properties.getProperty("driver");
  5.         url=properties.getProperty("url");
  6.         username=properties.getProperty("username");
  7.         password=properties.getProperty("password");}//获取数据库的连接publicstaticConnectiongetConnection()throwsClassNotFoundException,SQLException{Connection connection=null;Class.forName(driver);
  8.         connection=DriverManager.getConnection(url,username,password);return connection;}///编写查询公共方法 为了方便统一关闭,传入参数resultSet等publicstaticResultSetexecute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement)throwsSQLException{
  9.         preparedStatement=connection.prepareStatement(sql);for(int i=0;i<params.length;i++){
  10.             preparedStatement.setObject(i+1,params[i]);}
  11.         resultSet=preparedStatement.executeQuery();return resultSet;}///编写增删改公共方法publicstaticintexecute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement)throwsSQLException{
  12.         preparedStatement=connection.prepareStatement(sql);for(int i=0;i<params.length;i++){
  13.             preparedStatement.setObject(i+1,params[i]);}int ans=preparedStatement.executeUpdate();return ans;}///释放资源publicstaticbooleancloseResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){boolean flag=true;if(resultSet!=null){try{
  14.                 resultSet.close();
  15.                 resultSet=null;///GC回收}catch(SQLException e){
  16.                 e.printStackTrace();
  17.                 flag =false;}}if(preparedStatement!=null){try{
  18.                 preparedStatement.close();
  19.                 preparedStatement=null;///GC回收}catch(SQLException e){
  20.                 e.printStackTrace();
  21.                 flag =false;}}if(connection!=null){try{
  22.                 connection.close();
  23.                 connection=null;///GC回收}catch(SQLException e){
  24.                 e.printStackTrace();
  25.                 flag =false;}}return flag;}}
复制代码
7.3 编写字符编码过滤器
  1. packagexyz.yiui.filter;importjavax.servlet.*;importjava.io.IOException;publicclassCharacterEncodingFilterimplementsFilter{@Overridepublicvoidinit(FilterConfig filterConfig)throwsServletException{}@OverridepublicvoiddoFilter(ServletRequest request,ServletResponse response,FilterChain chain)throwsIOException,ServletException{
  2.         request.setCharacterEncoding("utf-8");
  3.         response.setCharacterEncoding("utf-8");
  4.         chain.doFilter(request,response);}@Overridepublicvoiddestroy(){}}
复制代码
在web.xml里注册
  1. <filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>xyz.yiui.filter.CharacterEncodingFilter</filter-class></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
复制代码
8.导入静态资源

【项目实战】JavaWeb订单管理系统smbms-2.png


登录功能实现

1.编写前端页面login.jsp

2.设置首页

在web.xml里配置
  1. <!--设置首页--><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list>
复制代码
3.编写dao层 用户登录的接口

3.1 编写dao接口UserDao
  1. packagexyz.yiui.dao.user;importxyz.yiui.pojo.User;importjava.sql.Connection;importjava.sql.SQLException;publicinterfaceUserDao{//得到要登录的用户publicUsergetLoginUser(Connection connection,String userCode)throwsSQLException;}
复制代码
3.2 编写对应的实现类UserDaoImpl
  1. packagexyz.yiui.dao.user;importxyz.yiui.dao.BaseDao;importxyz.yiui.pojo.User;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;publicclassUserDaoImplimplementsUserDao{@OverridepublicUsergetLoginUser(Connection connection,String userCode)throwsSQLException{PreparedStatement preparedStatement=null;ResultSet resultSet=null;User user=null;if(connection!=null){String sql="select * from smbms_user where userCode=?";Object[] params={userCode};
  2.                 resultSet=BaseDao.execute(connection,resultSet,preparedStatement,sql,params);if(resultSet.next()){
  3.                     user=newUser();
  4.                     user.setId(resultSet.getInt("id"));
  5.                     user.setUserCode(resultSet.getString("userCode"));
  6.                     user.setUserName(resultSet.getString("userName"));
  7.                     user.setUserPassword(resultSet.getString("userPassword"));
  8.                     user.setGender(resultSet.getInt("gender"));
  9.                     user.setBirthday(resultSet.getDate("birthday"));
  10.                     user.setPhone(resultSet.getString("phone"));
  11.                     user.setAddress(resultSet.getString("address"));
  12.                     user.setUserRole(resultSet.getInt("userRole"));
  13.                     user.setCreatedBy(resultSet.getInt("createdBy"));
  14.                     user.setCreationDate(resultSet.getTimestamp("creationDate"));
  15.                     user.setModifyBy(resultSet.getInt("modifyBy"));
  16.                     user.setModifyDate(resultSet.getTimestamp("modifyDate"));}BaseDao.closeResource(connection,preparedStatement,resultSet);}return user;}}
复制代码
4.编写业务层service 用户登录

4.1 业务层接口
  1. packagexyz.yiui.service.user;importxyz.yiui.pojo.User;publicinterfaceUserService{///用户登录publicUserlogin(String userCode,String password);}
复制代码
4.2 业务层实现类

假设密码不正确,设user为空。
  1. packagexyz.yiui.service.user;importorg.junit.jupiter.api.Test;importxyz.yiui.dao.BaseDao;importxyz.yiui.dao.user.UserDao;importxyz.yiui.dao.user.UserDaoImpl;importxyz.yiui.pojo.User;importjava.sql.Connection;importjava.sql.SQLException;publicclassUserServiceImplimplementsUserService{///引入dao层privateUserDao userDao;publicUserServiceImpl(){
  2.         userDao=newUserDaoImpl();}@OverridepublicUserlogin(String userCode,String password){Connection connection=null;User user=null;try{
  3.             connection=BaseDao.getConnection();///调用dao层详细操作
  4.             user= userDao.getLoginUser(connection,userCode);if(!password.equals(user.getUserPassword())) user=null;}catch(SQLException|ClassNotFoundException e){
  5.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return user;///返回查询结果}@Testpublicvoidtest(){UserServiceImpl userService=newUserServiceImpl();User admin=userService.login("admin","111");System.out.println(admin.getUserPassword());}}
复制代码
4.3 编写测试类
  1. @Testpublicvoidtest(){UserServiceImpl userService=newUserServiceImpl();User admin=userService.login("admin","111");System.out.println(admin.getUserPassword());}
复制代码
5.编写控制层servlet

5.1 编写代码
  1. packagexyz.yiui.servlet.user;importxyz.yiui.pojo.User;importxyz.yiui.service.user.UserService;importxyz.yiui.service.user.UserServiceImpl;importxyz.yiui.util.Constans;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;publicclassLoginServletextendsHttpServlet{//控制层,调用业务层代码@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{System.out.println("LoginServlet----------start");//获取用户名和密码String userCode=req.getParameter("userCode");String userPassword=req.getParameter("userPassword");///和数据库的密码停止对比,调用业务层UserService userService=newUserServiceImpl();User user=userService.login(userCode,userPassword);///查询胜利,可以登录if(user!=null){///将用户的信息放到session
  2.             req.getSession().setAttribute(Constans.USER_SESSION,user);///跳转到主页
  3.             resp.sendRedirect("jsp/frame.jsp");}else{///查询失败,转发到登陆页面,提示用户名或密码错误
  4.             req.setAttribute("error","用户名或密码不正确");
  5.             req.getRequestDispatcher("login.jsp").forward(req,resp);}}@OverrideprotectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{doGet(req, resp);}}
复制代码
utils里的Constans放常量
  1. packagexyz.yiui.util;publicclassConstans{publicfinalstaticString USER_SESSION="userSession";}
复制代码
5.2 注册servlet

在web.xml里注册
  1. <servlet><servlet-name>LoginServlet</servlet-name><servlet-class>xyz.yiui.servlet.user.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login.do</url-pattern></servlet-mapping>
复制代码
登录功能优化

1.注销:移除session,返回登陆页面

1.1servlet
  1. packagexyz.yiui.servlet.user;importxyz.yiui.util.Constans;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;publicclassLogoutServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{
  2.         req.getSession().removeAttribute(Constans.USER_SESSION);///移除session里的登录信息
  3.         resp.sendRedirect(req.getContextPath()+"/login.jsp");///跳转到登录页面}@OverrideprotectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{doGet(req, resp);}}
复制代码
1.2 web.xml
  1. <!--退出登录servlet--><servlet><servlet-name>LogoutServlet</servlet-name><servlet-class>xyz.yiui.servlet.user.LogoutServlet</servlet-class></servlet><servlet-mapping><servlet-name>LogoutServlet</servlet-name><url-pattern>/jsp/logout.do</url-pattern></servlet-mapping>
复制代码
2.登录拦截器

2.1 编写代码
  1. packagexyz.yiui.filter;importxyz.yiui.pojo.User;importxyz.yiui.util.Constans;importjavax.servlet.*;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;publicclassSysFilterimplementsFilter{@Overridepublicvoidinit(FilterConfig filterConfig)throwsServletException{}@OverridepublicvoiddoFilter(ServletRequest req,ServletResponse resp,FilterChain chain)throwsIOException,ServletException{HttpServletRequest request=(HttpServletRequest) req;HttpServletResponse response=(HttpServletResponse) resp;///从session获取用户User user=(User) request.getSession().getAttribute(Constans.USER_SESSION);if(user==null){///未登录或是注销
  2.             response.sendRedirect("/smbms/error.jsp");}else{
  3.             chain.doFilter(req,resp);}}@Overridepublicvoiddestroy(){}}
复制代码
2.2 注册web.xml
  1. <!--登录拦截--><filter><filter-name>SysFilter</filter-name><filter-class>xyz.yiui.filter.SysFilter</filter-class></filter><filter-mapping><filter-name>SysFilter</filter-name><url-pattern>/jsp/*</url-pattern></filter-mapping>
复制代码
密码修改

1.导入前端资源

2.编写代码dao层

2.1 userdao接口
  1. ///修改当前用户密码publicintupdatePwd(Connection connection,int id,String password)throwsSQLException;
复制代码
2.2 userdaoimpl实现类
  1. ///修改当前密码@OverridepublicintupdatePwd(Connection connection,int id,String password)throwsSQLException{PreparedStatement preparedStatement=null;int ans=0;if(connection!=null){String sql="update smbms_user set userPassword = ? where id = ?";Object params[]={password,id};
  2.             ans=BaseDao.execute(connection,preparedStatement,sql,params);BaseDao.closeResource(null,preparedStatement,null);///connection是传入的参数不需要释放资源}return ans;}
复制代码
3.service层

3.1 接口UserService
  1. ///修改当前用户密码publicbooleanupdatePwd(int id,String password);
复制代码
3.2实现类UserServiceImpl
  1. ///修改用户密码@OverridepublicbooleanupdatePwd(int id,String password){boolean flag=false;Connection connection=null;try{
  2.             connection=BaseDao.getConnection();if(userDao.updatePwd(connection,id,password)>0){
  3.                 flag=true;}}catch(SQLException|ClassNotFoundException e){
  4.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return flag;}
复制代码
4.servlet层UserServlet

进步servlet复用,写到方法里
  1. publicvoidupdatePwd(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{//从session里拿到当前登录用户的idObject o=req.getSession().getAttribute(Constans.USER_SESSION);///拿到新密码String newpassword=req.getParameter("newpassword");System.out.println("UserServlet"+newpassword);boolean flag=false;if(o!=null&&!StringUtils.isNullOrEmpty(newpassword)){UserService userService=newUserServiceImpl();
  2.             flag=userService.updatePwd(((User)o).getId(),newpassword );if(flag){//提示修改胜利,并且移除当前session
  3.                 req.setAttribute("message","update success,please logout");System.out.println("update success,please logout");
  4.                 req.getSession().removeAttribute(Constans.USER_SESSION);}else{
  5.                 req.setAttribute("message","update failed");System.out.println("update failed");}}else{
  6.             req.setAttribute("message","newpassword wrong");System.out.println("newpassword wrong");}
  7.         req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);System.out.println("update suceess");}
复制代码
在doGet里判断
  1. @OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{String method=req.getParameter("method");if(method.equals("savepwd")&&method!=null){this.updatePwd(req,resp);}}
复制代码
密码修改优化

在输入旧密码的时候就应该匹配旧密码是否正确,假设都放到后端去判断的话,不太符合逻辑需求,使用Ajax在前端停止判断。
1.导入jar包依赖 编写Ajax代码

借助阿里巴巴的工具类JSONArray实现格式的转换,所以先导入依赖
  1. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
复制代码
  1. $.ajax({type:"GET",url:path+"/jsp/user.do",data:{method:"pwdmodify",oldpassword:oldpassword.val()},///Ajax传送的参数///等价于跳转到path+"/jsp/user.do/method="pwdmodify"&&oldpassword=oldpassword.val()"dataType:"json",success:function(data){if(data.result =="true"){//旧密码正确validateTip(oldpassword.next(),{"color":"green"},imgYes,true);}elseif(data.result =="false"){//旧密码输入不正确validateTip(oldpassword.next(),{"color":"red"},imgNo +" 11oldpassword error",false);}elseif(data.result =="sessionerror"){//当前用户session过期,请重新登录validateTip(oldpassword.next(),{"color":"red"},imgNo +" 22session timeout",false);}elseif(data.result =="error"){//旧密码输入为空validateTip(oldpassword.next(),{"color":"red"},imgNo +" 33oldpassword null",false);}},error:function(data){//恳求出错validateTip(oldpassword.next(),{"color":"red"},imgNo +" 44req error",false);}});
复制代码
2.修改session过期时间web.xml
  1. <!--默认session过期时间30min--><session-config><session-timeout>30</session-timeout></session-config>
复制代码
3.编写servlet

首先停止判断,通过原生代码处置让map里的东西变为json
  1. ///修改密码publicvoidupdatePwd(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{//从session里拿到当前登录用户的idObject o=req.getSession().getAttribute(Constans.USER_SESSION);///拿到新密码String newpassword=req.getParameter("newpassword");System.out.println("UserServlet"+newpassword);boolean flag=false;if(o!=null&&!StringUtils.isNullOrEmpty(newpassword)){UserService userService=newUserServiceImpl();
  2.             flag=userService.updatePwd(((User)o).getId(),newpassword );if(flag){//提示修改胜利,并且移除当前session
  3.                 req.setAttribute("message","update success,please logout");System.out.println("update success,please logout");
  4.                 req.getSession().removeAttribute(Constans.USER_SESSION);}else{
  5.                 req.setAttribute("message","update failed");System.out.println("update failed");}}else{
  6.             req.setAttribute("message","newpassword wrong");System.out.println("newpassword wrong");}
  7.         req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);System.out.println("update suceess");}///判断旧密码是否合法,session里就有用户的密码,无需查询数据库publicvoidpwdmodify(HttpServletRequest req,HttpServletResponse resp){//从session里拿idObject o=req.getSession().getAttribute(Constans.USER_SESSION);String oldpassword=req.getParameter("oldpassword");///跟Ajax里的坚持一致///万能的map寄存结果集Map<String,String> resultMap=newHashMap<String,String>();if(o==null){///session失效或是过期了
  8.             resultMap.put("result","sessionerror");}elseif(StringUtils.isNullOrEmpty(oldpassword)){///输入的密码为空
  9.             resultMap.put("result","error");}else{///得到session里用户的密码String userpwd=((User)o).getUserPassword();if(oldpassword.equals(userpwd)){///密码正确
  10.                 resultMap.put("result","true");}else{
  11.                 resultMap.put("result","false");///密码不正确}}///将map转为json/*map=["result","true"]
  12.         * json={key:value}
  13.         * */try{
  14.             resp.setContentType("application/json");//设置响应格式PrintWriter writer=resp.getWriter();
  15.             writer.write(JSONArray.toJSONString(resultMap));
  16.             writer.flush();///刷新
  17.             writer.close();//关闭 防止内存溢出}catch(IOException e){
  18.             e.printStackTrace();}}
复制代码
用户管理

1.导入分页工具类PageSupport.java

OOP三大特性:封装(属性私有、get/set、在set里限定一些不安全情况
  1. packagexyz.yiui.util;publicclassPageSupport{//当前页码-来自于用户输入privateint currentPageNo =1;//总数量(表)private int totalCount = 0;//页面容量privateint pageSize =0;//总页数-totalCount/pageSize(+1)privateint totalPageCount =1;publicintgetCurrentPageNo(){return currentPageNo;}publicvoidsetCurrentPageNo(int currentPageNo){if(currentPageNo >0){this.currentPageNo = currentPageNo;}}publicintgetTotalCount(){return totalCount;}publicvoidsetTotalCount(int totalCount){if(totalCount >0){this.totalCount = totalCount;//设置总页数this.setTotalPageCountByRs();}}publicintgetPageSize(){return pageSize;}publicvoidsetPageSize(int pageSize){if(pageSize >0){this.pageSize = pageSize;}}publicintgetTotalPageCount(){return totalPageCount;}publicvoidsetTotalPageCount(int totalPageCount){this.totalPageCount = totalPageCount;}publicvoidsetTotalPageCountByRs(){if(this.totalCount %this.pageSize ==0){this.totalPageCount =this.totalCount /this.pageSize;}elseif(this.totalCount %this.pageSize >0){this.totalPageCount =this.totalCount /this.pageSize +1;}else{this.totalPageCount =0;}}}
复制代码
2.用户列表页面导入userlist.jsp跟rollpage.jsp

3.获取用户数量

3.1 编写代码dao层

3.1.1 UserDao
  1. //查询用户总数intpublicintgetUserCount(Connection connection,String username,int userRole)throwsSQLException;
复制代码
3.1.2 UserDaoImpl
  1. //根据用户名或用户角色查询用户总数@OverridepublicintgetUserCount(Connection connection,String username,int userRole)throwsSQLException{PreparedStatement preparedStatement=null;///预编译的ResultSet resultSet=null;int cnt=0;///最终查询出来的数量if(connection!=null){StringBuffer sql=newStringBuffer();
  2.             sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");ArrayList<Object> list =newArrayList<>();///先存到列表里if(!StringUtils.isNullOrEmpty(username)){///也要查询用户名
  3.                 sql.append("and u.userName like ?");
  4.                 list.add("%"+username+"%");}if(userRole>0){///也要查询角色信息
  5.                 sql.append("and u.userRole = ?");
  6.                 list.add(userRole);}Object[] objects=list.toArray();///转化为对象数组System.out.println("UserDaoImpl->getUserCount"+sql.toString());
  7.             resultSet=BaseDao.execute(connection,resultSet,preparedStatement,String.valueOf(sql),objects);if(resultSet.next()){
  8.                 cnt=resultSet.getInt("count");///从结果集中获取最终的数量}BaseDao.closeResource(null,preparedStatement,resultSet);///注意!在这里不关闭connection,因为connection是传入的参数,在业务层关闭}return cnt;}
复制代码
3.2 编写代码业务层

3.2.1 UserService
  1. //查询用户总数intpublicintgetUserCount(String username,int userRole);
复制代码
3.2.2 UserServiceImpl
  1. //查询记录数@OverridepublicintgetUserCount(String username,int userRole){Connection connection=null;int cnt=0;try{
  2.             connection=BaseDao.getConnection();
  3.             cnt=userDao.getUserCount(connection,username,userRole);}catch(SQLException throwables){
  4.             throwables.printStackTrace();}catch(ClassNotFoundException e){
  5.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return cnt;}
复制代码
3.3 测试
  1. @Testpublicvoidtest_getUserCount(){UserServiceImpl userService=newUserServiceImpl();int ans=userService.getUserCount(null,1);System.out.println(ans);}
复制代码
【项目实战】JavaWeb订单管理系统smbms-3.jpg


4.获取用户列表

在获取用户列表的时候要考虑到分页问题。
数据库中,分页使用limit
语法 limit startindex,pagesize
比如0,5表示第一页,5,5表示第二页,10,5表示第三页。
startindex=(当前页面-1)*页面大小
4.1编写代码dao层

4.1.1 UserDao
  1. ///获取用户列表publicList<User>getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throwsException;
复制代码
4.1.2 UserDaoImpl
  1. ///获取用户列表,考虑到分页问题@OverridepublicList<User>getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throwsException{PreparedStatement pstm =null;ResultSet rs =null;List<User> userList =newArrayList<User>();if(connection !=null){StringBuffer sql =newStringBuffer();
  2.             sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");List<Object> list =newArrayList<Object>();if(!StringUtils.isNullOrEmpty(userName)){
  3.                 sql.append(" and u.userName like ?");
  4.                 list.add("%"+userName+"%");}if(userRole >0){
  5.                 sql.append(" and u.userRole = ?");
  6.                 list.add(userRole);}
  7.             sql.append(" order by creationDate DESC limit ?,?");
  8.             currentPageNo =(currentPageNo-1)*pageSize;
  9.             list.add(currentPageNo);
  10.             list.add(pageSize);Object[] params = list.toArray();System.out.println("UserDaoImpl---->getUserList"+ sql.toString());
  11.             rs =BaseDao.execute(connection, rs,pstm , sql.toString(), params);while(rs.next()){User _user =newUser();
  12.                 _user.setId(rs.getInt("id"));
  13.                 _user.setUserCode(rs.getString("userCode"));
  14.                 _user.setUserName(rs.getString("userName"));
  15.                 _user.setGender(rs.getInt("gender"));
  16.                 _user.setBirthday(rs.getDate("birthday"));
  17.                 _user.setPhone(rs.getString("phone"));
  18.                 _user.setUserRole(rs.getInt("userRole"));
  19.                 _user.setUserRoleName(rs.getString("userRoleName"));
  20.                 userList.add(_user);}BaseDao.closeResource(null, pstm, rs);}return userList;}
复制代码
4.2 编写代码业务层

4.2.1 UserService
  1. //获取用户列表publicList<User>getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
复制代码
4.2.2 UserServiceImpl
  1. @OverridepublicList<User>getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize){Connection connection =null;List<User> userList =null;try{
  2.             connection =BaseDao.getConnection();
  3.             userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);}catch(Exception e){
  4.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return userList;}
复制代码
4.3 测试
  1. @Testpublicvoidtest_getUserList(){UserServiceImpl userService=newUserServiceImpl();List<User> ans=userService.getUserList(null,3,1,5);for(User t:ans)System.out.println(t);}
复制代码
【项目实战】JavaWeb订单管理系统smbms-4.png


改为2以后,查询第2页的数据

【项目实战】JavaWeb订单管理系统smbms-5.png


5.获取角色列表

5.1编写代码dao层

5.1.1 RoleDao
  1. //获取角色列表publicList<Role>getRoleList(Connection connection)throwsSQLException;
复制代码
5.1.2 RoleDaoImpl
  1. ///获取角色列表@OverridepublicList<Role>getRoleList(Connection connection)throwsSQLException{PreparedStatement pstm =null;ResultSet rs =null;List<Role> roleList =newArrayList<Role>();if(connection !=null){String sql ="select * from smbms_role";Object[] params ={};
  2.             rs =BaseDao.execute(connection, rs,pstm , sql, params);while(rs.next()){Role _role =newRole();
  3.                 _role.setId(rs.getInt("id"));
  4.                 _role.setRoleCode(rs.getString("roleCode"));
  5.                 _role.setRoleName(rs.getString("roleName"));
  6.                 roleList.add(_role);}BaseDao.closeResource(null, pstm, rs);}return roleList;}
复制代码
5.2 编写代码业务层

5.2.1 RoleService
  1. ///得到角色列表publicList<Role>getRoleList();
复制代码
5.2.2 RoleServiceImpl
  1. publicclassRoleServiceImplimplementsRoleService{privateRoleDao roleDao;publicRoleServiceImpl(){
  2.         roleDao =newRoleDaoImpl();}@OverridepublicList<Role>getRoleList(){Connection connection =null;List<Role> roleList =null;try{
  3.             connection =BaseDao.getConnection();
  4.             roleList = roleDao.getRoleList(connection);}catch(Exception e){
  5.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return roleList;}}
复制代码
5.3 测试
  1. @Testpublicvoidtest_getRoleList(){RoleServiceImpl roleService=newRoleServiceImpl();List<Role> ans=roleService.getRoleList();for(Role t:ans)System.out.println(t);}
复制代码
【项目实战】JavaWeb订单管理系统smbms-6.png


6.编写servlet

    获取用户的前端的数据,用于查询判断恳求是否要执行,看参数的值停止判断为了实现分页,需要计算出当前页面,总页面等,借助分页工具类实现用户列表显示将得到的数据返回给前端
UserServlet里
  1. @OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{String method=req.getParameter("method");if(method.equals("savepwd")&&method!=null){this.updatePwd(req,resp);}elseif(method.equals("pwdmodify")&&method!=null){this.pwdmodify(req,resp);}elseif(method.equals("query")&&method!=null){this.query(req,resp);}}
复制代码
  1. ///查询所有用户publicvoidquery(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{//查询用户列表//获取前端数据String queryUserName=req.getParameter("queryname");String tmp=req.getParameter("queryUserRole");///临时变量String pageIndex=req.getParameter("pageIndex");int queryUserRole=0;//获取用户列表UserServiceImpl userService=newUserServiceImpl();RoleServiceImpl roleService=newRoleServiceImpl();///第一次走这个恳求,一定是第一页,假设页面大小是固定的int pageSize=Constans.PAGESIZE;int currentPageNo=1;//当前if(queryUserName==null){
  2.             queryUserName="";}System.out.println(tmp);System.out.println(queryUserRole);if(!StringUtils.isNullOrEmpty(tmp)){
  3.             queryUserRole=Integer.parseInt(tmp);///查询真正的值System.out.println(queryUserRole);}if(pageIndex!=null){
  4.             currentPageNo=Integer.parseInt(pageIndex);}//获取用户的总数(分页,上一页和下一页)int totalCount=userService.getUserCount(queryUserName,queryUserRole);//总页数支持PageSupport pageSupport=newPageSupport();
  5.         pageSupport.setCurrentPageNo(currentPageNo);
  6.         pageSupport.setPageSize(pageSize);
  7.         pageSupport.setTotalCount(totalCount);int totalPageCount=pageSupport.getTotalPageCount();///得到总页数//下面控制首页和尾页if(currentPageNo<1) currentPageNo=1;if(currentPageNo>totalPageCount) currentPageNo=totalPageCount;///获取用户列表展示 将数据给前端List<User> userList=userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
  8.         req.setAttribute("userList",userList);List<Role>roleList=roleService.getRoleList();
  9.         req.setAttribute("roleList",roleList);
  10.         req.setAttribute("totalCount",totalCount);
  11.         req.setAttribute("currentPageNo",currentPageNo);
  12.         req.setAttribute("totalPageCount",totalPageCount);
  13.         req.setAttribute("queryUserName",queryUserName);
  14.         req.setAttribute("queryUserRole",queryUserRole);//返回前端try{
  15.             req.getRequestDispatcher("userlist.jsp").forward(req,resp);}catch(Exception e){
  16.             e.printStackTrace();}}
复制代码
一切的增删改操作都需要处置事务,ACID
7.增加用户

7.1 编写UserDao
  1. ///增加用户publicintadd(Connection connection,User user)throwsException;
复制代码
7.2 编写UserDaoImpl
  1. //修改用户@Overridepublicintadd(Connection connection,User user)throwsException{PreparedStatement pstm =null;int updateRows =0;if(null!= connection){String sql ="insert into smbms_user (userCode,userName,userPassword,"+"userRole,gender,birthday,phone,address,creationDate,createdBy) "+"values(?,?,?,?,?,?,?,?,?,?)";Object[] params ={user.getUserCode(),user.getUserName(),user.getUserPassword(),
  2.                     user.getUserRole(),user.getGender(),user.getBirthday(),
  3.                     user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()};
  4.             updateRows =BaseDao.execute(connection, pstm, sql, params);///影响的行数BaseDao.closeResource(null, pstm,null);}return updateRows;}
复制代码
7.3 编写UserService
  1. //增加用户呢publicbooleanadd(User user);
复制代码
7.4 编写UserServiceImpl
  1. //增加用户@Overridepublicbooleanadd(User user){boolean flag =false;Connection connection =null;try{
  2.             connection =BaseDao.getConnection();
  3.             connection.setAutoCommit(false);//开启JDBC事务管理int updateRows = userDao.add(connection,user);
  4.             connection.commit();//胜利的话直接提交if(updateRows >0){
  5.                 flag =true;System.out.println("add success!");}else{System.out.println("add failed!");}}catch(Exception e){
  6.             e.printStackTrace();try{System.out.println("rollback==================");
  7.                 connection.rollback();//失败的话回滚}catch(SQLException e1){
  8.                 e1.printStackTrace();}}finally{//关闭资源BaseDao.closeResource(connection,null,null);}return flag;}
复制代码
7.5 编写UserServlet

在doget里添加
  1. }elseif(method !=null&& method.equals("add")){//增加操作this.add(req, resp);}
复制代码
add函数如下
  1. //增加新用户privatevoidadd(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{System.out.println("add()================");String userCode = request.getParameter("userCode");String userName = request.getParameter("userName");String userPassword = request.getParameter("userPassword");String gender = request.getParameter("gender");String birthday = request.getParameter("birthday");String phone = request.getParameter("phone");String address = request.getParameter("address");String userRole = request.getParameter("userRole");User user =newUser();
  2.         user.setUserCode(userCode);
  3.         user.setUserName(userName);
  4.         user.setUserPassword(userPassword);
  5.         user.setAddress(address);try{
  6.             user.setBirthday(newSimpleDateFormat("yyyy-MM-dd").parse(birthday));}catch(ParseException e){
  7.             e.printStackTrace();}
  8.         user.setGender(Integer.valueOf(gender));
  9.         user.setPhone(phone);
  10.         user.setUserRole(Integer.valueOf(userRole));
  11.         user.setCreationDate(newDate());
  12.         user.setCreatedBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId());UserService userService =newUserServiceImpl();if(userService.add(user)){
  13.             response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");}else{
  14.             request.getRequestDispatcher("useradd.jsp").forward(request, response);}}
复制代码
8.修改用户信息

8.1 编写UserDao
  1. ///更新用户publicintmodify(Connection connection,User user)throwsException;
复制代码
8.2 编写UserDaoImpl
  1. //更新用户@Overridepublicintmodify(Connection connection,User user)throwsException{int flag =0;PreparedStatement pstm =null;if(null!= connection){String sql ="update smbms_user set userName=?,"+"gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";Object[] params ={user.getUserName(),user.getGender(),user.getBirthday(),
  2.                     user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
  3.                     user.getModifyDate(),user.getId()};
  4.             flag =BaseDao.execute(connection, pstm, sql, params);BaseDao.closeResource(null, pstm,null);}return flag;}
复制代码
8.3 编写UserService
  1. //修改用户publicbooleanmodify(User user);
复制代码
8.4 编写UserServiceImpl
  1. //更新用户@Overridepublicbooleanmodify(User user){Connection connection =null;boolean flag =false;try{
  2.             connection =BaseDao.getConnection();if(userDao.modify(connection,user)>0)
  3.                 flag =true;}catch(Exception e){
  4.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return flag;}
复制代码
8.5 编写UserServlet
  1. elseif(method !=null&& method.equals("modify")){this.getUserById(req, resp,"usermodify.jsp");}elseif(method !=null&& method.equals("modifyexe")){this.modify(req, resp);}
复制代码
  1. //更新用户privatevoidmodify(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String id = request.getParameter("uid");String userName = request.getParameter("userName");String gender = request.getParameter("gender");String birthday = request.getParameter("birthday");String phone = request.getParameter("phone");String address = request.getParameter("address");String userRole = request.getParameter("userRole");User user =newUser();
  2.         user.setId(Integer.valueOf(id));
  3.         user.setUserName(userName);
  4.         user.setGender(Integer.valueOf(gender));try{
  5.             user.setBirthday(newSimpleDateFormat("yyyy-MM-dd").parse(birthday));}catch(ParseException e){
  6.             e.printStackTrace();}
  7.         user.setPhone(phone);
  8.         user.setAddress(address);
  9.         user.setUserRole(Integer.valueOf(userRole));
  10.         user.setModifyBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId());
  11.         user.setModifyDate(newDate());UserService userService =newUserServiceImpl();if(userService.modify(user)){
  12.             response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");}else{
  13.             request.getRequestDispatcher("usermodify.jsp").forward(request, response);}}
复制代码
9.删除用户

9.1 编写UserDao
  1. //删除用户publicintdeleteUserById(Connection connection,Integer delId)throwsException;
复制代码
9.2 编写UserDaoImpl
  1. //删除用户@OverridepublicintdeleteUserById(Connection connection,Integer delId)throwsException{PreparedStatement pstm =null;int flag =0;if(null!= connection){String sql ="delete from smbms_user where id=?";Object[] params ={delId};
  2.             flag =BaseDao.execute(connection, pstm, sql, params);BaseDao.closeResource(null, pstm,null);}return flag;}
复制代码
9.3 编写UserService
  1. //删除用户publicbooleandeleteUserById(Integer delId);
复制代码
9.4 编写UserServiceImpl
  1. ///删除用户@OverridepublicbooleandeleteUserById(Integer delId){Connection connection =null;boolean flag =false;try{
  2.             connection =BaseDao.getConnection();
  3.             connection.setAutoCommit(false);//开启JDBC事务管理
  4.             connection.commit();//胜利的话直接提交if(userDao.deleteUserById(connection,delId)>0)
  5.                 flag =true;}catch(Exception e){
  6.             e.printStackTrace();try{System.out.println("rollback==================");
  7.                 connection.rollback();//失败的话回滚}catch(SQLException e1){
  8.                 e1.printStackTrace();}}finally{BaseDao.closeResource(connection,null,null);}return flag;}
复制代码
9.5 编写UserServlet

在doget里添加
  1. elseif(method !=null&& method.equals("deluser")){this.delUser(req, resp);}
复制代码
删除方法如下:
  1. //删除用户privatevoiddelUser(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String id = request.getParameter("uid");Integer delId =0;try{
  2.             delId =Integer.parseInt(id);}catch(Exception e){
  3.             delId =0;}HashMap<String,String> resultMap =newHashMap<String,String>();if(delId <=0){
  4.             resultMap.put("delResult","notexist");}else{UserService userService =newUserServiceImpl();if(userService.deleteUserById(delId)){
  5.                 resultMap.put("delResult","true");}else{
  6.                 resultMap.put("delResult","false");}}//把resultMap转换成json对象输出
  7.         response.setContentType("application/json");PrintWriter outPrintWriter = response.getWriter();
  8.         outPrintWriter.write(JSONArray.toJSONString(resultMap));
  9.         outPrintWriter.flush();
  10.         outPrintWriter.close();}
复制代码
10.查看用户详细信息

10.1 编写UserDao
  1. ///根据id得到用户publicUsergetUserById(Connection connection,String id)throwsException;
复制代码
10.2 编写UserDaoImpl
  1. ///根据id得到用户@OverridepublicUsergetUserById(Connection connection,String id)throwsException{User user =null;PreparedStatement pstm =null;ResultSet rs =null;if(null!= connection){String sql ="select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";Object[] params ={id};
  2.             rs =BaseDao.execute(connection, rs,pstm , sql, params);if(rs.next()){
  3.                 user =newUser();
  4.                 user.setId(rs.getInt("id"));
  5.                 user.setUserCode(rs.getString("userCode"));
  6.                 user.setUserName(rs.getString("userName"));
  7.                 user.setUserPassword(rs.getString("userPassword"));
  8.                 user.setGender(rs.getInt("gender"));
  9.                 user.setBirthday(rs.getDate("birthday"));
  10.                 user.setPhone(rs.getString("phone"));
  11.                 user.setAddress(rs.getString("address"));
  12.                 user.setUserRole(rs.getInt("userRole"));
  13.                 user.setCreatedBy(rs.getInt("createdBy"));
  14.                 user.setCreationDate(rs.getTimestamp("creationDate"));
  15.                 user.setModifyBy(rs.getInt("modifyBy"));
  16.                 user.setModifyDate(rs.getTimestamp("modifyDate"));
  17.                 user.setUserRoleName(rs.getString("userRoleName"));}BaseDao.closeResource(null, pstm, rs);}return user;}
复制代码
10.3 编写UserService
  1. //根据id得到用户publicUsergetUserById(String id);
复制代码
10.4 编写UserServiceImpl
  1. //根据id得到用户@OverridepublicUsergetUserById(String id){User user =null;Connection connection =null;try{
  2.             connection =BaseDao.getConnection();
  3.             user = userDao.getUserById(connection,id);}catch(Exception e){
  4.             e.printStackTrace();
  5.             user =null;}finally{BaseDao.closeResource(connection,null,null);}return user;}
复制代码
10.5 编写UserServlet

在doGET里添加
  1. elseif(method !=null&& method.equals("view")){this.getUserById(req, resp,"userview.jsp");}
复制代码
  1. //根据id得到用户privatevoidgetUserById(HttpServletRequest request,HttpServletResponse response,String url)throwsServletException,IOException{String id = request.getParameter("uid");if(!StringUtils.isNullOrEmpty(id)){//调用后台方法得到user对象UserService userService =newUserServiceImpl();User user = userService.getUserById(id);
  2.             request.setAttribute("user", user);
  3.             request.getRequestDispatcher(url).forward(request, response);}}
复制代码
11.完善

11.1添加获取角色列表

在servlet里添加获取角色列表的方法
doGet添加
  1. elseif(method !=null&& method.equals("getrolelist")){this.getRoleList(req,resp);}
复制代码
然后写这个方法,就是得到角色列表,调用之前写好的业务层逻辑即可
  1. privatevoidgetRoleList(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{List<Role> roleList =null;RoleService roleService =newRoleServiceImpl();
  2.         roleList = roleService.getRoleList();//把roleList转换成json对象输出
  3.         response.setContentType("application/json");PrintWriter outPrintWriter = response.getWriter();
  4.         outPrintWriter.write(JSONArray.toJSONString(roleList));
  5.         outPrintWriter.flush();
  6.         outPrintWriter.close();}
复制代码
11.2 查看相同用户编码的人是否存在

因为在填写的时候,使用了Ajax异步判断相同用户编码的人在数据库里是否已经存在,所以对其停止判断。
11.2.1 UserDao
  1. ///通过用户编码查找用户publicUsergetUserByCode(Connection connection,String userCode)throwsException;
复制代码
11.2.2 UserDaoImpl
  1. @OverridepublicUsergetUserByCode(Connection connection,String userCode)throwsException{// TODO Auto-generated method stubPreparedStatement pstm =null;ResultSet rs =null;User user =null;if(null!= connection){String sql ="select * from smbms_user where userCode=?";Object[] params ={userCode};
  2.             rs =BaseDao.execute(connection, rs, pstm, sql, params);if(rs.next()){
  3.                 user =newUser();
  4.                 user.setId(rs.getInt("id"));
  5.                 user.setUserCode(rs.getString("userCode"));
  6.                 user.setUserName(rs.getString("userName"));
  7.                 user.setUserPassword(rs.getString("userPassword"));
  8.                 user.setGender(rs.getInt("gender"));
  9.                 user.setBirthday(rs.getDate("birthday"));
  10.                 user.setPhone(rs.getString("phone"));
  11.                 user.setAddress(rs.getString("address"));
  12.                 user.setUserRole(rs.getInt("userRole"));
  13.                 user.setCreatedBy(rs.getInt("createdBy"));
  14.                 user.setCreationDate(rs.getTimestamp("creationDate"));
  15.                 user.setModifyBy(rs.getInt("modifyBy"));
  16.                 user.setModifyDate(rs.getTimestamp("modifyDate"));}BaseDao.closeResource(null, pstm, rs);}return user;}
复制代码
11.2.3 userService
  1. ///根据用户编码查找用户publicUserselectUserCodeExist(String userCode);
复制代码
11.2.4 userServiceImpl
  1. //根据用户编码查找用户@OverridepublicUserselectUserCodeExist(String userCode){Connection connection =null;User user =null;try{
  2.             connection =BaseDao.getConnection();
  3.             user = userDao.getUserByCode(connection, userCode);}catch(Exception e){
  4.             e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return user;}
复制代码
11.2.5 UserServlet

在doGet里添加判断
  1. elseif(method !=null&& method.equals("ucexist")){this.userCodeExist(request, response);}
复制代码
编写判断函数
  1. ///判断用户编码的用户是否存在privatevoiduserCodeExist(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String userCode = request.getParameter("userCode");HashMap<String,String> resultMap =newHashMap<String,String>();if(StringUtils.isNullOrEmpty(userCode)){
  2.             resultMap.put("userCode","exist");}else{UserService userService =newUserServiceImpl();User user = userService.selectUserCodeExist(userCode);if(null!= user){
  3.                 resultMap.put("userCode","exist");}else{
  4.                 resultMap.put("userCode","notexist");}}//把resultMap转为json字符串以json的形式输出//配置上下文的输出类型
  5.         response.setContentType("application/json");//从response对象中获取往外输出的writer对象PrintWriter outPrintWriter = response.getWriter();//把resultMap转为json字符串 输出
  6.         outPrintWriter.write(JSONArray.toJSONString(resultMap));
  7.         outPrintWriter.flush();//刷新
  8.         outPrintWriter.close();//关闭流}
复制代码
项目地址

回复

举报 使用道具

相关帖子
全部回复
暂无回帖,快来参与回复吧
本版积分规则 高级模式
B Color Image Link Quote Code Smilies

马可菠萝包
注册会员
主题 8
回复 18
粉丝 0
|网站地图
快速回复 返回顶部 返回列表