SMBMS ⑤ AJAX authentication old password

SMBMS ⑤ AJAX authentication old password

1. What is AJAX?

AJAX is a technology that can update some web pages without reloading the whole web page.

AJAX = Asynchronous Javascript And XML, i.e. asynchronous JavaScript and XML, is a technology for creating fast and dynamic web pages.

AJAX can make web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page. Traditional web pages (without AJAX) must reload the whole web page if they need to update the content.

2. Use of Ajax

2.1 AJAX format

Connect the password modification in pwdmodify JS uses AJAX technology to dynamically verify the old password

// Lose focus
oldpassword.on("blur", function () {
        $.ajax({
           // Request mode GET
            type: "GET",
            // Submitted requests and parameters
            // This is equivalent to initiating a path + "/ JSP / user. Do? Method = pwdmodify & oldpassword = oldpassword. Val()" request
            url: path + "/jsp/user.do",
            data: {method: "pwdmodify", oldpassword: oldpassword.val()}, //Parameters passed by ajax
            // Data format json mainstream development uses json for front-end and back-end interaction
            dataType: "json",
            success: function (data) {
                if (data.result == "true") {//The old password is correct
                    validateTip(oldpassword.next(), {"color": "green"}, imgYes, true);
                } else if (data.result == "false") {//The old password was entered incorrectly
                    validateTip(oldpassword.next(), {"color": "red"}, imgNo + " Incorrect input of original password", false);
                } else if (data.result == "sessionerror") {//The current user session has expired. Please log in again
                    validateTip(oldpassword.next(), {"color": "red"}, imgNo + " Current user session Expired, please log in again", false);
                } else if (data.result == "error") {//The old password is blank
                    validateTip(oldpassword.next(), {"color": "red"}, imgNo + " Please enter your old password", false);
                }
            },
            error: function (data) {
                //Request error
                validateTip(oldpassword.next(), {"color": "red"}, imgNo + " Request error", false);
            }
        });

Call the AJAX method when the oldpassword box loses focus, where

  1. type: "GET" is the request mode
  2. url: path + "/jsp/user.do" is the requested path
  3. data: {method: "pwdmodify", oldpassword: oldpassword.val()} is the data carried by the request
  4. dataType: "json" is the data format
  5. success: function (data) indicates that the request is successful, and the returned data is in data
  6. Error: the request for function (data) failed

Note: the data format in data is variable, but the mainstream development uses json for front-end and back-end interaction; Probably because json is a key value pair, it is directly through data You can get value by using the key method.

2.2 Servlet data acquisition

After password modification, Servlet reuse is realized in UserServlet, and an additional pwdModify can be added

public class UserServlet extends HttpServlet {
    // Servlet reuse, UserServlet not only changes the password, but also adds, deletes, changes and queries
    // How to execute multiple methods in a doGet?
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if("savepwd".equals(method)){
            this.updatePwd(req, resp);
        }else if("pwdmodify".equals(method)){
            this.pwdModify(req, resp);
        }
    }
    ...
	// Use the old password in the Session for authentication
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Get user from Session
        Object object = req.getSession().getAttribute(Constants.USER_SESSION);
        // Get the oldpassword parameter passed from the front end
        String oldpassword = req.getParameter("oldpassword");
        // Use Map to save the value of result
        Map<String, String> resultMap = new HashMap<String, String>();
        if(object == null){ // The user cannot be obtained, and the Session is invalid (set the Session expiration time)
            // Return value agreed with the front end
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){ //The old password is empty. Both the front end and the back end should be verified
            resultMap.put("result","error");
        }else{
            // Get old password
            String userPassword = ((User) object).getUserPassword();
            if( userPassword.equals(oldpassword)){ //The old password was entered correctly
                resultMap.put("result","true");
            }else{ //Old password input error
                resultMap.put("result","false");
            }
        }
        // Format response data
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        // JSON tool class of JSONArray Ali, where Map is converted to JSON
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush(); // ?
        writer.close();
    }
}

3. Summary

Process: the front end sends a request through AJAX, carries the pwdmodify parameter, tells the Servlet to use the pwdModify() method, and sends a JSON data containing the result value to the front end (converts the Map into JSON using JSONArray), and the front end judges the result value and performs corresponding operations.

Note: Tomcat can't find the jar package imported by Mavne. There should be two solutions

  1. Directly copy a copy of the jar package imported from the Mavne project from External Libraries to the lib folder under Tomcat.
  2. In the Artifacts option of project structtrue, put all jar packages into / WEB-INF / lib.

It's useful to see the end of AJAX at first, but I still need to study JSON 🤔.

Keywords: Java Ajax

Added by bubbadawg on Sat, 01 Jan 2022 01:55:37 +0200