JavaWeb 项目实现(四) 验证旧密码

1.验证旧密码

步骤很简单,从Session中取到当前密码,和修改密码界面得到的旧密码对比,判断是否相等。

特别之处在于实现用到了Ajax,可以不刷新整个页面的情况下与Web服务器进行通信。

2.Ajax

Ajax(Asynchronous JavaScript and XML)是一种用于在Web应用程序中创建交互式用户界面和实现异步数据交换的技术。它使用JavaScript编写的代码,在不刷新整个页面的情况下与Web服务器进行通信,从而实现动态加载内容和更新页面。

用法: 

3.JSON

在使用Ajax的时候,我们看到了数据类型是json,所以来了解一下jason。

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它使用易于读写的文本格式来表示数据,通常用于在客户端和服务器之间传递数据。JSON格式基于JavaScript语言的一个子集,但它可以由很多不同的编程语言解析和生成。

JSON格式由键值对组成,其中键是字符串,值可以是字符串、数字、布尔值、数组、对象或null。例如,下面是一个简单的JSON对象:

```
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
```

JSON格式具有很多优点,例如易于读写、易于解析、轻量级、可读性好等。

JSON已成为Web应用程序中传递数据的常用格式,例如在AJAX请求中传递数据,或者在RESTful API中返回数据。

4.代码实现

上面说到了在AJAX请求中传递数据,或者在RESTful API中返回数据。

所以我们的实现也是一样的,先是js代码:

var oldpassword = null;
var newpassword = null;
var rnewpassword = null;
var saveBtn = null;

$(function(){
	oldpassword = $("#oldpassword");
	newpassword = $("#newpassword");
	rnewpassword = $("#rnewpassword");
	saveBtn = $("#save");
	
	oldpassword.next().html("*");
	newpassword.next().html("*");
	rnewpassword.next().html("*");
	
	oldpassword.on("blur",function(){
		$.ajax({
			type:"GET",
			url:path+"/jsp/user.do",
			data:{method:"pwdmodify",oldpassword:oldpassword.val()},	//Ajax传递的参数
			//path+/jsp/user.do?method=pwdmodify&oldpassword=oldpassword.val();
			dataType:"json",	//主流开发都是用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);
			}
		});


	}).on("focus",function(){
		validateTip(oldpassword.next(),{"color":"#666666"},"* 请输入原密码",false);
	});

	newpassword.on("focus",function(){
		validateTip(newpassword.next(),{"color":"#666666"},"* 密码长度必须是大于6小于20",false);
	}).on("blur",function(){
		if(newpassword.val() != null && newpassword.val().length > 6
				&& newpassword.val().length < 20 ){
			validateTip(newpassword.next(),{"color":"green"},imgYes,true);
		}else{
			validateTip(newpassword.next(),{"color":"red"},imgNo + " 密码输入不符合规范,请重新输入",false);
		}
	});


	rnewpassword.on("focus",function(){
		validateTip(rnewpassword.next(),{"color":"#666666"},"* 请输入与上面一致的密码",false);
	}).on("blur",function(){
		if(rnewpassword.val() != null && rnewpassword.val().length > 5
				&& rnewpassword.val().length < 20 && newpassword.val() == rnewpassword.val()){
			validateTip(rnewpassword.next(),{"color":"green"},imgYes,true);
		}else{
			validateTip(rnewpassword.next(),{"color":"red"},imgNo + " 两次密码输入不一致,请重新输入",false);
		}
	});

	saveBtn.on("click",function(){
		oldpassword.blur();
		newpassword.blur();
		rnewpassword.blur();
		if(
			oldpassword.attr("validateStatus") == "true"
			&&
			newpassword.attr("validateStatus") == "true"
			&&
			rnewpassword.attr("validateStatus") == "true"){
			if(confirm("确定要修改密码?")){
				$("#userForm").submit();
			}
		}
	});
}
);

再是servlet代码:

package com.code.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.code.pojo.User;
import com.code.service.user.UserService;
import com.code.service.user.UserServiceImpl;
import com.code.util.Constants;
import com.mysql.cj.util.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");
        if (method.equals("savePwd")) {
            updatePwd(req, resp);
        }else if (method.equals("pwdmodify")) {
            modifyPwd(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        Object object = req.getSession().getAttribute(Constants.USER_SESSION);
        String newPwd = req.getParameter("newpassword");

        if(object!=null && !StringUtils.isNullOrEmpty(newPwd)){
            UserService userService = new UserServiceImpl();
            boolean res = userService.updatePwd(((User)object).getId(), newPwd);
            if(res){

                req.setAttribute(Constants.MESSAGE, "更新密码成功,请成功登录");
                req.removeAttribute(Constants.USER_SESSION);
            }else{

                req.setAttribute(Constants.MESSAGE, "更新密码失败");
            }
        }else {

            req.setAttribute(Constants.MESSAGE, "新密码异常");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void modifyPwd(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldPwd = req.getParameter("oldpassword");
        Map<String, String > resultMap = new HashMap<String, String>();
        if(o==null){
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldPwd)) {
            resultMap.put("result", "error");
        } else  {
            String pwd = ((User)(o)).getUserPassword();
            if(oldPwd.equals(pwd)){
                resultMap.put("result", "true");
            }else{
                resultMap.put("result", "false");
            }
        }


        try {
            resp.setContentType("application/jason");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,修改密码实现代码如下: 1. 修改密码页面的 HTML 代码: ```html <form action="updatePassword" method="post"> <label for="oldPassword">密码:</label> <input type="password" id="oldPassword" name="oldPassword"><br> <label for="newPassword">新密码:</label> <input type="password" id="newPassword" name="newPassword"><br> <label for="confirmPassword">确认新密码:</label> <input type="password" id="confirmPassword" name="confirmPassword"><br> <button type="submit">确认修改</button> </form> ``` 2. 修改密码的 Servlet 代码: ```java @WebServlet("/updatePassword") public class UpdatePasswordServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取密码、新密码、确认新密码 String oldPassword = request.getParameter("oldPassword"); String newPassword = request.getParameter("newPassword"); String confirmPassword = request.getParameter("confirmPassword"); // 获取当前登录用户的信息 HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); // 验证密码是否正确 if (!user.getPassword().equals(oldPassword)) { response.getWriter().println("<script>alert('密码不正确!');history.go(-1);</script>"); return; } // 验证密码和确认新密码是否一致 if (!newPassword.equals(confirmPassword)) { response.getWriter().println("<script>alert('新密码和确认新密码一致!');history.go(-1);</script>"); return; } // 修改密码 UserService userService = new UserServiceImpl(); boolean result = userService.updatePassword(user.getId(), newPassword); if (result) { response.sendRedirect("login.jsp"); } else { response.getWriter().println("<script>alert('修改密码失败!');history.go(-1);</script>"); } } } ``` 3. UserServiceImpl 中的 updatePassword 方法代码: ```java public boolean updatePassword(int userId, String newPassword) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); String sql = "update user set password = ? where id = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, newPassword); pstmt.setInt(2, userId); int count = pstmt.executeUpdate(); return count > 0; } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(conn, pstmt); } return false; } ``` 注意:以上代码仅供参考,具体实现可能因为业务需求而有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值