12.SMBMS
源码下载
一,项目搭建-前期准备
1. 创建mavenweb项目
2. 添加Tomcat
3. 测试localhost访问
4. 导入jar包
-
servlet-api jsp-api mysql-connector-java jstl-api standard
2.maven项目导入pom.xml
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- JSP依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- jdbc依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- jstl标签依赖 -->
<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>
<!-- 单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- 阿里fastjson依赖-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
5. 创建项目结构

6. 编写实体类
1. ORM映射: 表-;类映射
7. 编写基础公共类
-
数据库配置文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://192.168.0.201:3306/smbms?useUnicode=true&characterEncoding=utf-8 username=root password=123456
-
编写工具类
-
数据库连接, 增删改查操作(BaseDao)
package com.ccc.dao; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class BaseDao { private static String driver = null; private static String url = null; private static String user = null; private static String pwd = null; private static Connection conn = null; //初始化变量, 加载驱动 static { Properties properties = new Properties(); InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); try { properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); pwd = properties.getProperty("pwd"); //加载驱动 Class.forName(driver); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } //获取连接connection public static Connection getConn(){ try { conn = DriverManager.getConnection(url, user, pwd); } catch (SQLException e) { e.printStackTrace(); } return conn; } //通用查询方法, 返回结果集 public static ResultSet excute(Connection connection, PreparedStatement pst1,ResultSet resultSet,String sql,Object[] params){ try { pst1 = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { pst1.setObject(i+1,params[i]); } resultSet = pst1.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return resultSet; } //通用修改方法, 返回影响条数 public static int excute(Connection connection, PreparedStatement pst1,String sql,Object[] params){ int row = 0; try { pst1 = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { pst1.setObject(i+1,params[i]); } row = pst1.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return row; } //关闭连接方法 public static boolean closeAll(Connection connection, PreparedStatement pst,ResultSet rs){ boolean flag = true; if (rs!=null){ try { rs.close(); rs = null; } catch (SQLException e) { flag =false; e.printStackTrace(); } } if (pst!=null){ try { pst.close(); pst = null; } catch (SQLException e) { flag =false; e.printStackTrace(); } } if (connection!=null){ try { connection.close(); connection = null; } catch (SQLException e) { flag =false; e.printStackTrace(); } } return flag; } }
-
-
编写字符编码过滤器
public class CharacterFilter 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"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
8. 导入静态资源
二,登录功能实现
1. 获取登录用户UserDao
public interface UserDao {
public User getLoginUser(Connection conn, String userCode);
}
public class UserDaoImpl implements UserDao {
@Override
public User getLoginUser(Connection conn, String userCode) {
PreparedStatement pst =null;
ResultSet rs = null;
User user =null;
if (conn!=null){
String sql = "select * from smbms_user where userCode = ?";
Object[] params = {userCode};
ResultSet resultSet = BaseDao.excute(conn, pst, rs, sql, params);
try {
while (resultSet.next()){
user = new User();
user.setUserID(resultSet.getInt("id"));
user.setUserCode(resultSet.getString("userCode"));
user.setUserName(resultSet.getString("userName"));
user.setUserPassword(resultSet.getString("userPassword"));
user.setUserGender(resultSet.getInt("gender"));
user.setUserBirthday(resultSet.getTimestamp("birthday"));
user.setUserPhone(resultSet.getString("phone"));
user.setUserAddress(resultSet.getString("address"));
user.setUserRole(resultSet.getInt("userRole"));
user.setUserCreateBy(resultSet.getInt("createdBy"));
user.setUserCreationDate(resultSet.getTimestamp("creationDate"));
user.setUserModifyBy(resultSet.getInt("modifyBy"));
user.setUserModifyDate(resultSet.getTimestamp("modifyDate"));
}
}catch (SQLException throwables) {
System.out.println("UserDaoImpl-遍历resulset错误");
throwables.printStackTrace();
}finally {
//不用关Conn, 连接可能设计业务, 到事物里面关
BaseDao.closeAll(null,pst,resultSet);
}
}else {
System.out.println("UserDaoImpl没获取到Connection");
}
return user;
}
}
2. UserService
public interface UserService {
//只负责登录
public User userLogin(String userCode, String userPwd);
}
public class UserServiceImpl implements UserService{
private static Connection conn = null;
UserDao dao = null;
public UserServiceImpl() {
dao = new UserDaoImpl();
}
@Override
public User userLogin(String userCode, String userPwd) {
User user = null;
try {
conn = BaseDao.getConn();
user = dao.getLoginUser(conn, userCode);
}catch (Exception e){
e.printStackTrace();
}finally {
BaseDao.closeAll(conn,null,null);
}
//验证密码
if (user!=null &&userPwd.equals(user.getUserPassword())){
return user;
}
return null;
}
}
3. 处理登录请求
1. 登录Servlet
```java
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
UserService service = new UserServiceImpl();
User user = service.userLogin(userCode, userPassword);
if (user!=null){
req.getSession().setAttribute(Constant.USER_SESSION,user);
resp.sendRedirect(req.getContextPath()+"/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);
}
}
```
2. web.xml配置
```xml
<!--登录-->
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.ccc.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
```
4. 登出功能
-
servlet
```java public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //登出, 1 清除session , 2重定向到登录 req.getSession().setAttribute(Constant.USER_SESSION,null); resp.sendRedirect(req.getContextPath()+"/login.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ```
-
web
```xml <servlet> <servlet-name>logout</servlet-name> <servlet-class>com.ccc.servlet.user.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>logout</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping> ```
5. 过滤器实现没有登录不能访问/jsp 目录下的页面
1. filter
```java
public class FrameFilter 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;
//不存在session说明没有登录, 直接重定向
if (req.getSession().getAttribute(Constant.USER_SESSION)==null){
resp.sendRedirect(req.getContextPath()+"/error.jsp");
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
```
2. web.xml
```xml
<!--页面拦截-->
<filter>
<filter-name>FrameFilter</filter-name>
<filter-class>com.ccc.filter.FrameFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FrameFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
```
修改密码实现
三,修改密码实现
1.UserDao–UserService中添加修改密码方法
//--------------------------UserDao------------------------------------------
@Override
public int updatePwd(Connection conn, String newPwd, int userID) {
PreparedStatement pst =null;
int row = 0;
if (conn!=null){
String sql = "update smbms_user set userpassword = ? where id = ?";
Object[] params = {newPwd,userID};
row = BaseDao.excute(conn, pst, sql, params);
//不用关Conn, 连接可能设计业务, 到事物里面关
BaseDao.closeAll(null,pst,null);
}else {
System.out.println("没获取到Connection");
}
return row;
}
//--------------------------UserService------------------------------------------
@Override
public int updatePwd(String newPwd, int userID) {
int row = 0;
try {
conn = BaseDao.getConn();
row = dao.updatePwd(conn,newPwd,userID);
}catch (Exception e){
e.printStackTrace();
}finally {
BaseDao.closeAll(conn,null,null);
}
return row;
}
2.编写通用类UserServlet
- 通过获取页面的
method
来判断是什么请求, 达到servlet复用
package com.ccc.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.ccc.pojo.User;
import com.ccc.service.user.UserService;
import com.ccc.service.user.UserServiceImpl;
import com.ccc.util.Constant;
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.Map;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
System.out.println(method);
if (method.equals("pwdmodify") && !StringUtils.isNullOrEmpty(method)){
//检查用户旧密码是否正确
this.pwdModify(req,resp);
}else if (method.equals("savepwd") && !StringUtils.isNullOrEmpty(method)){
//修改用户密码
this.UpdatePwd(req,resp);
}
}
//修改密码方法
private void UpdatePwd(HttpServletRequest req, HttpServletResponse resp) {
String newpassword = req.getParameter("newpassword");
String oldpassword = req.getParameter("oldpassword");
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
if (user!=null && !StringUtils.isNullOrEmpty(newpassword) && !StringUtils.isNullOrEmpty(oldpassword) ){
//session不为空, 新密码和旧密码不为空进
if (oldpassword.equals(user.getUserPassword())){
//输入的旧密码和用户旧密码一致进
UserService service = new UserServiceImpl();
int i = service.updatePwd(newpassword, user.getUserID());
if (i==1){
//影响行数为1代表修改成功
req.setAttribute(Constant.SYS_MESSAGE,"密码修改成功! 请重新登录");
req.getSession().setAttribute(Constant.USER_SESSION,null);
}else {//修改失败
req.setAttribute(Constant.SYS_MESSAGE,"密码修改失败! 请重试试");
}
}else {输入的旧密码和用户旧密码不一致
req.setAttribute(Constant.SYS_MESSAGE,"旧密码不匹配");
}
}else {//session为空或 新密码或旧密码为空
req.setAttribute(Constant.SYS_MESSAGE,"请重新登录在尝试");
}
try {
//最后要跳转回修改密码界面, 不写回卡在user.do请求
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//查看旧密码方法, 返回JSON
private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
Map<String,String> resultMap = new HashMap<>();
if (user==null){
resultMap.put("result","sessionerror");
}else if (StringUtils.isNullOrEmpty(oldpassword)){
resultMap.put("result","error");
}else if (!oldpassword.equals((user.getUserPassword()))){
resultMap.put("result","false");
}else {
resultMap.put("result","true");
}
try {
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(resultMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.注册servlet-------web.xml
<!--用户请求-->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.ccc.servlet.user.UserServlet</servlet-class>
</servlet>
四,用户管理
1,分页工具类
package com.ccc.util;
public class PageSupport {
//获取SQL 开始位置 , limit a, b; 返回 a 的值
public int getPageStart() {
return (this.currentPageNo - 1) * this.pageSize;
}
//总数量(查表总数count)
private int totalCount = 0;
//每页显示的数量
private int pageSize = 0;
//总页数-totalCount/pageSize(+1)
private int totalPageCount = 1;
//当前页码-来自于用户输入
private int currentPageNo = 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;
}
//最大页数约定 小于0 = 0 , 除尽 = 总数/每页数量 , 有余数 = (总数/每页数量) +1 页
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;
}
}
// public int getPageStart(int currentPageNo,int pageSize) {
return (currentPageNo-1)*this.pageSize;
// int i = ((currentPageNo - 1) * pageSize);
// return i ;
// }
}
2,获取用户列表
//--------------------------UserDao------------------------------------------
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(pageSize);
PreparedStatement pst =null;
ResultSet rs = null;
ArrayList<User> list = new ArrayList<>();
ArrayList<Object> parms = new ArrayList<>();
StringBuffer sql = new StringBuffer();
User user =null;
sql.append("SELECT a.*,r.rolename FROM `smbms_user` as a INNER JOIN smbms_role AS r ON a.userRole = r.id ");
if (!StringUtils.isNullOrEmpty(userName) && userRole>0){
sql.append(" where username like ? and userRole = ? ");
parms.add("%"+userName+"%");
parms.add(userRole);
}else if (!StringUtils.isNullOrEmpty(userName)){
sql.append(" where username like ? ");
parms.add("%"+userName+"%");
}else if (userRole>0){
sql.append(" where userRole = ? ");
parms.add(userRole);
}
sql.append(" order by a.creationDate LIMIT ?,? ");
if (currentPageNo<=0){
currentPageNo =1;
}
parms.add(pageSupport.getPageStart());
parms.add(pageSupport.getPageSize());
// System.out.println(sql.toString());
// System.out.println(parms.toArray());
if (connection!=null){
rs = BaseDao.excute(connection, pst, rs, sql.toString(), parms.toArray());
while (rs.next()) {
user = new User();
user.setId(rs.getInt("a.id"));
user.setUserCode(rs.getString("a.userCode"));
user.setUserName(rs.getString("a.userName"));
user.setUserPassword(rs.getString("a.userPassword"));
user.setGender(rs.getInt("a.gender"));
user.setBirthday(rs.getTimestamp("a.birthday"));
user.setPhone(rs.getString("a.phone"));
user.setAddress(rs.getString("a.address"));
user.setUserRole(rs.getInt("a.userRole"));
user.setCreatedBy(rs.getInt("a.createdBy"));
user.setCreationDate(rs.getTimestamp("a.creationDate"));
user.setModifyBy(rs.getInt("a.modifyBy"));
user.setModifyDate(rs.getTimestamp("a.modifyDate"));
user.setUserRoleName(rs.getString("r.rolename"));
list.add(user);
}
BaseDao.closeAll(null,pst,rs);
}
// System.out.println(sql);
// System.out.println(parms);
// System.out.println(list.size());
// for (int i = 0; i < list.size(); i++) {
// System.out.println(list.get(i).getUserName());
// }
return list;
}
//--------------------------Service------------------------------------------
@Override
public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {
List<User> list = null;
try {
conn = BaseDao.getConn();
list = dao.getUserList(conn,userName,userRole,currentPageNo,pageSize);
} catch (Exception e) {
e.printStackTrace();
}finally {
BaseDao.closeAll(conn,null,null);
}
return list;
}
3,UserServlet
package com.ccc.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.ccc.pojo.Role;
import com.ccc.pojo.User;
import com.ccc.service.user.UserService;
import com.ccc.service.user.UserServiceImpl;
import com.ccc.util.Constant;
import com.ccc.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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
System.out.println(method);
if (method.equals("pwdmodify") && !StringUtils.isNullOrEmpty(method)){
//检查用户旧密码是否正确
this.pwdModify(req,resp);
}else if (method.equals("savepwd") && !StringUtils.isNullOrEmpty(method)){
//修改用户密码
this.UpdatePwd(req,resp);
}else if (method.equals("query") && !StringUtils.isNullOrEmpty(method)){
//查询用户userlist
this.QueryUser(req,resp);
}
}
//--------------------查询所有用户UserList-----------------------------------------------
private void QueryUser(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl service = new UserServiceImpl();
//查询用户名字
String queryname = req.getParameter("queryname");
//查询用户ID
String tempRole = req.getParameter("queryUserRole");
int queryUserRole = 0;
if (!StringUtils.isNullOrEmpty(tempRole)) {
//不为空的话使用页面获取的ID
queryUserRole = Integer.parseInt(tempRole);
}
System.out.println("queryUserRole---->>>>" + queryUserRole);
//最大条数
String totalCount = req.getParameter("totalCount");
//第几页
String tempCurrentPageNo = req.getParameter("currentPageNo");
int currentPageNo = 0;
//最大页数
// String totalPageCount = req.getParameter("totalPageCount");
//当前页数
String tempPageIndex = req.getParameter("pageIndex");
int pageIndex = 0;
//用户总数量
int userCount = service.getUserCount(queryname, queryUserRole, null);
System.out.println("userCount--->>" + userCount);
//处理分页
PageSupport pageSupport = new PageSupport();
//设置每页大小
pageSupport.setPageSize(Constant.PAGE_SIZE);
//放入当前页数
if (!StringUtils.isNullOrEmpty(tempPageIndex)) {
pageIndex = Integer.parseInt(tempPageIndex);
}
pageSupport.setCurrentPageNo(pageIndex);
//放入当前总数
pageSupport.setTotalCount(userCount);
if (!StringUtils.isNullOrEmpty(tempCurrentPageNo)) {
currentPageNo = Integer.parseInt(tempCurrentPageNo);
}
pageSupport.setCurrentPageNo(currentPageNo);
//从分页工具类中获取新当前页面CurrentPageNo
int newPageno = pageSupport.getCurrentPageNo();
// System.out.println("newPageno--->>" + newPageno);
//从分页工具类中获取新页面大小PageSize
int newPageSize = pageSupport.getPageSize();
// System.out.println("newPageSize--->>" + newPageSize);
//查询user
List<User> userList = service.getUserList(queryname, queryUserRole, newPageno, newPageSize);
// System.out.println("userList--->>" + userList.size());
//查询role
List<Role> roleList = service.getRoleList(null);
// System.out.println("roleList--->>" + roleList.size());
//回显页面输入框
req.setAttribute("queryUserName", queryname);
req.setAttribute("queryUserRole", queryUserRole);
//返回list页面展示
req.setAttribute("roleList", roleList);
req.setAttribute("userList", userList);
//从分页工具类中获取新最大行数 getTotalCount()
int totalCount1 = pageSupport.getTotalCount();
// System.out.println("totalCount1--->>" + totalCount1);
//从分页工具类中获取新最大页数 getTotalPageCount
int totalPageCount = pageSupport.getTotalPageCount();
// System.out.println("totalPageCount--->>" + totalPageCount);
//返回分页参数到页面
req.setAttribute("totalCount", totalCount1); //总行数
req.setAttribute("currentPageNo", newPageno); //当前页
req.setAttribute("totalPageCount", totalPageCount); //总页数
try {
//跳转页面显示
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
} catch (ServletException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
} catch (IOException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
}
}
//修改密码方法
private void UpdatePwd(HttpServletRequest req, HttpServletResponse resp) {
String newpassword = req.getParameter("newpassword");
String oldpassword = req.getParameter("oldpassword");
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
if (user!=null && !StringUtils.isNullOrEmpty(newpassword) && !StringUtils.isNullOrEmpty(oldpassword) ){
//session不为空, 新密码和旧密码不为空进
if (oldpassword.equals(user.getUserPassword())){
//输入的旧密码和用户旧密码一致进
UserService service = new UserServiceImpl();
int i = service.updatePwd(newpassword, user.getId());
if (i==1){
//影响行数为1代表修改成功
req.setAttribute(Constant.SYS_MESSAGE,"密码修改成功! 请重新登录");
req.getSession().setAttribute(Constant.USER_SESSION,null);
}else {//修改失败
req.setAttribute(Constant.SYS_MESSAGE,"密码修改失败! 请重试试");
}
}else {输入的旧密码和用户旧密码不一致
req.setAttribute(Constant.SYS_MESSAGE,"旧密码不匹配");
}
}else {//session为空或 新密码或旧密码为空
req.setAttribute(Constant.SYS_MESSAGE,"请重新登录在尝试");
}
try {
//最后要跳转回修改密码界面, 不写回卡在user.do请求
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//查看旧密码方法, 返回JSON
private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
Map<String,String> resultMap = new HashMap<>();
if (user==null){
resultMap.put("result","sessionerror");
}else if (StringUtils.isNullOrEmpty(oldpassword)){
resultMap.put("result","error");
}else if (!oldpassword.equals((user.getUserPassword()))){
resultMap.put("result","false");
}else {
resultMap.put("result","true");
}
try {
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(resultMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4,测试功能
验证搜索框
五,添加用户
1,添加方法Dao层
@Override
public int addUser(Connection conn, User user) {
PreparedStatement pst =null;
int row = 0;
if (conn!=null){
String sql = "INSERT INTO `smbms`.`smbms_user`( `userCode`, `userName`, `userPassword`, `gender`, `birthday`, `phone`, `address`, `userRole`, `createdBy`, `creationDate`, `modifyBy`, `modifyDate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreationDate(),user.getModifyBy(),user.getModifyDate()};
row = BaseDao.excute(conn, pst, sql, params);
//不用关Conn, 连接可能设计业务, 到事物里面关
BaseDao.closeAll(null,pst,null);
}else {
System.out.println("没获取到Connection");
}
return row;
}
// service---------------------------------------------------------------------------
@Override
public int addUser(User user) {
int count = 0;
try {
conn = BaseDao.getConn();
count = dao.addUser(conn,user);
}catch (Exception e){
e.printStackTrace();
}finally {
BaseDao.closeAll(conn,null,null);
}
return count;
}
2,小小修改getUserCount, 添加了userCode作为条件
// 查询用户数方法
@Override
public int getUserCount(Connection conn, String userName, int userRole,String userCode) throws SQLException {
PreparedStatement pst =null;
ResultSet rs = null;
ArrayList<Object> list = new ArrayList<>();
StringBuffer sql = new StringBuffer();
sql.append("SELECT COUNT(1) FROM `smbms_user` as a INNER JOIN smbms_role AS r ON a.userRole = r.id");
int count = 0;
if (conn!=null){
if (!StringUtils.isNullOrEmpty(userName) && userRole>0){
sql.append(" where username like ? and userRole = ?");
list.add("%"+userName+"%");
list.add(userRole);
}else if (userRole>0){
sql.append(" where userRole = ?");
list.add(userRole);
}else if (!StringUtils.isNullOrEmpty(userName) ){
sql.append(" where username like ?");
list.add("%"+userName+"%");
}else if (!StringUtils.isNullOrEmpty(userCode) ){
sql.append(" where userCode = ?");
list.add(userCode);
}
rs = BaseDao.excute(conn, pst, rs,sql.toString(), list.toArray());
while (rs.next()){
count = rs.getInt("count(1)");
}
//不用关Conn, 连接可能设计业务, 到事物里面关
BaseDao.closeAll(null,pst,rs);
}else {
System.out.println("没获取到Connection");
}
System.out.println(sql);
return count;
}
3,Servlet
package com.ccc.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.ccc.pojo.Role;
import com.ccc.pojo.User;
import com.ccc.service.user.UserService;
import com.ccc.service.user.UserServiceImpl;
import com.ccc.util.Constant;
import com.ccc.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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
System.out.println(method);
if (method.equals("pwdmodify") && !StringUtils.isNullOrEmpty(method)) {
//检查用户旧密码是否正确
this.pwdModify(req, resp);
} else if (method.equals("savepwd") && !StringUtils.isNullOrEmpty(method)) {
//修改用户密码
this.UpdatePwd(req, resp);
} else if (method.equals("query") && !StringUtils.isNullOrEmpty(method)) {
//查询用户userlist
this.QueryUser(req, resp);
} else if (method.equals("add") && !StringUtils.isNullOrEmpty(method)) {
//添加用户
this.addUser(req, resp);
} else if (method.equals("getrolelist") && !StringUtils.isNullOrEmpty(method)) {
//查询权限表字段
this.getRoleList(req, resp);
} else if (method.equals("ucexist") && !StringUtils.isNullOrEmpty(method)) {
//查询用户code是否存在
this.queryUcode(req, resp);
}
}
//查询用户code是否存在
private void queryUcode(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl userService = new UserServiceImpl();
String userCode = req.getParameter("userCode");
HashMap<String, String> hashMap = new HashMap<>();
int userCount = 0;
if (!StringUtils.isNullOrEmpty(userCode)) {
userCount = userService.getUserCount(null, 0, userCode);
if (userCount ==1){
hashMap.put("userCode", "exist");
}else {
hashMap.put("userCode", "ok");
}
}else {
hashMap.put("userCode", "错误");
}
// System.out.println("queryUcode-----userCode>>>>"+userCode);
// System.out.println("queryUcode-----userCount>>>>"+userCount);
try {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(hashMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//查询权限表字段
private void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl userService = new UserServiceImpl();
List<Role> roleList = userService.getRoleList(null);
System.out.println("getRoleList-----roleList>>>>>" + roleList.size());
try {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(roleList);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//t添加用户
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取页面输入字段
String userCode = req.getParameter("userCode");
String userName = req.getParameter("userName");
String userPassword = req.getParameter("userPassword");
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();
if (!StringUtils.isNullOrEmpty(userCode)) {
user.setUserCode(userCode);
}
if (!StringUtils.isNullOrEmpty(userName)) {
user.setUserName(userName);
}
if (!StringUtils.isNullOrEmpty(userPassword)) {
user.setUserPassword(userPassword);
}
if (!StringUtils.isNullOrEmpty(gender)) {
user.setGender(Integer.parseInt(gender));
}
if (!StringUtils.isNullOrEmpty(phone)) {
user.setPhone(phone);
}
if (!StringUtils.isNullOrEmpty(address)) {
user.setAddress(address);
}
if (!StringUtils.isNullOrEmpty(userRole)) {
user.setUserRole(Integer.parseInt(userRole));
}
if (!StringUtils.isNullOrEmpty(birthday)) {
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
}
//创建对象从session获取当前用户ID
Object o = req.getSession().getAttribute(Constant.USER_SESSION);
if (o != null) {
int createBy = ((User) o).getCreatedBy();
user.setCreatedBy(createBy);
}
UserServiceImpl service = new UserServiceImpl();
if (user != null) {
//创建日期填当前日期
user.setCreationDate(new Date());
int i = service.addUser(user);
if (i == 1) { // 成功就跳转到查询页面
resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
} else {// 失败重新到添加页面
req.getRequestDispatcher("useradd.jsp").forward(req, resp);
}
} else {
req.getRequestDispatcher("useradd.jsp").forward(req, resp);
}
}
private void QueryUser(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl service = new UserServiceImpl();
//查询用户名字
String queryname = req.getParameter("queryname");
//查询用户ID
String tempRole = req.getParameter("queryUserRole");
int queryUserRole = 0;
if (!StringUtils.isNullOrEmpty(tempRole)) {
//不为空的话使用页面获取的ID
queryUserRole = Integer.parseInt(tempRole);
}
System.out.println("queryUserRole---->>>>" + queryUserRole);
//最大条数
String totalCount = req.getParameter("totalCount");
//第几页
String tempCurrentPageNo = req.getParameter("currentPageNo");
int currentPageNo = 0;
//最大页数
// String totalPageCount = req.getParameter("totalPageCount");
//当前页数
String tempPageIndex = req.getParameter("pageIndex");
int pageIndex = 0;
//用户总数量
int userCount = service.getUserCount(queryname, queryUserRole, null);
System.out.println("userCount--->>" + userCount);
//处理分页
PageSupport pageSupport = new PageSupport();
//设置每页大小
pageSupport.setPageSize(Constant.PAGE_SIZE);
//放入当前页数
if (!StringUtils.isNullOrEmpty(tempPageIndex)) {
pageIndex = Integer.parseInt(tempPageIndex);
}
pageSupport.setCurrentPageNo(pageIndex);
//放入当前总数
pageSupport.setTotalCount(userCount);
if (!StringUtils.isNullOrEmpty(tempCurrentPageNo)) {
currentPageNo = Integer.parseInt(tempCurrentPageNo);
}
pageSupport.setCurrentPageNo(currentPageNo);
//从分页工具类中获取新当前页面CurrentPageNo
int newPageno = pageSupport.getCurrentPageNo();
// System.out.println("newPageno--->>" + newPageno);
//从分页工具类中获取新页面大小PageSize
int newPageSize = pageSupport.getPageSize();
// System.out.println("newPageSize--->>" + newPageSize);
//查询user
List<User> userList = service.getUserList(queryname, queryUserRole, newPageno, newPageSize);
// System.out.println("userList--->>" + userList.size());
//查询role
List<Role> roleList = service.getRoleList(null);
// System.out.println("roleList--->>" + roleList.size());
//回显页面输入框
req.setAttribute("queryUserName", queryname);
req.setAttribute("queryUserRole", queryUserRole);
//返回list页面展示
req.setAttribute("roleList", roleList);
req.setAttribute("userList", userList);
//从分页工具类中获取新最大行数 getTotalCount()
int totalCount1 = pageSupport.getTotalCount();
// System.out.println("totalCount1--->>" + totalCount1);
//从分页工具类中获取新最大页数 getTotalPageCount
int totalPageCount = pageSupport.getTotalPageCount();
// System.out.println("totalPageCount--->>" + totalPageCount);
//返回分页参数到页面
req.setAttribute("totalCount", totalCount1); //总行数
req.setAttribute("currentPageNo", newPageno); //当前页
req.setAttribute("totalPageCount", totalPageCount); //总页数
try {
//跳转页面显示
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
} catch (ServletException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
} catch (IOException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
}
}
//修改密码方法
private void UpdatePwd(HttpServletRequest req, HttpServletResponse resp) {
String newpassword = req.getParameter("newpassword");
String oldpassword = req.getParameter("oldpassword");
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
if (user != null && !StringUtils.isNullOrEmpty(newpassword) && !StringUtils.isNullOrEmpty(oldpassword)) {
//session不为空, 新密码和旧密码不为空进
if (oldpassword.equals(user.getUserPassword())) {
//输入的旧密码和用户旧密码一致进
UserService service = new UserServiceImpl();
int i = service.updatePwd(newpassword, user.getId());
if (i == 1) {
//影响行数为1代表修改成功
req.setAttribute(Constant.SYS_MESSAGE, "密码修改成功! 3秒后跳转到登录界面");
req.getSession().setAttribute(Constant.USER_SESSION, null);
resp.setHeader("refresh", "3;url="+req.getContextPath()+"/login.jsp");
} else {//修改失败
req.setAttribute(Constant.SYS_MESSAGE, "密码修改失败! 请重试试");
}
} else {输入的旧密码和用户旧密码不一致
req.setAttribute(Constant.SYS_MESSAGE, "旧密码不匹配");
}
} else {//session为空或 新密码或旧密码为空
req.setAttribute(Constant.SYS_MESSAGE, "请重新登录在尝试");
}
try {
//最后要跳转回修改密码界面, 不写回卡在user.do请求
req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//查看旧密码方法, 返回JSON
private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
Map<String, String> resultMap = new HashMap<>();
if (user == null) {
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {
resultMap.put("result", "error");
} else if (!oldpassword.equals((user.getUserPassword()))) {
resultMap.put("result", "false");
} else {
resultMap.put("result", "true");
}
try {
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(resultMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3,访问测试
用户名检测功能
添加功能
添加成功
六,删除用户
1,Dao, service
@Override
public int delUser(Connection conn, int userID) {
PreparedStatement pst =null;
int row = 0;
if (conn!=null){
String sql = "delete from smbms_user where id = ?";
Object[] params = {userID};
row = BaseDao.excute(conn, pst, sql, params);
//不用关Conn, 连接可能设计业务, 到事物里面关
BaseDao.closeAll(null,pst,null);
}else {
System.out.println("没获取到Connection");
}
return row;
}
//----------------------------service
@Override
public int delUser(int userID) {
int row = 0;
try {
conn = BaseDao.getConn();
row = dao.delUser(conn,userID);
}catch (Exception e){
e.printStackTrace();
}finally {
BaseDao.closeAll(conn,null,null);
}
return row;
}
2,Servlet
package com.ccc.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.ccc.pojo.Role;
import com.ccc.pojo.User;
import com.ccc.service.user.UserService;
import com.ccc.service.user.UserServiceImpl;
import com.ccc.util.Constant;
import com.ccc.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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
System.out.println(method);
if (method.equals("pwdmodify") && !StringUtils.isNullOrEmpty(method)) {
//检查用户旧密码是否正确
this.pwdModify(req, resp);
} else if (method.equals("savepwd") && !StringUtils.isNullOrEmpty(method)) {
//修改用户密码
this.UpdatePwd(req, resp);
} else if (method.equals("query") && !StringUtils.isNullOrEmpty(method)) {
//查询用户userlist
this.QueryUser(req, resp);
} else if (method.equals("add") && !StringUtils.isNullOrEmpty(method)) {
//添加用户
this.addUser(req, resp);
} else if (method.equals("getrolelist") && !StringUtils.isNullOrEmpty(method)) {
//查询权限表字段
this.getRoleList(req, resp);
} else if (method.equals("ucexist") && !StringUtils.isNullOrEmpty(method)) {
//查询用户code是否存在
this.queryUcode(req, resp);
}else if (method.equals("deluser") && !StringUtils.isNullOrEmpty(method)) {
//查询用户code是否存在
this.delUser(req, resp);
}
}
//删除用户一: 删除
private void delUser(HttpServletRequest req, HttpServletResponse resp) {
HashMap<String, String> map = new HashMap<>();
String temuserid = req.getParameter("uid");
int userid = 0;
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
if (user.getUserRole()==1){
if (!StringUtils.isNullOrEmpty(temuserid)){
userid = Integer.parseInt(temuserid);
if (userid!= user.getId() && userid>0){
UserServiceImpl service = new UserServiceImpl();
System.out.println("userid----------------"+userid);
int i = service.delUser(userid);
System.out.println("IIIII----------------"+i);
if (i == 1) {
map.put("delResult","true");
}else {
map.put("delResult","notexist");
}
}else {
map.put("delResult","错误");
}
}else {
map.put("delResult","false");
}
}else {
map.put("delResult","norole");
}
try {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(map);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//查询用户code是否存在
private void queryUcode(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl userService = new UserServiceImpl();
String userCode = req.getParameter("userCode");
HashMap<String, String> hashMap = new HashMap<>();
int userCount = 0;
if (!StringUtils.isNullOrEmpty(userCode)) {
userCount = userService.getUserCount(null, 0, userCode);
if (userCount ==1){
hashMap.put("userCode", "exist");
}else {
hashMap.put("userCode", "ok");
}
}else {
hashMap.put("userCode", "错误");
}
// System.out.println("queryUcode-----userCode>>>>"+userCode);
// System.out.println("queryUcode-----userCount>>>>"+userCount);
try {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(hashMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//查询权限表字段
private void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl userService = new UserServiceImpl();
List<Role> roleList = userService.getRoleList(null);
System.out.println("getRoleList-----roleList>>>>>" + roleList.size());
try {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(roleList);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//t添加用户
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取页面输入字段
String userCode = req.getParameter("userCode");
String userName = req.getParameter("userName");
String userPassword = req.getParameter("userPassword");
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();
if (!StringUtils.isNullOrEmpty(userCode)) {
user.setUserCode(userCode);
}
if (!StringUtils.isNullOrEmpty(userName)) {
user.setUserName(userName);
}
if (!StringUtils.isNullOrEmpty(userPassword)) {
user.setUserPassword(userPassword);
}
if (!StringUtils.isNullOrEmpty(gender)) {
user.setGender(Integer.parseInt(gender));
}
if (!StringUtils.isNullOrEmpty(phone)) {
user.setPhone(phone);
}
if (!StringUtils.isNullOrEmpty(address)) {
user.setAddress(address);
}
if (!StringUtils.isNullOrEmpty(userRole)) {
user.setUserRole(Integer.parseInt(userRole));
}
if (!StringUtils.isNullOrEmpty(birthday)) {
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
}
//创建对象从session获取当前用户ID
Object o = req.getSession().getAttribute(Constant.USER_SESSION);
if (o != null) {
int createBy = ((User) o).getCreatedBy();
user.setCreatedBy(createBy);
}
UserServiceImpl service = new UserServiceImpl();
if (user != null) {
//创建日期填当前日期
user.setCreationDate(new Date());
int i = service.addUser(user);
if (i == 1) { // 成功就跳转到查询页面
resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
} else {// 失败重新到添加页面
req.getRequestDispatcher("useradd.jsp").forward(req, resp);
}
} else {
req.getRequestDispatcher("useradd.jsp").forward(req, resp);
}
}
private void QueryUser(HttpServletRequest req, HttpServletResponse resp) {
UserServiceImpl service = new UserServiceImpl();
//查询用户名字
String queryname = req.getParameter("queryname");
//查询用户ID
String tempRole = req.getParameter("queryUserRole");
int queryUserRole = 0;
if (!StringUtils.isNullOrEmpty(tempRole)) {
//不为空的话使用页面获取的ID
queryUserRole = Integer.parseInt(tempRole);
}
System.out.println("queryUserRole---->>>>" + queryUserRole);
//最大条数
String totalCount = req.getParameter("totalCount");
//第几页
String tempCurrentPageNo = req.getParameter("currentPageNo");
int currentPageNo = 0;
//最大页数
// String totalPageCount = req.getParameter("totalPageCount");
//当前页数
String tempPageIndex = req.getParameter("pageIndex");
int pageIndex = 0;
//用户总数量
int userCount = service.getUserCount(queryname, queryUserRole, null);
System.out.println("userCount--->>" + userCount);
//处理分页
PageSupport pageSupport = new PageSupport();
//设置每页大小
pageSupport.setPageSize(Constant.PAGE_SIZE);
//放入当前页数
if (!StringUtils.isNullOrEmpty(tempPageIndex)) {
pageIndex = Integer.parseInt(tempPageIndex);
}
pageSupport.setCurrentPageNo(pageIndex);
//放入当前总数
pageSupport.setTotalCount(userCount);
if (!StringUtils.isNullOrEmpty(tempCurrentPageNo)) {
currentPageNo = Integer.parseInt(tempCurrentPageNo);
}
pageSupport.setCurrentPageNo(currentPageNo);
//从分页工具类中获取新当前页面CurrentPageNo
int newPageno = pageSupport.getCurrentPageNo();
// System.out.println("newPageno--->>" + newPageno);
//从分页工具类中获取新页面大小PageSize
int newPageSize = pageSupport.getPageSize();
// System.out.println("newPageSize--->>" + newPageSize);
//查询user
List<User> userList = service.getUserList(queryname, queryUserRole, newPageno, newPageSize);
// System.out.println("userList--->>" + userList.size());
//查询role
List<Role> roleList = service.getRoleList(null);
// System.out.println("roleList--->>" + roleList.size());
//回显页面输入框
req.setAttribute("queryUserName", queryname);
req.setAttribute("queryUserRole", queryUserRole);
//返回list页面展示
req.setAttribute("roleList", roleList);
req.setAttribute("userList", userList);
//从分页工具类中获取新最大行数 getTotalCount()
int totalCount1 = pageSupport.getTotalCount();
// System.out.println("totalCount1--->>" + totalCount1);
//从分页工具类中获取新最大页数 getTotalPageCount
int totalPageCount = pageSupport.getTotalPageCount();
// System.out.println("totalPageCount--->>" + totalPageCount);
//返回分页参数到页面
req.setAttribute("totalCount", totalCount1); //总行数
req.setAttribute("currentPageNo", newPageno); //当前页
req.setAttribute("totalPageCount", totalPageCount); //总页数
try {
//跳转页面显示
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
} catch (ServletException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
} catch (IOException e) {
System.out.println("userlist.jsp");
e.printStackTrace();
}
}
//修改密码方法
private void UpdatePwd(HttpServletRequest req, HttpServletResponse resp) {
String newpassword = req.getParameter("newpassword");
String oldpassword = req.getParameter("oldpassword");
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
if (user != null && !StringUtils.isNullOrEmpty(newpassword) && !StringUtils.isNullOrEmpty(oldpassword)) {
//session不为空, 新密码和旧密码不为空进
if (oldpassword.equals(user.getUserPassword())) {
//输入的旧密码和用户旧密码一致进
UserService service = new UserServiceImpl();
int i = service.updatePwd(newpassword, user.getId());
if (i == 1) {
//影响行数为1代表修改成功
req.setAttribute(Constant.SYS_MESSAGE, "密码修改成功! 3秒后跳转到登录界面");
req.getSession().setAttribute(Constant.USER_SESSION, null);
resp.setHeader("refresh", "3;url="+req.getContextPath()+"/login.jsp");
} else {//修改失败
req.setAttribute(Constant.SYS_MESSAGE, "密码修改失败! 请重试试");
}
} else {输入的旧密码和用户旧密码不一致
req.setAttribute(Constant.SYS_MESSAGE, "旧密码不匹配");
}
} else {//session为空或 新密码或旧密码为空
req.setAttribute(Constant.SYS_MESSAGE, "请重新登录在尝试");
}
try {
//最后要跳转回修改密码界面, 不写回卡在user.do请求
req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//查看旧密码方法, 返回JSON
private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
Map<String, String> resultMap = new HashMap<>();
if (user == null) {
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {
resultMap.put("result", "error");
} else if (!oldpassword.equals((user.getUserPassword()))) {
resultMap.put("result", "false");
} else {
resultMap.put("result", "true");
}
try {
PrintWriter out = resp.getWriter();
String jsonString = JSONArray.toJSONString(resultMap);
out.write(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3,测试
- 管理员才能删除
- 管理员也不能删除自己
- 删除后跳转
- js