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代码:

javascript 复制代码
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代码:

java 复制代码
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();
        }
    }
}
相关推荐
_祝你今天愉快几秒前
技术成神之路:设计模式(十四)享元模式
java·设计模式
小筱在线39 分钟前
SpringCloud微服务实现服务熔断的实践指南
java·spring cloud·微服务
luoluoal44 分钟前
java项目之基于Spring Boot智能无人仓库管理源码(springboot+vue)
java·vue.js·spring boot
VinciYan1 小时前
Rust使用Actix-web和SeaORM库开发WebAPI通过Swagger UI查看接口文档
rust·api·web·orm
ChinaRainbowSea1 小时前
十三,Spring Boot 中注入 Servlet,Filter,Listener
java·spring boot·spring·servlet·web
小游鱼KF1 小时前
Spring学习前置知识
java·学习·spring
扎克begod1 小时前
JAVA并发编程系列(9)CyclicBarrier循环屏障原理分析
java·开发语言·python
青灯文案11 小时前
SpringBoot 项目统一 API 响应结果封装示例
java·spring boot·后端
我就是程序猿1 小时前
tomcat的配置
java·tomcat
阳光阿盖尔1 小时前
EasyExcel的基本使用——Java导入Excel数据
java·开发语言·excel