[](()3)权限拦截
未登录用户不允计访问后台
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
Object user = request.getSession().getAttribute(Constants.USER_SESSION);
// 未登录
if (user == null) {
response.sendRedirect(request.getContextPath() + “/error.jsp”);
}
// 执行下一链
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
[](()4)修改密码
public interface UserDao {
/**
修改密码
@param connection 连接
@param id 用户id
@param newPassword 新密码
@return 成功修改的记录数
*/
int modifyPwd(Connection connection, int id, String newPassword);
}
public class UserDaoImpl implements UserDao{
@Override
public int modifyPwd(Connection connection, int id, String newPassword){
if(connection == null){
return 0;
}
String sql = “update smbms_user set userPassword = ? where id = ?”;
//Object[] params = {newPassword,id};
List params = new ArrayList<>();
params.add(newPassword);
params.add(id);
int i = 0;
try {
i = BaseDao.executeUpdate(connection, sql, params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
return i;
}
}
}
public interface UserService {
/**
修改密码
@param id 当前用户id
@param newPassword 新密码
@return
*/
boolean modifyPwd(int id, String newPassword);
}
public class UserServiceImpl implements UserService {
@Override
public boolean modifyPwd(int id, String newPassword) {
Connection connection = BaseDao.getConnection();
int i = userDao.modifyPwd(connection, id, newPassword);
// 关闭连接
BaseDao.close(connection, null, null);
if (i > 0) {
return true;
}
return false;
}
}
类的复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if(StringUtils.isNullOrEmpty(method)){
return;
}
// 修改密码
if (Objects.equals(“modifypwd”, method)) {
modifyPwd(req, resp);
return;
}
// 检验旧密码
if (Objects.equals(“checkpwd”, method)) {
checkPwd(req, resp);
return;
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
/**
修改密码
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void modifyPwd(HttpServletRequest req, 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if(user==null){
req.setAttribute(Constants.MESSAGE,“请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req,resp);
return;
}
// —得到用户输入的旧密码—
String oldpassword = req.getParameter(“oldpassword”);
if(StringUtils.isNullOrEmpty(oldpassword) || !Objects.equals(user.getUserPassword(),oldpassword)){
// 旧密码不合法:空 | null | 新旧不一致
// 请求转发至修改密码页面,返回
req.setAttribute(Constants.MESSAGE,“旧密码错误!”);
req.getRequestDispatcher(“/jsp/pwdmodify.jsp”).forward(req,resp);
return;
}
// —得到用户输入的新密码—
String newpassword = req.getParameter(“newpassword”);
// 修改密码
UserServiceImpl userService = new UserServiceImpl();
boolean b = userService.modifyPwd(user.getId(), newpassword);
// 修改成功:移除Session中的User,重定向至登录页,给出提示信息,退出
if(b){
req.getSession().removeAttribute(Constants.USER_SESSION);
req.setAttribute(Constants.MESSAGE,“密码修改成功!请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req,resp);
return;
}
// 修改失败:请求转发至修改密码页面,给出提示信息
req.setAttribute(Constants.MESSAGE,“密码修改失败!”);
req.getRequestDispatcher(“/jsp/pwdmodify.jsp”).forward(req,resp);
}
}
userServlet
com.tuwer.servlet.user.UserServlet
userServlet
/jsp/user.do
$.ajax({
type:“GET”,
url:path+“/jsp/user.do”,
data:{method:“checkpwd”,oldpassword:oldpassword.val()},
dataType:“json”,
success:function(data){
if(data.result == “true”){//旧密码正确
validateTip(oldpassword.next(),{“color”:“green”},imgYes,true);
}else if(data.result == “false”){//旧密码输入不正确
validateTip(oldpassword.next(),{“color”:“red”},imgNo + " 原密码输入不正确",false);
}else if(data.result == “sessionerror”){//当前用户session过期,请重新登录
validateTip(oldpassword.next(),{“color”:“red”},imgNo + " 当前用户session过期,请重新登录",false);
}else if(data.result == “error”){//旧密码输入为空
validateTip(oldpassword.next(),{“color”:“red”},imgNo + " 请输入旧密码",false);
}
},
error:function(data){
//请求出错
validateTip(oldpassword.next(),{“color”:“red”},imgNo + " 请求错误",false);
}
});
private void checkPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 结果集
Map
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
resultMap.put(“result”, “sessionerror”);
} else {
// —得到用户输入的旧密码—
String oldpassword = req.getParameter(“oldpassword”);
if (StringUtils.isNullOrEmpty(oldpassword)) {
// 旧密码不合法:空 | null
resultMap.put(“result”, “error”);
} else if (Objects.equals(user.getUserPassword(), oldpassword)) {
// 密码新旧一致
resultMap.put(“result”, “true”);
} else {
resultMap.put(“result”, “false”);
}
}
// —返回json数据—
resp.setContentType(“application/json”);
PrintWriter writer = resp.getWriter();
// 自定义JSON {“result”:“true”}
//writer.print(“{“result”:”" + resultMap.get(“result”) + “”}");
// 调用阿里巴巴JSON
writer.print(JSONArray.toJSONString(resultMap));
writer.close();
}
com.alibaba
fastjson
1.2.78
[](()5、用户管理
================================================================
[](()1)查看用户列表
分页查询用户信息
- 需要查用户信息 / 需要统计用户总数 / 需要查角色表
- 支持名称模糊查询
- 支持按角色查询
UserDao.java
/**
得到用户总数
@param connection 连接
@param userName 用户名(支持模糊查询)
@param userRole 用户角色
@return
*/
int getUserCount(Connection connection,String userName,int userRole);
/**
得到用户列表
@param connection 连接
@param userName 用户名(支持模糊查询)
@param userRole 用户角色
@param startIndex 当前页数据开始索引:从1开始,1.2.3…
@param pageSize 页面数量
@return
*/
List getUserList(
Connection connection,
String userName,
int userRole,
int startIndex,
int pageSize
);
角色接口
public interface RoleDao {
/**
得到角色列表
@param connection
@return
*/
List getRoleList(Connection connection);
}
UserDaoImpl.java
@Override
public int getUserCount(Connection connection, String userName, int userRole) {
if (connection == null) {
return 0;
}
//String sql = “select count(1) from smbms_user u,smbms_role r where u.userRole = ? and u.userName like ? and u.userRole = r.id”;
// 只要数量,不需要查角色表
StringBuffer sql = new StringBuffer();
sql.append(“select count(1) as count from smbms_user u”);
// 参数
List params = new ArrayList<>();
// —拼接sql及参数列表—
// 判断是否有用户名
boolean noUserName = StringUtils.isNullOrEmpty(userName);
// 判断是否有用色
boolean noUserRole = userRole < 1;
// 没有角色
if (noUserRole) {
// 有用户名
if (!noUserName) {
sql.append(" where u.userName like ?");
params.add(“%” + userName + “%”);
}
}
// 有角色
else {
sql.append(" where u.userRole = ?");
params.add(userRole);
// 有用户名
if (!noUserName) {
sql.append(" and u.userName like ?");
params.add(“%” + userName + “%”);
}
}
int count = 0;
try {
RowSet rowSet = BaseDao.executeQuery(connection, sql.toString(), params);
if (rowSet.next()) {
count = rowSet.getInt(“count”);
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
@Override
public List getUserList(
Connection connection,
String userName,
int userRole,
int startIndex,
int pageSize) {
if (connection == null) {
return null;
}
StringBuffer sql = new StringBuffer();
sql.append(“select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where”);
// 参数
List params = new ArrayList<>();
// —拼接sql及参数列表—
// 判断是否有用户名
boolean noUserName = StringUtils.isNullOrEmpty(userName);
// 判断是否有用色
boolean noUserRole = userRole < 1;
// 没有角色
if (noUserRole) {
// 有用户名
if (!noUserName) {
sql.append(" u.userName like ? and");
params.add(“%” + userName + “%”);
}
sql.append(" u.userRole = r.id");
}
// 有角色
else {
sql.append(" u.userRole = ? and");
params.add(userRole);
// 有用户名
if (!noUserName) {
sql.append(" u.userName like ? and");
params.add(“%” + userName + “%”);
}
sql.append(" u.userRole = r.id");
}
sql.append(" order by creationDate desc limit ?,?");
params.add(startIndex - 1);
params.add(pageSize);
List userList = new ArrayList<>();
try {
RowSet rs = BaseDao.executeQuery(connection, 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.setUserPassword(rs.getString(“userPassword”));
user.setGender(rs.getInt(“gender”));
user.setBirthday(rs.getDate(“birthday”));
user.setPhone(rs.getString(“phone”));
user.setAddress(rs.getString(“address”));
user.setUserRole(rs.getInt(“userRole”));
user.setCreatedBy(rs.getInt(“createdBy”));
user.setCreationDate((LocalDateTime) rs.getObject(“creationDate”));
user.setModifyBy(rs.getInt(“modifyBy”));
user.setModifyDate((LocalDateTime) rs.getObject(“modifyDate”));
user.setUserRoleName(rs.getString(“roleName”));
//user.setUserRoleName(rs.getString(rs.getMetaData().getColumnName(14)));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
return userList;
}
}
RoleDaoImpl.java
public class RoleDaoImpl implements RoleDao{
@Override
public List getRoleList(Connection connection) {
if(connection == null){
return null;
}
String sql = “select * from smbms_role order by creationDate desc”;
List roleList = new ArrayList<>();
try {
RowSet rs = BaseDao.executeQuery(connection, sql, null);
while (rs.next()){
Role r = new Role();
r.setId(rs.getInt(“id”));
r.setRoleCode(rs.getString(“roleCode”));
r.setRoleName(rs.getString(“roleName”));
r.setCreatedBy(rs.getInt(“createdBy”));
r.setCreatedBy(rs.getInt(“createdBy”));
r.setCreationDate((LocalDateTime) rs.getObject(“creationDate”));
r.setModifyBy(rs.getInt(“modifyBy”));
r.setModifyDate((LocalDateTime) rs.getObject(“modifyDate”));
roleList.add®;
}
} catch (SQLException e) {
e.printStackTrace();
}
return roleList;
}
}
UserService.java
/**
查询用户数量
@param userName 用户名
@param userRole 用户角色
@return
*/
int getUserCount(String userName,int userRole);
/**
得到用户列表
@param userName 用户名
@param userRole 用户角色
@param startIndex 起始位置:从1开始,1.2.3…
@param pageSize 数据量
@return
*/
List getUserList(
String userName,
int userRole,
int startIndex,
int pageSize
);
RoleService.java
public interface RoleService {
/**
得到角色列表
@return
*/
List getRoleList();
}
UserServiceImpl.java
@Override
public int getUserCount(String userName, int userRole) {
Connection connection = BaseDao.getConnection();
int count = userDao.getUserCount(connection, userName, userRole);
// 关闭连接
BaseDao.close(connection, null, null);
return count;
}
@Override
public List getUserList(String userName, int userRole, int startIndex, int pageSize) {
Connection connection = BaseDao.getConnection();
List userList = userDao.getUserList(connection, userName, userRole, startIndex, pageSize);
// 关闭连接
BaseDao.close(connection, null, null);
return userList;
}
RoleServiceImpl.java
public class RoleServiceImpl implements RoleService {
RoleDao roleDao;
public RoleServiceImpl() {
this.roleDao = new RoleDaoImpl();
}
@Override
public List getRoleList() {
Connection connection = BaseDao.getConnection();
List roleList = roleDao.getRoleList(connection);
// 关闭连接
BaseDao.close(connection, null, null);
return roleList;
}
}
UserServlet.java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if (StringUtils.isNullOrEmpty(method)) {
return;
}
// 查询用户列表
if (Objects.equals(“query”, method)) {
query(req, resp);
return;
}
}
/**
查询用户列表
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
req.setAttribute(Constants.MESSAGE, “请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
// —准备参数—
// 要查询用户名
String queryName = req.getParameter(“queryname”);
// 要查询角色
int userRoleId = PageUtil.strToInt_0123(req.getParameter(“queryUserRole”));
// 总记录数
UserServiceImpl userService = new UserServiceImpl();
int rows = userService.getUserCount(queryName, userRoleId);
// 总页数
int pages = PageUtil.getPages(rows, Constants.PAGE_SIZE);
// 当前页
int currentPage = PageUtil.getCurrentPage(req.getParameter(“pageIndex”), pages);
// 查询起始位置
int startIndex = PageUtil.getStartIndex(currentPage, Constants.PAGE_SIZE);
// —获取角色列表—
RoleServiceImpl roleService = new RoleServiceImpl();
List roleList = roleService.getRoleList();
// 把角色列表存入Session中,方便后面使用
req.getSession().setAttribute(Constants.ROLE_SESSION, roleList);
// —获取用户列表—
List userList = userService.getUserList(queryName, userRoleId, startIndex, Constants.PAGE_SIZE);
// 转发请求
req.setAttribute(“roleList”, roleList);
req.setAttribute(“userList”, userList);
req.setAttribute(“totalCount”, rows);
req.setAttribute(“currentPageNo”, currentPage);
req.setAttribute(“totalPageCount”, pages);
req.setAttribute(“queryUserName”, queryName);
req.setAttribute(“queryUserRole”, userRoleId);
req.setAttribute(“startIndex”, startIndex);
req.getRequestDispatcher(“/jsp/userlist.jsp”).forward(req, resp);
}
[](()2)添加用户
/**
验证用户账号是否已存在
@param connection 连接
@param userCode 用户账号
@return
*/
boolean userCodeIsExist(Connection connection,String userCode);
/**
添加用户
@param connection 连接
@param user 用户
@return
*/
int addUser(Connection connection,User user);
@Override
public boolean userCodeIsExist(Connection connection, String userCode) {
if (connection == null) {
return false;
}
String sql = “select count(1) as count from smbms_user where userCode = ?”;
// 参数
List params = new ArrayList<>();
params.add(userCode);
boolean isExist = false;
try {
RowSet rowSet = BaseDao.executeQuery(connection, sql, params);
if (rowSet.next()) {
if (rowSet.getInt(“count”) > 0) {
isExist = true;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return isExist;
}
@Override
public int addUser(Connection connection, User user) {
if (connection == null) {
return 0;
}
String sql = “insert into smbms_user (userCode,userName,userPassword,” +
"userRole,gender,birthday,phone,address,creationDate,createdBy) " +
“values(?,?,?,?,?,?,?,?,?,?)”;
// 参数
List params = new ArrayList<>();
params.add(user.getUserCode());
params.add(user.getUserName());
params.add(user.getUserPassword());
params.add(user.getUserRole());
params.add(user.getGender());
params.add(user.getBirthday());
params.add(user.getPhone());
params.add(user.getAddress());
params.add(user.getCreationDate());
params.add(user.getCreatedBy());
int i = 0;
try {
i = BaseDao.executeUpdate(connection, sql, params);
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
/**
验证用户账号是否已存在
@param userCode 用户账号
@return
*/
boolean userCodeIsExist(String userCode);
/**
添加用户
@param user
@return
*/
boolean addUser(User user);
@Override
public boolean userCodeIsExist(String userCode) {
Connection connection = BaseDao.getConnection();
boolean isExist = userDao.userCodeIsExist(connection,userCode);
// —关闭—
BaseDao.close(connection, null, null);
return isExist;
}
@Override
public boolean addUser(User user) {
boolean flag = false;
Connection connection = BaseDao.getConnection();
try {
// —开启事务—
connection.setAutoCommit(false);
// —添加—
int i = userDao.addUser(connection, user);
// —正常返回,提交事务—
connection.commit();
if (i > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
// —异常—
// —事务回滚—
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} finally {
// —关闭—
BaseDao.close(connection, null, null);
}
// —返回—
return flag;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if (StringUtils.isNullOrEmpty(method)) {
return;
}
// 添加用户
if (Objects.equals(“add”, method)) {
addUser(req, resp);
return;
}
// 验证userCode是否已存在
if (Objects.equals(“ucexist”, method)) {
userCodeIsExist(req, resp);
return;
}
}
/**
检验用户账号是否已存在
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void userCodeIsExist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 结果集
Map
// —得到用户账号—
String userCode = req.getParameter(“userCode”);
if (StringUtils.isNullOrEmpty(userCode)) {
// 用户账号不合法:空 | null
resultMap.put(“userCode”, “error”);
} else if (new UserServiceImpl().userCodeIsExist(userCode)) {
// 已存在
resultMap.put(“userCode”, “exist”);
} else {
// 不存在
resultMap.put(“userCode”, “notexist”);
}
// —返回json数据—
resp.setContentType(“application/json”);
PrintWriter writer = resp.getWriter();
// 自定义JSON {“result”:“true”}
//writer.print(“{“result”:”" + resultMap.get(“result”) + “”}");
// 调用阿里巴巴JSON
writer.print(JSONArray.toJSONString(resultMap));
writer.close();
}
/**
添加用户
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
req.setAttribute(Constants.MESSAGE, “请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
// —接收参数—
String userCode = req.getParameter(“userCode”).trim();
String userName = req.getParameter(“userName”).trim();
String userPassword = req.getParameter(“userPassword”);
String gender = req.getParameter(“gender”).trim();
String birthday = req.getParameter(“birthday”).trim();
String phone = req.getParameter(“phone”).trim();
String address = req.getParameter(“address”).trim();
String userRole = req.getParameter(“userRole”).trim();
// —生成User—
User newUser = new User();
newUser.setUserCode(userCode);
newUser.setUserName(userName);
newUser.setUserPassword(userPassword);
newUser.setGender(Integer.parseInt(gender));
try {
newUser.setBirthday(new SimpleDateFormat(“yyyy-MM-dd”).parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
newUser.setPhone(phone);
newUser.setAddress(address);
newUser.setUserRole(Integer.parseInt(userRole));
// 创建时间:当前时间
newUser.setCreationDate(LocalDateTime.now());
// 创建者:当前登录用户Id
newUser.setCreatedBy(user.getId());
// —添加—
UserServiceImpl userService = new UserServiceImpl();
// 添加成功:重定向至用户列表页
if (userService.addUser(newUser)) {
resp.sendRedirect(req.getContextPath() + “/jsp/user.do?method=query”);
return;
}
// 添加失败:转发至添加用户页
req.getRequestDispatcher(“/jsp/useradd.jsp”).forward(req, resp);
}
[](()3)查看特定用户
/**
根据用户ID获取用户
@param userId
@return
*/
User getUserById(Connection connection,int userId);
@Override
public User getUserById(Connection connection, int userId) {
if (connection == null) {
return null;
}
String sql = “select u.*,r.roleName from smbms_user u,smbms_role r where u.id = ? and u.userRole = r.id”;
// 参数
List params = new ArrayList<>();
params.add(userId);
User user = null;
try {
RowSet rs = BaseDao.executeQuery(connection, sql, params);
if (rs.next()) {
user = new User();
user.setId(userId);
user.setUserCode(rs.getString(“userCode”));
user.setUserName(rs.getString(“userName”));
user.setUserPassword(rs.getString(“userPassword”));
user.setGender(rs.getInt(“gender”));
user.setBirthday(rs.getDate(“birthday”));
user.setPhone(rs.getString(“phone”));
user.setAddress(rs.getString(“address”));
user.setUserRole(rs.getInt(“userRole”));
user.setCreatedBy(rs.getInt(“createdBy”));
user.setCreationDate((LocalDateTime) rs.getObject(“creationDate”));
user.setModifyBy(rs.getInt(“modifyBy”));
user.setModifyDate((LocalDateTime) rs.getObject(“modifyDate”));
user.setUserRoleName(rs.getString(rs.getMetaData().getColumnName(14)));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
/**
根据Id获取用户
@param userId
@return
*/
User getUserById(int userId);
@Override
public User getUserById(int userId) {
Connection connection = BaseDao.getConnection();
User user = userDao.getUserById(connection, userId);
// —关闭—
BaseDao.close(connection, null, null);
return user;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if (StringUtils.isNullOrEmpty(method)) {
return;
}
// 查看用户
if (Objects.equals(“view”, method)) {
viewUser(req, resp);
return;
}
}
/**
查看特定用户
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
req.setAttribute(Constants.MESSAGE, “请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
// —准备参数—
// 要查询用户Id
String userId = req.getParameter(“uid”);
if (StringUtils.isNullOrEmpty(userId)) {
// 用户Id不合法:空 | null
return;
} else {
User u = new UserServiceImpl().getUserById(Integer.parseInt(userId));
// 转发请求
req.setAttribute(“user”, u);
req.getRequestDispatcher(“/jsp/userview.jsp”).forward(req, resp);
}
}
[](()4)修改用户
/**
修改用户
@param connection 连接
@param user 用户
@return
*/
boolean modifyUser(Connection connection,User user);
@Override
public boolean modifyUser(Connection connection, User user) {
if (connection == null) {
return false;
}
String sql = “update smbms_user set userName = ?,gender = ?,birthday = ?,phone = ?,address = ?,userRole = ?,modifyBy = ?,modifyDate = ? where id = ?”;
// 参数
List params = new ArrayList<>();
params.add(user.getUserName());
params.add(user.getGender());
params.add(user.getBirthday());
params.add(user.getPhone());
params.add(user.getAddress());
params.add(user.getUserRole());
params.add(user.getModifyBy());
params.add(user.getModifyDate());
params.add(user.getId());
boolean success = false;
try {
int i = BaseDao.executeUpdate(connection, sql, params);
if (i > 0) {
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return success;
}
/**
修改用户
@param user
@return
*/
boolean modifyUser(User user);
@Override
public boolean modifyUser(User user) {
boolean flag = false;
Connection connection = BaseDao.getConnection();
try {
// —开启事务—
connection.setAutoCommit(false);
// —修改—
flag = userDao.modifyUser(connection, user);
// —正常返回,提交事务—
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
// —异常—
// —事务回滚—
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} finally {
// —关闭—
BaseDao.close(connection, null, null);
}
// —返回—
return flag;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if (StringUtils.isNullOrEmpty(method)) {
return;
}
// 进入修改用户页面
if (Objects.equals(“modify”, method)) {
goModifyUser(req, resp);
return;
}
// 修改用户
if (Objects.equals(“modifyexe”, method)) {
modifyUser(req, resp);
return;
}
}
/**
进入修改用户页面
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void goModifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
req.setAttribute(Constants.MESSAGE, “请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
// —准备参数—
// 用户Id
String userId = req.getParameter(“uid”);
if (StringUtils.isNullOrEmpty(userId)) {
// 用户Id不合法:空 | null
return;
} else {
User u = new UserServiceImpl().getUserById(Integer.parseInt(userId));
// 转发请求
req.setAttribute(“user”, u);
req.getRequestDispatcher(“/jsp/usermodify.jsp”).forward(req, resp);
}
}
/**
修改用户
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// —从Session中获取用户—
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
// Session失效
if (user == null) {
req.setAttribute(Constants.MESSAGE, “请重新登录!”);
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
// —准备参数—
// 用户Id
String userId = 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”);
if (StringUtils.isNullOrEmpty(userId)) {
// 用户Id不合法:空 | null
return;
} else {
// —生成User—
UserServiceImpl userService = new UserServiceImpl();
User newUser = userService.getUserById(Integer.parseInt(userId));
newUser.setUserName(userName);
newUser.setGender(Integer.parseInt(gender));
try {
newUser.setBirthday(new SimpleDateFormat(“yyyy-MM-dd”).parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
newUser.setPhone(phone);
newUser.setAddress(address);
newUser.setUserRole(Integer.parseInt(userRole));
// 修改时间:当前时间
newUser.setCreationDate(LocalDateTime.now());
// 创建者:当前登录用户Id
newUser.setCreatedBy(user.getId());
if (userService.modifyUser(newUser)) {
// 修改成功:返回用户信息页面
resp.sendRedirect(req.getContextPath() + “/jsp/user.do?method=view&uid=” + userId);
} else {
// 修改失败:返回修改页面
// 转发请求
req.setAttribute(“user”, newUser);
req.getRequestDispatcher(“/jsp/usermodify.jsp”).forward(req, resp);
}
}
}
[](()5)删除用户
/**
删除用户
@param connection
@param userId
@return
*/
boolean deleteUser(Connection connection,int userId);
@Override
public boolean deleteUser(Connection connection, int userId) {
if (connection == null) {
return false;
}
String sql = “delete from smbms_user where id = ?”;
// 参数
List params = new ArrayList<>();
params.add(userId);
boolean success = false;
try {
if (BaseDao.executeUpdate(connection, sql, params) > 0) {
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return success;
}
/**
删除用户
@param userId 用户Id
@return
*/
boolean deleteUser(int userId);
@Override
public boolean deleteUser(int userId) {
Connection connection = BaseDao.getConnection();
boolean success = userDao.deleteUser(connection, userId);
// —关闭—
BaseDao.close(connection, null, null);
return success;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter(“method”);
if (StringUtils.isNullOrEmpty(method)) {
return;
}
// 删除用户
if (Objects.equals(“deluser”, method)) {
deleteUser(req, resp);
return;
}
}
/**
删除用户
@param req
@param resp
@throws ServletException
@throws IOException
*/
private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 结果集
Map
// —得到用户id—
String userId = req.getParameter(“uid”);
if (StringUtils.isNullOrEmpty(userId)) {
// 用户Id不合法:空 | null
resultMap.put(“result”, “false”);
} else if (new UserServiceImpl().deleteUser(Integer.parseInt(userId))) {
// 已存在
resultMap.put(“result”, “true”);
} else {
// 不存在
resultMap.put(“result”, “notexist”);
}
// —返回json数据—