目录
SMBMS(超市管理项目)
数据库:
项目如何搭建?
考虑是不是用maven? jar包,依赖
搭建项目准备工作
smbms项目静态资源+数据库下载 密码:smbms
-
搭建一个maven web 项目
-
配置Tomcat
-
测试项目是否能够跑起来
-
导入项目中需要的jar包;
jsp,Servlet,mysql驱动,jstl,stand…<dependencies> <!--servlet与jsp依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!--mysql驱动依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <!--jstl依赖与standard标签库--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies>
-
构建项目包结构
-
编写实体类
ROM映射:表-类映射 -
编写基础公共类
1、数据库配置文件(mysql5.xx和8.xx的编写有差异)
在Tomcat服务器lib目录下也要导mysql-connector-java.jar包
db.properties:
#mysql8.xx com.mysql.cj.jdbc.Driver #mysql5.xx com.mysql.jdbc.Driver driver=com.mysql.cj.jdbc.Drive #在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8 url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=false username=root password=123456
2、编写数据库的公共类
三种拿到db.properties文件的方法
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); InputStream is = ClassLoader.getSystemResourceAsStream("db.properties"); InputStream is = BaseDao.class.getResourceAsStream("/db.properties"); FileReader is = new FileReader("src/main/resources/db.properties"); properties.load(is);
package dao; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * 操作数据库的基类--静态类 * @author Administrator * */ public class BaseDao { static{//静态代码块,在类加载的时候执行 init(); } private static String driver; private static String url; private static String user; private static String password; //初始化连接参数,从配置文件里获得 public static void init(){ Properties params=new Properties(); String configFile = "database.properties"; InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(configFile); try { params.load(is); } catch (IOException e) { e.printStackTrace(); } driver=params.getProperty("driver"); url=params.getProperty("url"); user=params.getProperty("user"); password=params.getProperty("password"); } /** * 获取数据库连接 * @return */ public static Connection getConnection(){ Connection connection = null; try { Class.forName(driver); connection = DriverManager.getConnection(url, user, password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } /** * 查询操作 * @param connection * @param pstm * @param rs * @param sql * @param params * @return */ public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs, String sql,Object[] params) throws Exception{ pstm = connection.prepareStatement(sql); for(int i = 0; i < params.length; i++){ pstm.setObject(i+1, params[i]); } rs = pstm.executeQuery(); return rs; } /** * 更新操作 * @param connection * @param pstm * @param sql * @param params * @return * @throws Exception */ public static int execute(Connection connection,PreparedStatement pstm, String sql,Object[] params) throws Exception{ int updateRows = 0; pstm = connection.prepareStatement(sql); for(int i = 0; i < params.length; i++){ pstm.setObject(i+1, params[i]); } updateRows = pstm.executeUpdate(); return updateRows; } /** * 释放资源 * @param connection * @param pstm * @param rs * @return */ public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){ boolean flag = true; if(rs != null){ try { rs.close(); rs = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } if(pstm != null){ try { pstm.close(); pstm = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } if(connection != null){ try { connection.close(); connection = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } return flag; } }
3、编写字符编码过滤器
public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
然后在web.xml中注册
<!--字符编码过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.yingxu.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
-
导入静态资源
smbms项目静态资源+数据库下载 密码:smbms
放在webapp目录下
登录功能实现
-
编写前端页面
-
设置首页
1.设置欢迎首页
<!--设置欢迎页面--> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list>
-
编写dao层登录用户登录的接口
在dao中建立一个user包,在包中建一个UserDao接口,在接口中写
public interface UserDao { public User getLoginUser(Connection connection,String userCode) throws SQLException; }
-
编写dao层接口的实现类
编写UserDao接口的实现类UserDaoImpl
public class UserDaoImpl implements UserDao{ //持久层只做查询数据库的内容 @Override public User getLoginUser(Connection connection, String userCode) throws SQLException { PreparedStatement preparedStatement=null; ResultSet resultSet=null; User user=null; //判断是否连接成功 if (connection!=null){ String sql="select * from smbms_user where userCode=?"; Object[] params={userCode}; ResultSet execute = BaseDao.execute(connection, preparedStatement, resultSet, sql, params); if (execute.next()){ user = new User(); user.setId(execute.getInt("id")); user.setUserCode(execute.getString("userCode")); user.setUserName(execute.getString("userName")); user.setUserPassword(execute.getString("userPassword")); user.setGender(execute.getInt("gender")); user.setBirthday(execute.getDate("birthday")); user.setPhone(execute.getString("phone")); user.setAddress(execute.getString("address")); user.setUserRole(execute.getInt("userRole")); user.setCreatedBy(execute.getInt("createdBy")); user.setCreationDate(execute.getTimestamp("creationDate")); user.setModifyBy(execute.getInt("modifyBy")); user.setModifyDate(execute.getTimestamp("modifyDate")); } BaseDao.closeResource(null,preparedStatement,resultSet); } return user; } }
-
业务层接口
在service下建立user包,建立UserService接口
public interface UserService { //用户登录 public User login(String userCode,String userPassword); }
-
业务层接口的实现类
在service的user包中建立UserServiceImpl类
public class UserServiceImpl implements UserService{ //业务层都会调用dao层.所以我们要引入Dao层(重点) //只处理对应业务 private UserDao userDao; public UserServiceImpl() { userDao = new UserDaoImpl(); } @Override public User login(String userCode, String userPassword) { Connection connection = null; //通过业务层调用对应的具体数据库操作 User user = null; try { connection = BaseDao.getConnection(); user = userDao.getLoginUser(connection, userCode); } catch (Exception e) { e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return user; } // @Test // public void test(){ // UserServiceImpl userService = new UserServiceImpl(); // User login = userService.login("test", "111"); // System.out.println(login.getUserPassword()); // } }
-
编写util
在util包中建立Constants类
public class Constants { public final static String USER_SESSION="userSession"; }
-
编写Servlet
在Servlet包中创建user包,在user包中建立LoginServlet类
public class LoginServlet extends HttpServlet { //Servlet:控制层,调用业务层代码 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet--start...."); //获取用户名和密码 String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); //和数据库中的密码进行对比,调用业务层; UserService userService = new UserServiceImpl(); User user = userService.login(userCode, userPassword); //这里已经把登录的人给查出来了 System.out.println(userCode); System.out.println(userPassword); if (user!=null && userPassword.equals(user.getUserPassword())){ //查有此人,可以登录 //将用户的信息放到Session中; req.getSession().setAttribute(Constants.USER_SESSION,user); //跳转到主页重定向 resp.sendRedirect("jsp/frame.jsp"); }else {//查无此人,无法登录 //转发回登录页面,顺带提示它,用户名或者密码错误; req.setAttribute("error","用户名或者密码不正确"); req.getRequestDispatcher("login.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
注册Servlet
<!--注册登录页面的Servlet--> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.yingxu.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
-
测试访问,保证以上功能可以成功
登录功能优化
注销功能
思路:移除session,返回登录页面,servlet.user下创建LogoutServlet类
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
在web.xml中注册注销servlet
<!--移除session-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.yingxu.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截器
编写一个过滤器,并注册
在filter下创建SysFilter类
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
if (user==null){
resp.sendRedirect(req.getContextPath()+"/error.jsp");
}else {
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
在web.xml中注册
<!-- 用户登录过滤器 -->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.yingxu.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
测试,登录,注销,权限,都要保证OK
密码修改
自顶向下设计,自底向上实现
先写基本逻辑,前端在测试后端的路上完善的
- 为了实这个功能需要自底向上逐一实现功能,修改密码需要更新数据库的相关行,所以这就需要dao层去进行增删改查操作数据
- dao层的需要的当前的一些信息,比如用户名,当前的密码,要修改的密码,所以这些就要dao层去从Service层获取这些参数
- service需要获取从Servlet层传过来的数据进行相应的处理,验证,核算,然后将最终的信息传递给dao层
- 而servlet直接与前端接触,返回当前页面上传递而来的用户输入触发的参数,转发到不同的页面,交给不同的service来处理这些请求意味着先从dao层开始写,分模块,先写接口,再写接口的实现类,依次写service和servlet,最后注册这个servlet,最后测试并完善前端页面
-
编写dao层用户修改密码的接口UserDao
在dao.user.UserDao的接口下增加updatepwd
//修改当前用户密码 //增删改都会影响数据库的变化,所以是返回int类型,说明有几行受到了影响 public int updatePwd(Connection connection,int id,String userPassword) throws SQLException;
-
编写dao层用户修改密码的接口实现类
UserDaoImpl下增加
//修改当前用户密码 //增删改都会影响数据库的变化,所以是返回int类型,说明有几行受到了影响 @Override public int updatePwd(Connection connection, int id, String userPassword) throws SQLException { int execute=0; PreparedStatement preparedStatement=null; if (connection!=null){ String sql="update smbms_user set userPassword=? where id=?"; Object[] params={userPassword,id}; execute = BaseDao.execute(connection, preparedStatement, sql, params); } BaseDao.closeResource(null,preparedStatement,null); return execute; }
-
编写业务层Service的用户修改密码的接口
UserService下增加
//根据用户id修改密码 public boolean updatePwd(int id,String password);
-
编写业务层Service的用户修改密码的接口实现类
UserServiceImpl下增加
//根据用户id修改密码 //通过返回的参数flag判断是否修改成功 @Override public boolean updatePwd(int id, String password) { Connection connection=null; boolean flag=false; try { connection = BaseDao.getConnection(); int updatePwd = userDao.updatePwd(connection, id, password); if (updatePwd>0){ flag=true; } } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return flag; }
-
编写修改密码的Servlet类
servlet.user 下新增UserServlet类
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //实现复用~~~~~~ //实现Servlet复用,实现复用需要提取出方法,然后在doGet函数中调用即可 // 想添加新的增删改查,直接用if(method.equals("savepwd") && method != null); String method = req.getParameter("method"); if (method.equals("savepwd") && method!=null){ updatePwd(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //在doGet外写复用方法 public void updatePwd(HttpServletRequest req, HttpServletResponse resp){ //从session中获得用户id,这里的attribute包括了用户的所用信息 Object attribute = req.getSession().getAttribute(Constants.USER_SESSION); //获得新密码 String newpassword = req.getParameter("newpassword"); boolean flag=false; //判断是否有这个用户是否存在,以及新密码不为空 if (attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User) attribute).getId(), newpassword); if (flag){ req.setAttribute("message","修改密码成功,请退出后重新登录"); // 密码修改成功,移除session(移除后不能再次修改密码,建议不移除) req.getSession().removeAttribute(Constants.USER_SESSION); }else { // 密码修改失败 req.setAttribute("message","密码修改失败请重新输入"); } }else { // 密码修改有问题 req.setAttribute("message","新密码设置错误请重新输入"); } try { req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
-
在web.xml中注册这个servlet
<!--注册UserServlet页面--> <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.yingxu.servlet.user.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/jsp/user.do</url-pattern> </servlet-mapping>
-
如果旧密码输入框一直报错(打开pwdmodify.js 注释下面这段)
-
测试
优化密码修改使用Ajax
阿里巴巴的fastjson.jar包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
设置session过期时间
<!--默认session过期时间:真实业务需求,1天后自动注销-->
<session-config>
<session-timeout>1440</session-timeout>
</session-config>
编写验证旧密码的servlet类,还是servlet方法复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//实现复用~~~~~~
//实现Servlet复用,实现复用需要提取出方法,然后在doGet函数中调用即可
// 想添加新的增删改查,直接用if(method.equals("savepwd") && method != null);
String method = req.getParameter("method");
if (method.equals("savepwd") && method!=null){
this.updatePwd(req,resp);
}else if (method!=null && method.equals("pwdmodify")){
this.modifyPwd(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
//修改密码
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
//从session中获得用户id,这里的attribute包括了用户的所用信息
Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
//获得新密码
String newpassword = req.getParameter("newpassword");
boolean flag=false;
//判断是否有这个用户是否存在,以及新密码不为空
if (attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) attribute).getId(), newpassword);
if (flag){
req.setAttribute("message","修改密码成功,请退出后重新登录");
// 密码修改成功,移除session(移除后不能再次修改密码,建议不移除)
req.getSession().removeAttribute(Constants.USER_SESSION);
}else {
// 密码修改失败
req.setAttribute("message","密码修改失败请重新输入");
}
}else {
// 密码修改有问题
req.setAttribute("message","新密码设置错误请重新输入");
}
try {
req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//数证旧密码,session中有用户的密码
public void modifyPwd(HttpServletRequest req, HttpServletResponse resp){
//从session中获得用户的旧密码,这里的attribute包括了用户的所用信息
Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
//从前端输入的页面中获得输入的旧密码
String oldpassword = req.getParameter("oldpassword");
//万能的Map:结果集
Map<String, String> resultMap = new HashMap<String, String>();
if (attribute==null){//取到的session为空,意味着session过期了
resultMap.put("result","sessionerror");
}else if (StringUtils.isNullOrEmpty(oldpassword)){//如果输入的旧密码为空
resultMap.put("result","error");
}else {//session不为空,输入的旧密码也不为空,则取出当前旧密码与之比较
String userPassword = ((User) attribute).getUserPassword();//session 中用户的密码
if (oldpassword.equals(userPassword)){
resultMap.put("result","true");
}else {
resultMap.put("result","false");
}
}
try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
/*
* resultMap = ["result","sessionerror","result",error]
* json格式={key:value}
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
用户管理模块实现
-
导入分页的util工具类-PageSupport
public class PageSupport { //当前页码-来自于用户输入 private int currentPageNo = 1; //总数量(表) private int totalCount = 0; //页面容量 private int pageSize = 0; //总页数-totalCount/pageSize(+1) private int totalPageCount = 1; public int getCurrentPageNo() { return currentPageNo; } public void setCurrentPageNo(int currentPageNo) { if(currentPageNo > 0){ this.currentPageNo = currentPageNo; } } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { if(totalCount > 0){ this.totalCount = totalCount; //设置总页数 this.setTotalPageCountByRs(); } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize > 0){ this.pageSize = pageSize; } } public int getTotalPageCount() { return totalPageCount; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public void setTotalPageCountByRs(){ if(this.totalCount % this.pageSize == 0){ this.totalPageCount = this.totalCount / this.pageSize; }else if(this.totalCount % this.pageSize > 0){ this.totalPageCount = this.totalCount / this.pageSize + 1; }else{ this.totalPageCount = 0; } } }
-
用户列表页面导入-userlist.jsp
1、获取用户数量
-
编写Dao层的接口UserDao
//根据用户名或者角色查询用户总数 public int getUserCount(Connection connection,String username ,int userRole)throws SQLException, Exception;
-
编写Dao层的实现类UserDaoImpl
//根据用户名或者角色查询用户总数 @Override public int getUserCount(Connection connection, String username, int userRole) throws SQLException, Exception { PreparedStatement preparedStatement=null; ResultSet resultSet=null; //不能使用Integer去包装,Integer可以为null,这里返回的的结果是始终是int类型 int count=0; if (connection!=null){ //因为根据用户角色或用户名的条件查询,需要使用StringBuffer去拼接字符串 StringBuffer sql = new StringBuffer(); sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole=r.id"); //使用list集合去封装参数 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); } Object[] params = list.toArray(); resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), params); if (resultSet.next()){ count = resultSet.getInt("count");//这里count是sql里的as count } BaseDao.closeResource(null,preparedStatement,resultSet); } return count; }
-
编写service层的接口UserService
//根据用户名或用户角色查询用户总数 public int getUserCount(String username,int userRole) throws SQLException;
-
编写service层的实现类UserServiceImpl
//根据用户名或用户角色查询用户总数 @Override public int getUserCount(String username, int userRole) throws SQLException { Connection connection=null; int count=0; try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, username, userRole); } catch (Exception e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return count; }
2、获取用户列表
-
UserDao
//查询用户列表 //通过条件查询-userList public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;
-
UserDaoImpl
@Override public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; List<User> userList = new ArrayList<User>(); if(connection != null){ StringBuffer sql = new StringBuffer(); //当查询语句有order by时u.*,r.roleName 要加上前缀u.,r. 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); } //在数据库中,分页显示 limit startIndex,pageSize;总数 //当前页 (当前页-1)*页面大小 //0,5 1,0 01234 //5,5 5,0 56789 //10,5 10,0 10~ sql.append(" order by u.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 List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
-
UserServiceImpl
//根据条件查询用户列表 @Override public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { Connection 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) { e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return userList; }
3、获取角色操作
为了我们的职责分明,需要将角色列表另一起一个包,便于代码的维护
分别在dao,service下创捷role文件夹
-
RoleDao
public interface RoleDao { //获取角色列表 public List<Role> getRoleList(Connection connection) throws SQLException; }
-
RoleDaoIpml
public class RoleDaoImpl implements RoleDao{ //获取角色列表 @Override public List<Role> getRoleList(Connection connection) throws SQLException { PreparedStatement preparedStatement=null; ResultSet resultSet=null; Role role=null; ArrayList<Role> roles = new ArrayList<>(); if (connection!=null){ String sql="select * from smbms_role"; Object[] params={}; resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params); while (resultSet.next()){ role = new Role(); role.setId(resultSet.getInt("id")); role.setRoleCode(resultSet.getString("roleCode")); role.setRoleName(resultSet.getString("roleName")); roles.add(role); } BaseDao.closeResource(null,preparedStatement,resultSet); } return roles; } }
-
RoleService
public interface RoleService { //得到用户角色表 public List<Role> getRoleList(); }
-
RoleServiceIpml
public class RoleServiceImpl implements RoleService{ //引入Dao private RoleDao roleDao; public RoleServiceImpl() { roleDao = new RoleDaoImpl(); } //得到用户角色表 @Override public List<Role> getRoleList() { Connection connection=null; List<Role> list=null; try { connection = BaseDao.getConnection(); list = roleDao.getRoleList(connection); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return list; } // @Test // public void test(){ // RoleServiceImpl roleService = new RoleServiceImpl(); // List<Role> roleList = roleService.getRoleList(); // for (Role role : roleList) { // System.out.println(role.getRoleName()); // } // } }
4、用户显示的Servlet
- 获取用户前端的数据(查询)
- 判断请求是否需要执行,看参数的值判断
- 为了实现分页,需要计算出当前页面和总页面,页面大小…
- 用户列表展示
- 返回前端
UserServlet类doGet方法里:
else if (method.equals("query") && method!=null){
//用户管理模块页面查询
this.query(req,resp);
}
//用户管理模块页面查询(重点、难点)
public void query(HttpServletRequest req, HttpServletResponse resp){
//接收前端传来的参数
//用户名
String queryUserName = req.getParameter("queryname");
//用户角色
String temp = req.getParameter("queryUserRole");//从前端传回来的用户角色码不知是否为空或者是有效角色码,所以暂存起来
//当前页
String pageIndex = req.getParameter("pageIndex");
int queryUserRole=0;//用户角色=0:--请选择--,用户角色=1:系统管理员,...
//获取用户列表
UserServiceImpl userService = new UserServiceImpl();
List<User> userList = null;
//第一此请求肯定是走第一页,页面大小固定的
//设置页面容量
int pageSize = 5;//把它设置在配置文件里,后面方便修改
//当前页码
int currentPageNo = 1;
if(queryUserName == null){
queryUserName = "";
}
if(temp != null && !temp.equals("")){
queryUserRole = Integer.parseInt(temp);
}
if(pageIndex != null) {
currentPageNo = Integer.parseInt(pageIndex);
}
//获取用户总数(分页 上一页:下一页的情况)
//总数量(表)
int totalCount = 0;
try {
totalCount = userService.getUserCount(queryUserName,queryUserRole);
} catch (SQLException e) {
e.printStackTrace();
}
//总页数支持
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(pageSize);
pageSupport.setTotalCount(totalCount);
//(totalCount+pageSize-1/pageSize)取整
int totalPageCount =pageSupport.getTotalPageCount();//总共有几页
//控制首页和尾页
//如果页面小于 1 就显示第一页的东西
if(currentPageNo < 1) {
currentPageNo = 1;
}else if(currentPageNo > totalPageCount) {//如果页面大于了最后一页就显示最后一页
currentPageNo =totalPageCount;
}
System.out.println("queryUserName"+"="+queryUserName);
System.out.println("queryUserRole"+"="+queryUserRole);
System.out.println("currentPageNo"+"="+currentPageNo);
System.out.println("pageSize"+"="+pageSize);
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
System.out.println("userList"+userList);
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);
//返回前端
try {
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
小黄鸭调试法自查
思路:
5、用户管理模块的增删改查
UserDao
//增加用户信息
public int addUser(Connection connection,User user) throws SQLException;
//通过用户id删除用户信息
public int deleteUserById(Connection connection, Integer delId) throws SQLException;
//通过userId查看当前用户信息
public User getUserById(Connection connection, String id)throws Exception;
//修改用户信息
public int updateUser(Connection connection, User user)throws Exception;
UserDaoImpl
//增加用户信息
@Override
public int addUser(Connection connection, User user) throws SQLException {
PreparedStatement preparedStatement=null;
int execute=0;
if (connection!=null){
String sql="insert into smbms_user(userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate) values(?,?,?,?,?,?,?,?,?,?)";
Object[] params={user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreationDate()};
execute = BaseDao.execute(connection, preparedStatement, sql, params);
}
BaseDao.closeResource(null,preparedStatement,null);
return execute;
}
//通过用户id删除用户信息
@Override
public int deleteUserById(Connection connection, Integer delId) throws SQLException {
PreparedStatement preparedStatement=null;
int execute=0;
if (connection!=null){
String sql="delete from smbms_user where id=?";
Object[] params={delId};
execute = BaseDao.execute(connection, preparedStatement, sql, params);
}
BaseDao.closeResource(null,preparedStatement,null);
return execute;
}
//修改用户信息
@Override
public int updateUser(Connection connection, User user) throws Exception {
PreparedStatement preparedStatement=null;
int execute=0;
if (connection!=null){
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()};
execute = BaseDao.execute(connection, preparedStatement, sql, params);
}
BaseDao.closeResource(null,preparedStatement,null);
return execute;
}
//通过userId查看当前用户信息
@Override
public User getUserById(Connection connection, String id) throws Exception {
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
User user=null;
if (connection!=null){
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};
resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);
while (resultSet.next()){
user = new User();
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"));
user.setUserRoleName(resultSet.getString("userRoleName"));
}
BaseDao.closeResource(null,preparedStatement,resultSet);
}
return user;
}
UserService
//查询用户编码
//查询用户是否存在,存在就不能增加用户,不存在就增加用户
public User selectUserCodeExist(String userCode);
//增加用户
public Boolean add(User user);
//根据用户id删除用户
public boolean deleteUserById(Integer delId);
//根据用户id得到当前用户
public User getUserById(String id);
//修改用户信息
public Boolean updateUser(User user);
UserServiceImpl
//查询用户编码
//查询用户是否存在,存在就不能增加用户,不存在就增加用户
@Override
public User selectUserCodeExist(String userCode) {
Connection connection = null;
User users=null;
try {
connection = BaseDao.getConnection();
users = userDao.getLoginUser(connection, userCode);
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return users;
}
//增加用户
@Override
public Boolean add(User user) {
Connection connection = null;
int add=0;
boolean flag=false;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
add = userDao.addUser(connection, user);
connection.commit();
if (add>0){
flag=true;
System.out.println("add success");
}else {
System.out.println("add failed");
}
} catch (SQLException e) {
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();//失败就回滚
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
//根据用户id删除用户
@Override
public boolean deleteUserById(Integer delId) {
Connection connection=null;
int deleteUserById=0;
boolean flag=false;
try {
connection = BaseDao.getConnection();
deleteUserById = userDao.deleteUserById(connection, delId);
if (deleteUserById>0){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
//根据用户id得到当前用户
@Override
public User getUserById(String id) {
User user = new User();
Connection connection=null;
try {
connection=BaseDao.getConnection();
user = userDao.getUserById(connection,id);
} catch (Exception e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
//修改用户信息
@Override
public Boolean updateUser(User user) {
Connection connection = null;
int updateUser=0;
boolean flag=false;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
updateUser = userDao.updateUser(connection, user);
connection.commit();
if (updateUser>0){
flag=true;
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();//失败就回滚
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
增删改查UserServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//实现复用~~~~~~
//实现Servlet复用,实现复用需要提取出方法,然后在doGet函数中调用即可
// 想添加新的增删改查,直接用if(method.equals("savepwd") && method != null);
String method = req.getParameter("method");
if (method.equals("savepwd") && method!=null){
//修改密码
this.updatePwd(req,resp);
}else if (method.equals("pwdmodify") && method!=null){
//数证旧密码
this.pwdModify(req,resp);
}else if (method.equals("query") && method!=null){
//用户管理模块页面查询
this.query(req,resp);
}else if (method.equals("getrolelist") && method!=null){
//查询用户角色表
this.getRoleList(req,resp);
} else if (method.equals("ucexist") && method!=null){
//判断用户编码是否存在(存在就不能增加用户,不存在就增加用户)
this.isUserExist(req,resp);
}else if (method.equals("add") && method!=null){
//增加用户
this.add(req,resp);
}else if(method.equals("deluser") && method!=null){
//删除用户
this.delUser(req, resp);
}else if(method.equals("view") && method!=null){
//通过用户id得到用户
this.getUserById(req, resp,"/jsp/userview.jsp");
}else if(method.equals("modify") && method!=null){
//通过用户id得到用户
this.getUserById(req, resp,"/jsp/usermodify.jsp");
} else if(method.equals("modifyexe") && method!=null){
//修改用户信息
this.updateUser(req, resp);
}
}
//查询用户角色表
public void getRoleList(HttpServletRequest req, HttpServletResponse resp){
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
try {
//把roleList转换成json对象输出
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.write(JSONArray.toJSONString(roleList));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//判断用户编码是否存在(存在就不能增加用户,不存在就增加用户)
public void isUserExist(HttpServletRequest req, HttpServletResponse resp) {
//获取前端参数
String userCode = req.getParameter("userCode");
//使用Map封装数据
HashMap<String, String> resultMap = new HashMap<String, String>();
if(StringUtils.isNullOrEmpty(userCode)){
//userCode == null || userCode.equals("")
//如果输入的这个编码为空或者不存在,说明可用
resultMap.put("userCode", "exist");
}else{//如果输入的编码不为空,则需要去找一下是否存在这个用户
UserService userService = new UserServiceImpl();
User user = userService.selectUserCodeExist(userCode);
if(user!=null){
resultMap.put("userCode","exist");
}else{
resultMap.put("userCode", "notexist");
}
}
try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
/*
* resultMap = ["result","sessionerror","result",error]
* json格式={key:value}
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//增加用户
public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
System.out.println("当前正在执行增加用户操作");
//从前端得到页面的请求的参数即用户输入的值
String userCode = req.getParameter("userCode");
String userName = req.getParameter("userName");
String userPassword = req.getParameter("userPassword");
//String ruserPassword = req.getParameter("ruserPassword");
String gender = req.getParameter("gender");
String birthday = req.getParameter("birthday");
String phone = req.getParameter("phone");
String address = req.getParameter("address");
String userRole = req.getParameter("userRole");
//把这些值塞进一个用户属性中
User user = new User();
user.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
//查找当前正在登陆的用户的id
if (o != null) {
user.setCreatedBy(((User) o).getId());
}
user.setCreationDate(new Date());
UserServiceImpl userService = new UserServiceImpl();
Boolean flag = userService.add(user);
//如果添加成功,则页面转发,否则重新刷新,再次跳转到当前页面
if(flag){
resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
}else{
req.getRequestDispatcher("/jsp/useradd.jsp").forward(req,resp);
}
}
//删除用户,需要当前的Id,来找到这个用户然后删除
public void delUser(HttpServletRequest req, HttpServletResponse resp){
String id = req.getParameter("uid");
Integer delId = 0;
try{
delId = Integer.parseInt(id);
}catch (Exception e) {
delId = 0;
}
//需要判断是否能删除成功
HashMap<String, String> resultMap = new HashMap<String, String>();
if(delId <= 0){
resultMap.put("delResult", "notexist");
}else{
UserService userService = new UserServiceImpl();
if(userService.deleteUserById(delId)){
resultMap.put("delResult", "true");
}else{
resultMap.put("delResult", "false");
}
}
//把resultMap转换成json对象输出
try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//通过id得到用户信息
private void getUserById(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
String id = req.getParameter("uid");
if(!StringUtils.isNullOrEmpty(id)){
//调用后台方法得到user对象
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
req.setAttribute("user", user);
req.getRequestDispatcher(url).forward(req, resp);
}
}
//修改用户信息
private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//需要拿到前端传递进来的参数
String id = req.getParameter("uid");;
String userName = req.getParameter("userName");
String gender = req.getParameter("gender");
String birthday = req.getParameter("birthday");
String phone = req.getParameter("phone");
String address = req.getParameter("address");
String userRole = req.getParameter("userRole");
//创建一个user对象接收这些参数
User user = new User();
user.setId(Integer.valueOf(id));
user.setUserName(userName);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setModifyDate(new Date());
//调用service层
UserServiceImpl userService = new UserServiceImpl();
Boolean flag = userService.updateUser(user);
//判断是否修改成功来决定跳转到哪个页面
if(flag){
resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
}else{
req.getRequestDispatcher("/jsp/usermodify.jsp").forward(req, resp);
}
}