实现用户管功能
刚刚访问密码直接走前端
现在要发起请求走Servlet,Servlet处理后返回前端页面
Servlet
- 处理请求
- 调用业务
- 返回页面
业务要查询用户列表,查询角色列表,为了实现分页,需查询pageSize总数。查询从Service层到Dao层,Dao层从数据库里面查
1、导入分页的工具类
2、用户列表页面导入
为了我们职责统一,可以把角色的操作单独放在一个包中,和Pojo类一一对应
1、获取用户数量
UserDao
//查询用户总数public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
//通过条件查询-userlistpublic List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws Exception;
- UserDaoImpl
//根据用户名或者角色查询用户总数public int getUserCount(Connection connection, String username, int userRole) throws SQLException {PreparedStatement pstm=null;ResultSet rs=null;int count=0;if(connection!=null){StringBuffer sql=new StringBuffer();sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole=r.id");ArrayList<Object> list=new ArrayList<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);}//list转化为数组Object[] params=list.toArray();System.out.println("UserDaoImpl->getUserCount:"+sql.toString());rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);if(rs.next()){//从结果集中获取最终的数量count = rs.getInt("count");}BaseDao.closeResource(null,pstm,rs);}return count;}public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {// TODO Auto-generated method stubPreparedStatement pstm = null;ResultSet rs = null;List<User> userList = new ArrayList<User>();if(connection != null){StringBuffer sql = new StringBuffer();sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");List<Object> list = new ArrayList<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("sql ----> " + sql.toString());rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);while(rs.next()){User _user = new User();_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;}
- UserService
//查询记录数public int getUserCount(String userName,int userRole);public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
- UserServiceImpl
//查询记录数public int getUserCount(String userName, int userRole) {Connection connection = null;int count=0;try {connection=BaseDao.getConnection();count=userDao.getUserCount(connection,userName,userRole);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection,null,null);}return count;}public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {// TODO Auto-generated method stubConnection connection = null;List<User> userList = null;System.out.println("queryUserName ---- > " + queryUserName);System.out.println("queryUserRole ---- > " + queryUserRole);System.out.println("currentPageNo ---- > " + currentPageNo);System.out.println("pageSize ---- > " + pageSize);try {connection = BaseDao.getConnection();userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{BaseDao.closeResource(connection, null, null);}return userList;}@Testpublic void test1(){UserServiceImpl userService = new UserServiceImpl();int userCount=userService.getUserCount(null,0);System.out.println(userCount);}
2、获取角色数量
在Dao层和Service层都新增role部分
RoleDao
public interface RoleDao {//获取角色列表public List<Role> getRoleList(Connection connection)throws SQLException;
}
RoleDaoImpl
package com.lding.dao.role;import com.lding.dao.BaseDao;
import com.lding.pojo.Role;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;/*** @program: SMBMS* @description:* @author: 王丁* @date: 2021-11-09 15:39**/
public class RoleDaoImpl implements RoleDao{public List<Role> getRoleList(Connection connection) throws SQLException {PreparedStatement pstm = null;ResultSet rs = null;ArrayList<Role> roleList = new ArrayList<Role>();if (connection != null) {String sql = "select * from smbms_role";Object[] params = {};rs = BaseDao.execute(connection, pstm, rs, sql, params);while (rs.next()) {Role _role = new Role();_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;}
}
RoleService
public interface RoleService {//获取角色列表public List<Role> getRoleList();
}
RoleServiceImpl
public class RoleServiceImpl implements RoleService {//引入Daoprivate RoleDao roleDao;public RoleServiceImpl(){roleDao=new RoleDaoImpl();}public List<Role> getRoleList() {Connection connection = null;List<Role> roleList=null;try {connection=BaseDao.getConnection();roleList = roleDao.getRoleList(connection);} catch (SQLException e) {}finally {BaseDao.closeResource(connection,null,null);}return roleList;}@Testpublic void test(){RoleServiceImpl roleService=new RoleServiceImpl();List<Role> roleList=roleService.getRoleList();for(Role role:roleList){System.out.println(role.getRoleName());}}
}
和之前的实现思路一样,我们先在Dao层实现对数据库中信息的提取,然后在Service层直接调用Dao层中的方法
以角色查询为例,在DaoImpl实现方法中创建PrepareStatement预编译对象,rs结果集对象,
roleList存储角色列表,通过传过来的连接,编写查询role的sql语句,然后执行Dao的execute方法
得到rs结果集后遍历rs结果集,取出每个role对象,存储到roleList,然后返回roleList
RoleServiceImpl直接调用Dao层中的getRoleList方法
在service层创建与数据库的连接,然后调用getRoleList方法得到查询结果 最后关闭资源
拿到前端列表后,将所有数据通过req.setAttribute的方式存入属性中,前端也可以通过这个属性获取。
最后通过请求转发req.getRequestDispatcher(“userlist.jsp”).forward(req,resp);返回前端页面。
UserServlet完整代码
package com.lding.servlet.user;import com.alibaba.fastjson.JSONArray;
import com.lding.pojo.Role;
import com.lding.pojo.User;
import com.lding.service.role.RoleService;
import com.lding.service.role.RoleServiceImpl;
import com.lding.service.user.UserServiceImpl;
import com.lding.util.Constants;
import com.lding.util.PageSupport;
import com.mysql.jdbc.StringUtils;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @program: SMBMS* @description:* @author: 王丁* @date: 2021-11-06 20:49**/
public class UserServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String method = req.getParameter("method");if(method!=null&&method.equals("savepwd")){updatePwd(req,resp);}else if(method!=null&&method.equals("pwdmodify")){pwdModify(req,resp);}else if(method.equals("query")&&method!=null){this.query(req,resp);}}//重点难点public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//查询用户列表//从前端获取数据String queryUserName=req.getParameter("queryname");String temp=req.getParameter("queryUserRole");String pageIndex=req.getParameter("pageIndex");List<User> userList=null;int queryUserRole=0;//获取用户列表UserServiceImpl userService=new UserServiceImpl();//第一次走这个请求,一定是第一页,页面大小是固定的int pageSize=5; //可以把这个写在配置文件中,方便后期修改int currentPageNo=1;if(queryUserName==null){queryUserName="";}if(temp!=null&&!temp.equals("")){queryUserRole=Integer.parseInt(temp);//给查询赋值0,1,2,3}if(pageIndex!=null){currentPageNo = Integer.parseInt(pageIndex);}//获取用户的总数(分页:上一页,下一页)int totalCount= userService.getUserCount(queryUserName, queryUserRole);//总页数支持PageSupport pageSupport=new PageSupport();pageSupport.setCurrentPageNo(currentPageNo);pageSupport.setPageSize(pageSize);pageSupport.setTotalCount(totalCount);int totalPageCount=pageSupport.getTotalPageCount();//控制首页和尾页//如果页面要小于1了,就显示第一页的东西if(currentPageNo<1){currentPageNo=1;}else if(currentPageNo>totalPageCount){currentPageNo=totalPageCount;}//获取用户列表展示userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);req.setAttribute("userList",userList);//拿到角色列表RoleServiceImpl roleService = new RoleServiceImpl();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);//返回前端req.getRequestDispatcher("userlist.jsp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}public void updatePwd(HttpServletRequest req, HttpServletResponse resp){//获取参数往上提交//从Session中拿用户IDObject user = req.getSession().getAttribute(Constants.USER_SESSION);String newpassword = req.getParameter("newpassword");boolean flag=false;if(user!=null&&newpassword!=null){UserServiceImpl userService = new UserServiceImpl();flag= userService.updatePwd(((User) user).getId(), newpassword);if(flag){req.setAttribute("message","修改密码成功,请退出重新登陆");//密码修改成功 移除当前Sessionreq.getSession().removeAttribute(Constants.USER_SESSION);//过滤器自动判断Session为null 重新回登陆页面}else{req.setAttribute("message","密码修改失败");}}else{req.setAttribute("message","新密码有问题");}try {req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void pwdModify(HttpServletRequest req, HttpServletResponse resp){//从Session里面拿IDObject o=req.getSession().getAttribute(Constants.USER_SESSION);String oldpassword=req.getParameter("oldpassword");//万能的Map :结果集Map<String,String> resultMap=new HashMap<String, String>();if(o==null){//Session失效了,session过期了resultMap.put("result","sessionerror");}else if(StringUtils.isNullOrEmpty(oldpassword)){resultMap.put("result","error");}else{String userPassword=((User)o).getUserPassword();//Session中的用户的密码if(oldpassword.equals(userPassword)){resultMap.put("result","true");}else{resultMap.put("result","false");}}resp.setContentType("application/json");try {PrintWriter writer=resp.getWriter();//JSONArray 阿里巴巴的JSON工具类,转换格式/*resultMap=["result","sessionerror"]转化为Json格式={key:value}*/writer.write(JSONArray.toJSONString(resultMap));writer.flush();writer.close();} catch (IOException e) {e.printStackTrace();}}}