0

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 LoginOK 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 myData = {
        "userName": sLogin
    };
    $.ajax({
        type: "POST",
        url: "login",
        data:  JSON.stringify(myData),
        dataType: "json"
    });
    return false;
}

servlet:
public class login extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException{
        int  iCnt = iHitCnt++;
        res.setContentType("application/json");
        PrintWriter out = res.getWriter();
        StringBuffer sbuffer = new StringBuffer();
        String inLine = null;
        String sUsername = "";
        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");
                }
        }catch(Exception e){
           return;

        req.setAttribute("ID",sUsername);
        RequestDispatcher rd = req.getRequestDispatcher("ok.jsp");
        rd.forward(req, res);
    }
}

LoginOK.jsp:
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<%@ page language="java" contentType="text/html; charset=big5"%>
<%
    String sRemoteAddr="";
    String sID="";
    session = request.getSession(true);
    try {
        sRemoteAddr=(String)request.getRemoteAddr();
        sID=(String)request.getAttribute("ID");
    } catch (Exception e) {
       application.log("err");
    }
%>
<font size=20><%= sID%></font>
</body>
</html>

But the RequestDispatcher.forward(req,res) not working. The servlet ok to get the user input but fail to forward a new page. Anyone can give help which part of coding I'm wrong? Thanks.

stockton
  • 19
  • 6
  • In the abovelinked duplicate, scroll to the "Sending a redirect from servlet" section for the answer. – BalusC Aug 23 '22 at 10:59
  • I already search to look for similar cases. but still have no idea. I have checked the system access log. the result page is ok to load with parameter but no response on browser. would you please give me more hints? Thanks. – stockton Aug 23 '22 at 11:46
  • 1) Click the abovelinked duplicate. 2) Scroll or Ctrl+F to the section "Sending a redirect from servlet". 3) Read it. – BalusC Aug 23 '22 at 11:54

0 Answers0