Управлять прогрессом входа из сервлета -> JavaScript - PullRequest
1 голос
/ 26 апреля 2011

Я очень новичок в веб-разработке.

Вещи, которые я настроил

* 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

  • Я знаю, что приведенный ниже код - это очень интересная сборка, но в любом случае я могу просто перенаправить на новую страницу?
  • Пожалуйста, не стесняйтесь меня поправлять.

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();
    }
}

HTML с AJAX Script

<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>

1 Ответ

0 голосов
/ 26 апреля 2011

Давайте посмотрим, как это работает: ваш xmlhttp отправляется в сервлет и ждет ответа

первый случай: неверный логин / пароль - мы получили HTML в ответ (<h3>credentials invalid</h3>)

Второй случай: у нас есть HTML в ответ! (HTML со страницей /MovieDB/main.html)

Самый простой способ заставить ваш код работать, это заменить

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

до

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

Тогда, если логин / пароль верны, вы получите путь для перенаправления в ответ. И теперь вы можете перенаправить пользователя с помощью JavaScript.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...