java - 从 Servlet -> JavaScript 操作登录进度

标签 java ajax servlets

我对网络开发非常陌生。

我已经设置的东西

* the Apache server
* DB on Eclipse
* one index.html file with Javascript
* one servlet

目标

* get a credential information
* send via method of 'Javascript -> servlet' to find out user exist.
* from the Javascript method need to receive DB existence.

问题

* I used 'AJAX', looks to me all same as one of Javascript method that does do for asynchronous with HTML and server.
* from the index.html page, if I press wrong information (id, password) then yes it prompts the message.

when enters wrong input

  • 但是如果我输入正确的信息,那么我想要重定向的页面就会出现在上述错误消息页面的区域中。

new page directly loads up in that area which i don't want. I just want to open new view

  • 我知道下面的代码是非常菜鸟的构建,但是我是否可以重定向到新页面?
  • 请随时纠正我。

Servlet 中的 doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    String name = request.getParameter("user_id");
    String password = request.getParameter("passwd");
    // search for query user existence 
    try
    {
        // TODO session, cookies
        sharedConnection = dataSource.getConnection();
        Statement stmt = sharedConnection.createStatement();
        String str = "select * from customers where email ='" + name + "' and password='" + password + "' ";
        ResultSet rs = stmt.executeQuery(str);
        HttpSession session = request.getSession();

        // not found
        if (!rs.next())
        {
            PrintWriter out = response.getWriter();
            out.println("<h3>credentials invalid</h3>");
        }
        // exist
        else 
        {
            String first_name = rs.getString("first_name");
            String last_name = rs.getString("last_name");
            session.setMaxInactiveInterval(1800); //set timeout to 30min
            session.setAttribute("loggedin", true);
            session.setAttribute("name", (first_name+ ", " + last_name));
            response.sendRedirect("/MovieDB/main.html");
        }
    }
    catch(SQLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

带有 AJAX 脚本的 HTML

<script type="text/javascript">
function loadXMLDoc()
{
    var xmlhttp;
    var user_id = document.getElementById('user_id').value;
    var passwd = document.getElementById('passwd').value;

    <!-- newer browser -->
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    <!-- IE 5, 6 -->
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4)
       {
          if (xmlhttp.status==200)
              document.getElementById("state_msg").innerHTML=xmlhttp.responseText;

       }
    }
    <!-- access servlet with parameters -->
    xmlhttp.open("POST", ("LoginServlet?user_id=" + user_id +"&passwd=" + passwd) , true);
    xmlhttp.send();

    <!-- If Servlet don't detour main.html then we must assume error -->
    var err = document.getElementById("state_msg");
    err.style.display = "block";
}

</script>
<title>MovieDB : WebAuth</title>
</head>
<body>
    <h1>FabFlix WebAuth</h1>
    <!-- label user id -->
    <div id=input_info>
        <label for="user_id">User :</label>
    </div>
    <!-- user id -->
    <input type="text" id="user_id" name="user_id" />
    <p></p>
    <!-- password label -->
    <div id=input_info>
        <label for="passwd">Password :</label>
    </div>
    <!-- password -->
    <input type="password" id="passwd" name="passwd" />
    <!-- submit button -->
    <p></p>
    <div id="button_position" align="center">
        <button type="button" onclick="loadXMLDoc()">Login</button>
    </div>
    <div id="state_msg" style="display:none"></div>
</body>

最佳答案

让我们看看它是如何工作的: 您的 xmlhttp 转到 servlet 并等待响应

第一种情况:登录名/密码无效 - 我们收到 HTML 响应 ( <h3>credentials invalid</h3> )

第二种情况:我们也有 HTML 响应! (HTML 页面/MovieDB/main.html)

让代码正常工作的最简单方法就是替换

response.sendRedirect("/MovieDB/main.html");

out.println("/MovieDB/main.html");

然后,如果登录名/密码正确,您将获得重定向路径作为响应。现在您可以使用 JavaScript 重定向用户。

关于java - 从 Servlet -> JavaScript 操作登录进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788319/

相关文章:

java - 安装 JDK 并设置 JAVA_HOME

java - 使用 GAE 的简单测验网站?

java - Java 中的模拟对象库

php - 使用端口 3307 连接到 MySql

java - 如何使用 servlet 创建 html 页面

java - 如何在 JSP 中打印双引号?

jquery - 从 jQuery ajax 使用类数组调用 asmx

php - 从jquery ajax post获取php中的json字符串

AngularJS $http 参数与数据——如何在服务器上获取 'data'?

Tomcat6部署