修改用户密码

一、记·修改用户密码功效实现

  1. 新建页面
    profile.jsp,添加五个输入框和交由按钮:用户输入当前密码、输入新密码、再度肯定密码和重置按钮、修改密码按钮;

  2. 前台 js(JavaScript) 校验用户输入通过后触发 Ajax
    请求至后台;

  3. 后台(这里运用 Spring+SpringMVC+Mybatis 框架实现)在
    UserMapper.xmlSQL 语句实现,接着是
    UserModel.javaUserDAO.javaUserService.java
    和 UserServiceImpl.java 的接口实现;

  4. 后台控制器 UserAction.java
    实现,请求路径(path)、请求参数(parameter)、重返值实现。

 

二、相关代码示例

1. profile.jsp (将其文件后缀改为 profile.html 并在 Chrome
Google浏览器中开拓可参见 Demo)

图片 1图片 2

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
    String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>修改密码-系统后台管理</title>

        <!-- <jsp:include page="_css.jsp" /> -->

        <!-- <link rel="stylesheet" type="text/css" href="<%=path%>/view/assets/javascript/editor.css"/> --> <!-- 外部样式 -->
        <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
        <!-- 内部样式 -->
        <style type="text/css">
        .errorMsg {
            color: red;
        }

        .error {
            border: 1px solid red;
        }

        .password-input {
            width: 400px;
            hight: 25px !importent;
            margin-top: 5px;
        }

        .btn {
            vertical-align: middle;
            text-align: center;
            margin-top: 30px;
            width: 50%;
        }
        </style>
    </head>
    <body>
        <!-- <jsp:include page="_header.jsp" /> -->
        <div>
            <h3>修改用户密码</h3>
            <div>
                <label>当前密码</label></br>
                <input type="password" class="password-input" id="current_password" name="current_password" placeholder="密码长度为6-16个字符,由英文大小写字母、数字、符号组成" >
                &nbsp;
            </div>
            <div style="margin-top: 15px;"> <!-- 内联样式 -->
                <label>新密码</label></br>
                <input type="password" class="password-input" id="new_password" name="new_password" placeholder="新密码不能当前密码相同" >
                &nbsp;
            </div>
            <div style="margin-top: 15px;">
                <label>确认密码</label></br>
                <input type="password" class="password-input" id="confirmation_password" name="confirmation_password" placeholder="确认密码与新密码保持一致" >
                &nbsp;
            </div>
            <div class="btn">
                <input type="reset" value="重置" onclick="clearInput();"></i> &nbsp;
                <input type="button" value="修改密码" onclick="checkInput();"></i>
            </div>
        </div>

        <!-- <jsp:include page="_footer.jsp" /> -->
        <!-- <jsp:include page="_js.jsp">
                <jsp:param value="true" name="enableScript" />
             </jsp:include> -->

        <!-- <script type="text/javascript" src="<%=path%>/view/assets/javascript/editor.js"></script> -->
        <script type="text/javascript">
        var flag = true;

        function clearInput() {
            $("#current_password").val("");
            $("#new_password").val("");
            $("#confirmation_password").val("");
            clearErrorMsg();
        }

        function clearErrorMsg() {
            $("#currentMsg").html("");
            $("#newMsg").html("");
            $("#confirmMsg").html("");
            $("#current_password").removeClass("error");
            $("#new_password").removeClass("error");
            $("#confirmation_password").removeClass("error");
        }

        function checkInput() {
            clearErrorMsg();
            var currentPassword = $("#current_password").val();
            var newPassword = $("#new_password").val();
            var confirmPassword = $("#confirmation_password").val();

            checkPwdLength(currentPassword, "currentMsg", "current_password");
            checkPwdLength(newPassword, "newMsg", "new_password");
            checkPwdLength(confirmPassword, "confirmMsg", "confirmation_password");

            if (flag) {
                $.post("<%=path%>/user/updatePassword", {
                    currentPassword : currentPassword,
                    newPassword : newPassword
                }, function(data) {
                    if ("success" == data) {
                        alert("密码修改成功,请使用新密码重新登陆!");
                        window.location.href="<%=path%>/login";
                    } else {
                        $("#currentMsg").html(data);
                        $("#current_Password").addClass("error");
                    }
                });
            }
        }

        function checkPwdLength(obj, msg, id) {
            if ("" == obj) {
                $("#" + msg).html("该项不能为空!");
                $("#" + id).addClass("error");
                flag = false;
            } else if (6 > obj.length || obj.length > 16) {
                $("#" + msg).html("密码长度为6-16个字符!");
                $("#" + id).addClass("error");
                flag = false;
            } else if($("#current_password").val() == $("#new_password").val()) {
                $("#newMsg").html("新密码不能当前密码相同!");
                flag = false;
            } else if ($("#new_password").val() != $("#confirmation_password").val()) {
                $("#confirmMsg").html("两次输入的密码不一致!");
                flag = false;
            } else {
                flag = true;
            }
        }
        </script>
    </body>
