Home > Back-end >  how to passing data to next page from ajax success() function by using session.setAttribute()
how to passing data to next page from ajax success() function by using session.setAttribute()

Time:08-24

I am developing a login function by passing json object to servlet for validation. If the login/password match with DB. The page will redirect to a main page with the login ID and corresponding profile. Or redirect to an error page if login fail. Here my coding:

jsp:
function submitForm(thisObj, thisEvent) {
    var sLogin = $('#userName').val();
    var sPwd = $('#userPwd').val();
    var myData = {
    "userName": sLogin, 
    "userPwd": sPwd
    };
  
    $.ajax({
        type: "POST",
        url: "login",
        data:  JSON.stringify(myData),
        dataType: "json",
        success: function(result){
            if (result.status == "SUCCESS"){
                setAttribute("ID", result.requestId);
            }
        }
    });
    return false;
}

servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException{
    res.setContentType("application/json");
    PrintWriter out = res.getWriter();
    StringBuffer sbuffer = new StringBuffer();
    String inLine = null;
    String sUsername  = "", sUserPwd = "";
    try{
        BufferedReader reader = req.getReader();
        while ((inLine = reader.readLine()) != null)
            sbuffer.append(inLine);
        if (sbuffer.length() != 0){
            JSONObject jsObj = new JSONObject(sbuffer.toString());
            sUsername        = jsObj.optString("userName");
            sUserPwd         = jsObj.optString("userPwd");
        }
    }catch(Exception e){
        out.print("error");
        return;
    }
    if (sUsername == "userA") {
        JSONObject jsonSResp =  new JSONObject();
        jsonResp.put("status", "SUCCESS");
        jsonResp.put("requestId", "1");
        jsonResp.put("url", "LoginOK.jsp");
        out.println(jsonResp.toString());
    }
}    

The servlet can get the user input login/password and perform validation. And return result back to ajax. Up next, i want to pass the data from ajax success function to new page by using set session.setAttribute() method but not works. Can anyone give hint to me to solve such problem? Thanks.

CodePudding user response:

I think you need to use "rd.forward(req, res);" intead of "rd.include(req, res);" in this case.

CodePudding user response:

actually, i just want to return a success page with user profile (as json object) for follow up action if login/password match with mysql database or return login fail page for invalid login. but i really don't have any idea what my coding wrong.

  • Related