项目搭建
1.搭建maven web项目
2.配置tomcat
3.测试项目能否胜利启动
4.导入项目中可能会遇到的jar包
<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.创建项目包构造
6.编写实体类 ORM映射:表-类映射
User,Role,Bill,Provider
7.编写根底公共类
7.1 数据库配置文件database.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true&user=root&password=123456 user=root password=123456 复制代码 7.2 编写数据库公共类
主要的工作为:
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{ properties.load(is);}catch(IOException e){ e.printStackTrace();} driver=properties.getProperty("driver"); url=properties.getProperty("url"); username=properties.getProperty("username"); password=properties.getProperty("password");}//获取数据库的连接publicstaticConnectiongetConnection()throwsClassNotFoundException,SQLException{Connection connection=null;Class.forName(driver); connection=DriverManager.getConnection(url,username,password);return connection;}///编写查询公共方法 为了方便统一关闭,传入参数resultSet等publicstaticResultSetexecute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement)throwsSQLException{ preparedStatement=connection.prepareStatement(sql);for(int i=0;i<params.length;i++){ preparedStatement.setObject(i+1,params[i]);} resultSet=preparedStatement.executeQuery();return resultSet;}///编写增删改公共方法publicstaticintexecute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement)throwsSQLException{ preparedStatement=connection.prepareStatement(sql);for(int i=0;i<params.length;i++){ 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{ resultSet.close(); resultSet=null;///GC回收}catch(SQLException e){ e.printStackTrace(); flag =false;}}if(preparedStatement!=null){try{ preparedStatement.close(); preparedStatement=null;///GC回收}catch(SQLException e){ e.printStackTrace(); flag =false;}}if(connection!=null){try{ connection.close(); connection=null;///GC回收}catch(SQLException e){ e.printStackTrace(); flag =false;}}return flag;}} 复制代码 7.3 编写字符编码过滤器
packagexyz.yiui.filter;importjavax.servlet.*;importjava.io.IOException;publicclassCharacterEncodingFilterimplementsFilter{@Overridepublicvoidinit(FilterConfig filterConfig)throwsServletException{}@OverridepublicvoiddoFilter(ServletRequest request,ServletResponse response,FilterChain chain)throwsIOException,ServletException{ request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); chain.doFilter(request,response);}@Overridepublicvoiddestroy(){}} 复制代码 在web.xml里注册<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.导入静态资源
登录功能实现
1.编写前端页面login.jsp
2.设置首页
在web.xml里配置<!--设置首页--><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list> 复制代码 3.编写dao层 用户登录的接口
3.1 编写dao接口UserDao
packagexyz.yiui.dao.user;importxyz.yiui.pojo.User;importjava.sql.Connection;importjava.sql.SQLException;publicinterfaceUserDao{//得到要登录的用户publicUsergetLoginUser(Connection connection,String userCode)throwsSQLException;} 复制代码 3.2 编写对应的实现类UserDaoImpl
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}; resultSet=BaseDao.execute(connection,resultSet,preparedStatement,sql,params);if(resultSet.next()){ user=newUser(); user.setId(resultSet.getInt("id")); user.setUserCode(resultSet.getString("userCode")); user.setUserName(resultSet.getString("userName")); user.setUserPassword(resultSet.getString("userPassword")); user.setGender(resultSet.getInt("gender")); user.setBirthday(resultSet.getDate("birthday")); user.setPhone(resultSet.getString("phone")); user.setAddress(resultSet.getString("address")); user.setUserRole(resultSet.getInt("userRole")); user.setCreatedBy(resultSet.getInt("createdBy")); user.setCreationDate(resultSet.getTimestamp("creationDate")); user.setModifyBy(resultSet.getInt("modifyBy")); user.setModifyDate(resultSet.getTimestamp("modifyDate"));}BaseDao.closeResource(connection,preparedStatement,resultSet);}return user;}} 复制代码 4.编写业务层service 用户登录
4.1 业务层接口
packagexyz.yiui.service.user;importxyz.yiui.pojo.User;publicinterfaceUserService{///用户登录publicUserlogin(String userCode,String password);} 复制代码 4.2 业务层实现类
假设密码不正确,设user为空。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(){ userDao=newUserDaoImpl();}@OverridepublicUserlogin(String userCode,String password){Connection connection=null;User user=null;try{ connection=BaseDao.getConnection();///调用dao层详细操作 user= userDao.getLoginUser(connection,userCode);if(!password.equals(user.getUserPassword())) user=null;}catch(SQLException|ClassNotFoundException e){ 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 编写测试类
@Testpublicvoidtest(){UserServiceImpl userService=newUserServiceImpl();User admin=userService.login("admin","111");System.out.println(admin.getUserPassword());} 复制代码 5.编写控制层servlet
5.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 req.getSession().setAttribute(Constans.USER_SESSION,user);///跳转到主页 resp.sendRedirect("jsp/frame.jsp");}else{///查询失败,转发到登陆页面,提示用户名或密码错误 req.setAttribute("error","用户名或密码不正确"); req.getRequestDispatcher("login.jsp").forward(req,resp);}}@OverrideprotectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{doGet(req, resp);}} 复制代码 utils里的Constans放常量packagexyz.yiui.util;publicclassConstans{publicfinalstaticString USER_SESSION="userSession";} 复制代码 5.2 注册servlet
在web.xml里注册<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
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{ req.getSession().removeAttribute(Constans.USER_SESSION);///移除session里的登录信息 resp.sendRedirect(req.getContextPath()+"/login.jsp");///跳转到登录页面}@OverrideprotectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{doGet(req, resp);}} 复制代码 1.2 web.xml
<!--退出登录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 编写代码
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){///未登录或是注销 response.sendRedirect("/smbms/error.jsp");}else{ chain.doFilter(req,resp);}}@Overridepublicvoiddestroy(){}} 复制代码 2.2 注册web.xml
<!--登录拦截--><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接口
///修改当前用户密码publicintupdatePwd(Connection connection,int id,String password)throwsSQLException; 复制代码 2.2 userdaoimpl实现类
///修改当前密码@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}; ans=BaseDao.execute(connection,preparedStatement,sql,params);BaseDao.closeResource(null,preparedStatement,null);///connection是传入的参数不需要释放资源}return ans;} 复制代码 3.service层
3.1 接口UserService
///修改当前用户密码publicbooleanupdatePwd(int id,String password); 复制代码 3.2实现类UserServiceImpl
///修改用户密码@OverridepublicbooleanupdatePwd(int id,String password){boolean flag=false;Connection connection=null;try{ connection=BaseDao.getConnection();if(userDao.updatePwd(connection,id,password)>0){ flag=true;}}catch(SQLException|ClassNotFoundException e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return flag;} 复制代码 4.servlet层UserServlet
进步servlet复用,写到方法里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(); flag=userService.updatePwd(((User)o).getId(),newpassword );if(flag){//提示修改胜利,并且移除当前session req.setAttribute("message","update success,please logout");System.out.println("update success,please logout"); req.getSession().removeAttribute(Constans.USER_SESSION);}else{ req.setAttribute("message","update failed");System.out.println("update failed");}}else{ req.setAttribute("message","newpassword wrong");System.out.println("newpassword wrong");} req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);System.out.println("update suceess");} 复制代码 在doGet里判断@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实现格式的转换,所以先导入依赖<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency> 复制代码 $.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
<!--默认session过期时间30min--><session-config><session-timeout>30</session-timeout></session-config> 复制代码 3.编写servlet
首先停止判断,通过原生代码处置让map里的东西变为json///修改密码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(); flag=userService.updatePwd(((User)o).getId(),newpassword );if(flag){//提示修改胜利,并且移除当前session req.setAttribute("message","update success,please logout");System.out.println("update success,please logout"); req.getSession().removeAttribute(Constans.USER_SESSION);}else{ req.setAttribute("message","update failed");System.out.println("update failed");}}else{ req.setAttribute("message","newpassword wrong");System.out.println("newpassword wrong");} 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失效或是过期了 resultMap.put("result","sessionerror");}elseif(StringUtils.isNullOrEmpty(oldpassword)){///输入的密码为空 resultMap.put("result","error");}else{///得到session里用户的密码String userpwd=((User)o).getUserPassword();if(oldpassword.equals(userpwd)){///密码正确 resultMap.put("result","true");}else{ resultMap.put("result","false");///密码不正确}}///将map转为json/*map=["result","true"] * json={key:value} * */try{ resp.setContentType("application/json");//设置响应格式PrintWriter writer=resp.getWriter(); writer.write(JSONArray.toJSONString(resultMap)); writer.flush();///刷新 writer.close();//关闭 防止内存溢出}catch(IOException e){ e.printStackTrace();}} 复制代码 用户管理
1.导入分页工具类PageSupport.java
OOP三大特性:封装(属性私有、get/set、在set里限定一些不安全情况 )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
//查询用户总数intpublicintgetUserCount(Connection connection,String username,int userRole)throwsSQLException; 复制代码 3.1.2 UserDaoImpl
//根据用户名或用户角色查询用户总数@OverridepublicintgetUserCount(Connection connection,String username,int userRole)throwsSQLException{PreparedStatement preparedStatement=null;///预编译的ResultSet resultSet=null;int cnt=0;///最终查询出来的数量if(connection!=null){StringBuffer sql=newStringBuffer(); 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)){///也要查询用户名 sql.append("and u.userName like ?"); list.add("%"+username+"%");}if(userRole>0){///也要查询角色信息 sql.append("and u.userRole = ?"); list.add(userRole);}Object[] objects=list.toArray();///转化为对象数组System.out.println("UserDaoImpl->getUserCount"+sql.toString()); resultSet=BaseDao.execute(connection,resultSet,preparedStatement,String.valueOf(sql),objects);if(resultSet.next()){ cnt=resultSet.getInt("count");///从结果集中获取最终的数量}BaseDao.closeResource(null,preparedStatement,resultSet);///注意!在这里不关闭connection,因为connection是传入的参数,在业务层关闭}return cnt;} 复制代码 3.2 编写代码业务层
3.2.1 UserService
//查询用户总数intpublicintgetUserCount(String username,int userRole); 复制代码 3.2.2 UserServiceImpl
//查询记录数@OverridepublicintgetUserCount(String username,int userRole){Connection connection=null;int cnt=0;try{ connection=BaseDao.getConnection(); cnt=userDao.getUserCount(connection,username,userRole);}catch(SQLException throwables){ throwables.printStackTrace();}catch(ClassNotFoundException e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return cnt;} 复制代码 3.3 测试
@Testpublicvoidtest_getUserCount(){UserServiceImpl userService=newUserServiceImpl();int ans=userService.getUserCount(null,1);System.out.println(ans);} 复制代码
4.获取用户列表
在获取用户列表的时候要考虑到分页问题。
数据库中,分页使用limit
语法 limit startindex,pagesize
比如0,5表示第一页,5,5表示第二页,10,5表示第三页。
startindex=(当前页面-1)*页面大小
4.1编写代码dao层
4.1.1 UserDao
///获取用户列表publicList<User>getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throwsException; 复制代码 4.1.2 UserDaoImpl
///获取用户列表,考虑到分页问题@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(); 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)){ sql.append(" and u.userName like ?"); list.add("%"+userName+"%");}if(userRole >0){ sql.append(" and u.userRole = ?"); list.add(userRole);} sql.append(" order by creationDate DESC limit ?,?"); currentPageNo =(currentPageNo-1)*pageSize; list.add(currentPageNo); list.add(pageSize);Object[] params = list.toArray();System.out.println("UserDaoImpl---->getUserList"+ sql.toString()); rs =BaseDao.execute(connection, rs,pstm , sql.toString(), params);while(rs.next()){User _user =newUser(); _user.setId(rs.getInt("id")); _user.setUserCode(rs.getString("userCode")); _user.setUserName(rs.getString("userName")); _user.setGender(rs.getInt("gender")); _user.setBirthday(rs.getDate("birthday")); _user.setPhone(rs.getString("phone")); _user.setUserRole(rs.getInt("userRole")); _user.setUserRoleName(rs.getString("userRoleName")); userList.add(_user);}BaseDao.closeResource(null, pstm, rs);}return userList;} 复制代码 4.2 编写代码业务层
4.2.1 UserService
//获取用户列表publicList<User>getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize); 复制代码 4.2.2 UserServiceImpl
@OverridepublicList<User>getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize){Connection connection =null;List<User> userList =null;try{ connection =BaseDao.getConnection(); userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);}catch(Exception e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return userList;} 复制代码 4.3 测试
@Testpublicvoidtest_getUserList(){UserServiceImpl userService=newUserServiceImpl();List<User> ans=userService.getUserList(null,3,1,5);for(User t:ans)System.out.println(t);} 复制代码
改为2以后,查询第2页的数据
5.获取角色列表
5.1编写代码dao层
5.1.1 RoleDao
//获取角色列表publicList<Role>getRoleList(Connection connection)throwsSQLException; 复制代码 5.1.2 RoleDaoImpl
///获取角色列表@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 ={}; rs =BaseDao.execute(connection, rs,pstm , sql, params);while(rs.next()){Role _role =newRole(); _role.setId(rs.getInt("id")); _role.setRoleCode(rs.getString("roleCode")); _role.setRoleName(rs.getString("roleName")); roleList.add(_role);}BaseDao.closeResource(null, pstm, rs);}return roleList;} 复制代码 5.2 编写代码业务层
5.2.1 RoleService
///得到角色列表publicList<Role>getRoleList(); 复制代码 5.2.2 RoleServiceImpl
publicclassRoleServiceImplimplementsRoleService{privateRoleDao roleDao;publicRoleServiceImpl(){ roleDao =newRoleDaoImpl();}@OverridepublicList<Role>getRoleList(){Connection connection =null;List<Role> roleList =null;try{ connection =BaseDao.getConnection(); roleList = roleDao.getRoleList(connection);}catch(Exception e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return roleList;}} 复制代码 5.3 测试
@Testpublicvoidtest_getRoleList(){RoleServiceImpl roleService=newRoleServiceImpl();List<Role> ans=roleService.getRoleList();for(Role t:ans)System.out.println(t);} 复制代码
6.编写servlet
获取用户的前端的数据,用于查询判断恳求是否要执行,看参数的值停止判断为了实现分页,需要计算出当前页面,总页面等,借助分页工具类实现用户列表显示将得到的数据返回给前端
UserServlet里@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);}} 复制代码 ///查询所有用户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){ queryUserName="";}System.out.println(tmp);System.out.println(queryUserRole);if(!StringUtils.isNullOrEmpty(tmp)){ queryUserRole=Integer.parseInt(tmp);///查询真正的值System.out.println(queryUserRole);}if(pageIndex!=null){ currentPageNo=Integer.parseInt(pageIndex);}//获取用户的总数(分页,上一页和下一页)int totalCount=userService.getUserCount(queryUserName,queryUserRole);//总页数支持PageSupport pageSupport=newPageSupport(); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.setPageSize(pageSize); 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); req.setAttribute("userList",userList);List<Role>roleList=roleService.getRoleList(); req.setAttribute("roleList",roleList); req.setAttribute("totalCount",totalCount); req.setAttribute("currentPageNo",currentPageNo); req.setAttribute("totalPageCount",totalPageCount); req.setAttribute("queryUserName",queryUserName); req.setAttribute("queryUserRole",queryUserRole);//返回前端try{ req.getRequestDispatcher("userlist.jsp").forward(req,resp);}catch(Exception e){ e.printStackTrace();}} 复制代码 一切的增删改操作都需要处置事务 ,ACID
7.增加用户
7.1 编写UserDao
///增加用户publicintadd(Connection connection,User user)throwsException; 复制代码 7.2 编写UserDaoImpl
//修改用户@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(), user.getUserRole(),user.getGender(),user.getBirthday(), user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()}; updateRows =BaseDao.execute(connection, pstm, sql, params);///影响的行数BaseDao.closeResource(null, pstm,null);}return updateRows;} 复制代码 7.3 编写UserService
//增加用户呢publicbooleanadd(User user); 复制代码 7.4 编写UserServiceImpl
//增加用户@Overridepublicbooleanadd(User user){boolean flag =false;Connection connection =null;try{ connection =BaseDao.getConnection(); connection.setAutoCommit(false);//开启JDBC事务管理int updateRows = userDao.add(connection,user); connection.commit();//胜利的话直接提交if(updateRows >0){ flag =true;System.out.println("add success!");}else{System.out.println("add failed!");}}catch(Exception e){ e.printStackTrace();try{System.out.println("rollback=================="); connection.rollback();//失败的话回滚}catch(SQLException e1){ e1.printStackTrace();}}finally{//关闭资源BaseDao.closeResource(connection,null,null);}return flag;} 复制代码 7.5 编写UserServlet
在doget里添加}elseif(method !=null&& method.equals("add")){//增加操作this.add(req, resp);} 复制代码 add函数如下//增加新用户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(); user.setUserCode(userCode); user.setUserName(userName); user.setUserPassword(userPassword); user.setAddress(address);try{ user.setBirthday(newSimpleDateFormat("yyyy-MM-dd").parse(birthday));}catch(ParseException e){ e.printStackTrace();} user.setGender(Integer.valueOf(gender)); user.setPhone(phone); user.setUserRole(Integer.valueOf(userRole)); user.setCreationDate(newDate()); user.setCreatedBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId());UserService userService =newUserServiceImpl();if(userService.add(user)){ response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");}else{ request.getRequestDispatcher("useradd.jsp").forward(request, response);}} 复制代码 8.修改用户信息
8.1 编写UserDao
///更新用户publicintmodify(Connection connection,User user)throwsException; 复制代码 8.2 编写UserDaoImpl
//更新用户@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(), user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(), user.getModifyDate(),user.getId()}; flag =BaseDao.execute(connection, pstm, sql, params);BaseDao.closeResource(null, pstm,null);}return flag;} 复制代码 8.3 编写UserService
//修改用户publicbooleanmodify(User user); 复制代码 8.4 编写UserServiceImpl
//更新用户@Overridepublicbooleanmodify(User user){Connection connection =null;boolean flag =false;try{ connection =BaseDao.getConnection();if(userDao.modify(connection,user)>0) flag =true;}catch(Exception e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return flag;} 复制代码 8.5 编写UserServlet
elseif(method !=null&& method.equals("modify")){this.getUserById(req, resp,"usermodify.jsp");}elseif(method !=null&& method.equals("modifyexe")){this.modify(req, resp);} 复制代码 //更新用户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(); user.setId(Integer.valueOf(id)); user.setUserName(userName); user.setGender(Integer.valueOf(gender));try{ user.setBirthday(newSimpleDateFormat("yyyy-MM-dd").parse(birthday));}catch(ParseException e){ e.printStackTrace();} user.setPhone(phone); user.setAddress(address); user.setUserRole(Integer.valueOf(userRole)); user.setModifyBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId()); user.setModifyDate(newDate());UserService userService =newUserServiceImpl();if(userService.modify(user)){ response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");}else{ request.getRequestDispatcher("usermodify.jsp").forward(request, response);}} 复制代码 9.删除用户
9.1 编写UserDao
//删除用户publicintdeleteUserById(Connection connection,Integer delId)throwsException; 复制代码 9.2 编写UserDaoImpl
//删除用户@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}; flag =BaseDao.execute(connection, pstm, sql, params);BaseDao.closeResource(null, pstm,null);}return flag;} 复制代码 9.3 编写UserService
//删除用户publicbooleandeleteUserById(Integer delId); 复制代码 9.4 编写UserServiceImpl
///删除用户@OverridepublicbooleandeleteUserById(Integer delId){Connection connection =null;boolean flag =false;try{ connection =BaseDao.getConnection(); connection.setAutoCommit(false);//开启JDBC事务管理 connection.commit();//胜利的话直接提交if(userDao.deleteUserById(connection,delId)>0) flag =true;}catch(Exception e){ e.printStackTrace();try{System.out.println("rollback=================="); connection.rollback();//失败的话回滚}catch(SQLException e1){ e1.printStackTrace();}}finally{BaseDao.closeResource(connection,null,null);}return flag;} 复制代码 9.5 编写UserServlet
在doget里添加elseif(method !=null&& method.equals("deluser")){this.delUser(req, resp);} 复制代码 删除方法如下://删除用户privatevoiddelUser(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String id = request.getParameter("uid");Integer delId =0;try{ delId =Integer.parseInt(id);}catch(Exception e){ delId =0;}HashMap<String,String> resultMap =newHashMap<String,String>();if(delId <=0){ resultMap.put("delResult","notexist");}else{UserService userService =newUserServiceImpl();if(userService.deleteUserById(delId)){ resultMap.put("delResult","true");}else{ resultMap.put("delResult","false");}}//把resultMap转换成json对象输出 response.setContentType("application/json");PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush(); outPrintWriter.close();} 复制代码 10.查看用户详细信息
10.1 编写UserDao
///根据id得到用户publicUsergetUserById(Connection connection,String id)throwsException; 复制代码 10.2 编写UserDaoImpl
///根据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}; rs =BaseDao.execute(connection, rs,pstm , sql, params);if(rs.next()){ user =newUser(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setUserPassword(rs.getString("userPassword")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setAddress(rs.getString("address")); user.setUserRole(rs.getInt("userRole")); user.setCreatedBy(rs.getInt("createdBy")); user.setCreationDate(rs.getTimestamp("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate")); user.setUserRoleName(rs.getString("userRoleName"));}BaseDao.closeResource(null, pstm, rs);}return user;} 复制代码 10.3 编写UserService
//根据id得到用户publicUsergetUserById(String id); 复制代码 10.4 编写UserServiceImpl
//根据id得到用户@OverridepublicUsergetUserById(String id){User user =null;Connection connection =null;try{ connection =BaseDao.getConnection(); user = userDao.getUserById(connection,id);}catch(Exception e){ e.printStackTrace(); user =null;}finally{BaseDao.closeResource(connection,null,null);}return user;} 复制代码 10.5 编写UserServlet
在doGET里添加elseif(method !=null&& method.equals("view")){this.getUserById(req, resp,"userview.jsp");} 复制代码 //根据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); request.setAttribute("user", user); request.getRequestDispatcher(url).forward(request, response);}} 复制代码 11.完善
11.1添加获取角色列表
在servlet里添加获取角色列表的方法
doGet添加elseif(method !=null&& method.equals("getrolelist")){this.getRoleList(req,resp);} 复制代码 然后写这个方法,就是得到角色列表,调用之前写好的业务层逻辑即可privatevoidgetRoleList(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{List<Role> roleList =null;RoleService roleService =newRoleServiceImpl(); roleList = roleService.getRoleList();//把roleList转换成json对象输出 response.setContentType("application/json");PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(roleList)); outPrintWriter.flush(); outPrintWriter.close();} 复制代码 11.2 查看相同用户编码的人是否存在
因为在填写的时候,使用了Ajax异步判断相同用户编码的人在数据库里是否已经存在,所以对其停止判断。
11.2.1 UserDao
///通过用户编码查找用户publicUsergetUserByCode(Connection connection,String userCode)throwsException; 复制代码 11.2.2 UserDaoImpl
@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}; rs =BaseDao.execute(connection, rs, pstm, sql, params);if(rs.next()){ user =newUser(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setUserPassword(rs.getString("userPassword")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setAddress(rs.getString("address")); user.setUserRole(rs.getInt("userRole")); user.setCreatedBy(rs.getInt("createdBy")); user.setCreationDate(rs.getTimestamp("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate"));}BaseDao.closeResource(null, pstm, rs);}return user;} 复制代码 11.2.3 userService
///根据用户编码查找用户publicUserselectUserCodeExist(String userCode); 复制代码 11.2.4 userServiceImpl
//根据用户编码查找用户@OverridepublicUserselectUserCodeExist(String userCode){Connection connection =null;User user =null;try{ connection =BaseDao.getConnection(); user = userDao.getUserByCode(connection, userCode);}catch(Exception e){ e.printStackTrace();}finally{BaseDao.closeResource(connection,null,null);}return user;} 复制代码 11.2.5 UserServlet
在doGet里添加判断elseif(method !=null&& method.equals("ucexist")){this.userCodeExist(request, response);} 复制代码 编写判断函数///判断用户编码的用户是否存在privatevoiduserCodeExist(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String userCode = request.getParameter("userCode");HashMap<String,String> resultMap =newHashMap<String,String>();if(StringUtils.isNullOrEmpty(userCode)){ resultMap.put("userCode","exist");}else{UserService userService =newUserServiceImpl();User user = userService.selectUserCodeExist(userCode);if(null!= user){ resultMap.put("userCode","exist");}else{ resultMap.put("userCode","notexist");}}//把resultMap转为json字符串以json的形式输出//配置上下文的输出类型 response.setContentType("application/json");//从response对象中获取往外输出的writer对象PrintWriter outPrintWriter = response.getWriter();//把resultMap转为json字符串 输出 outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush();//刷新 outPrintWriter.close();//关闭流} 复制代码 项目地址