</html>

View Code

 2. UserMapper.xml

图片 3图片 4

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE mapper  
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cqupt.dao.UserDAO">

    <resultMap id="userResultMap" type="com.cqupt.model.UserModel">
        <result property="id" column="id" jdbcType="INTEGER" javaType="int" />
        <result property="account" column="account" jdbcType="VARCHAR" javaType="String" />
        <result property="gender" column="gender" jdbcType="BIT" javaType="boolean" />
        <result property="password" column="password" jdbcType="VARCHAR" javaType="String" />
        <result property="phone" column="phone" jdbcType="VARCHAR" javaType="String" />
        <result property="qq" column="qq" jdbcType="VARCHAR" javaType="String" />
        <result property="mail" column="mail" jdbcType="VARCHAR" javaType="String" />
        <result property="type" column="type" jdbcType="INTEGER" javaType="int" />
        <result property="regTime" column="reg_time" jdbcType="TIMESTAMP" javaType="java.sql.Timestamp" />
    </resultMap>

    <insert id="addUser" parameterType="com.cqupt.model.UserModel">
        INSERT INTO web_user_info (account, gender,  password, phone, qq, mail, type, reg_time)
        VALUES(#{account }, #{gender }, #{password }, #{ phone } #{qq }, #{mail }, #{type }, now())
    </insert>

    <select id="findUserById" parameterType="int" resultMap="userResultMap">
        SELECT * FROM web_user_info WHERE id = #{userId }
    </select>

    <select id="findByAccount" parameterType="String" resultMap="userResultMap">
        SELECT * FROM web_user_info WHERE account = #{account }
    </select>

    <!-- 查询所有用户信息 -->
    <select id="findAllUsers" resultMap="userResultMap">
        SELECT * FROM web_user_info
    </select>

    <update id="updatePassword">
        UPDATE web_user_info SET password= #{newPassword } WHERE id = #{userId}
    </update>

</mapper> 

View Code

 3. UserDAO.java

图片 5图片 6

public interface UserDAO
{

    /**
     * 通过用户ID修改密码
     * @param userId user id
     * @param newPassword new password
     * @return 受影响的条数
     */
    int updatePassword(@Param("userId") int userId, @Param("newPassword") String newPassword);

}

View Code

 4. UserService.java

图片 7图片 8

public interface UserService
{

    /**
     * 通过ID修改用户密码
     * @param userId user id
     * @param newPassword new password
     * @return 受影响的数据行数
     */
    int updatePassword(int userId, String newPassword);

}

View Code

 5. UserServiceImpl.java

图片 9图片 10

@Service
public class UserServiceImpl implements UserService
{

    @Autowired
    private UserDAO userDAO;

    /**
     * {@inheritDoc }
     */
    @Override
    public int updatePassword(int userId, String newPassword) 
    {
        return userDAO.updatePassword(userId, newPassword);
    }

}

View Code

 6. UserAction.java

图片 11图片 12

@Controller
@RequestMapping("user")
public class UserAction extends WebCommonAction
{

    @Autowired
    private UserService userService;

    /**
     * 通过用户ID修改密码
     * @param req HttpServletRequest
     * @param newPassword 新密码
     * @return ModelAndView
     */
    @ResponseBody
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public Object updatePassword(HttpServletRequest req, String currentPassword, String newPassword)
    {
        UserModel currentUserModel = getCurrentUser(req);
        if (!currentUserModel.getPassword().equals(StringUtil.encodePwd(currentPassword))) 
        {
            return "当前密码输入不正确";
        }
        else 
        {
            userService.updatePassword(getCurrentUserId(req), StringUtil.encodePwd(newPassword));
            HttpSession session = req.getSession();
            session.setAttribute(Constant.WEB_CURRENT_USER, null);
            session.invalidate();
            return "success";
        }
    }

}

View Code

 

相关文章