2017-06-29 8 views
1

テキストファイルから入力されたユーザー名とパスワードを比較し、ユーザー名/パスワードが間違っているかアクセスが許可されているかを表示するログインフォームを作成しました。応答を取得し、サーブレットの応答に従って動作するJavascriptコード

<form role="form" action="/traveositelogin" method="post"> 
         <div class="form-group"> 
          <label class="sr-only" for="form-username">Username</label> 
          <input type="text" placeholder="Username..." class="form-username form-control" id="username"> 
          <p id="UsernameIncorrect" hidden>Incorrect Username. Try Again</p> 
         </div> 
         <div class="form-group"> 
          <label class="sr-only" for="form-password">Password</label> 
          <input type="password" placeholder="Password..." class="form-password form-control" id="password"> 
          <P id="PasswordIncorrect" hidden>Incorrect Password. Try Again.</p> 
         </div> 
           <button type="submit" class="btn" id="Login">Login</button> 
            <p><a href="contact.html"> Forgot Password?</a></p> 

        <div class="form-group"> 
       </div> 

これは私のサーブレットのコードです:

package com.traveosoft; 

import java.io.IOException; 
import java.util.Properties; 

import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Scanner; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 

public class TraveoWebsiteLoginServlet extends HttpServlet { 
    @Override 
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
     throws IOException { 
     resp.setContentType("text/plain"); 
     resp.getWriter().println("Hello, this is a testing servlet. \n\n"); 
     Properties p = System.getProperties(); 
     p.list(resp.getWriter()); 

    } 

    public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws IOException { 
      String filePath = "{login.txt}"; 
      String username = null; 
      String password = null; 

     //resp.setContentType("text/plain"); 
     //resp.getWriter().println("Hello, this is a testing servlet. Post method \n\n"); 
     //Properties p = System.getProperties(); 
     //p.list(resp.getWriter()); 

     if (req.getParameter("Login")!= null) 
     { 
      username = req.getParameter("username"); 
      password = req.getParameter("password"); 
      //resp.sendRedirect("index.html"); 
     } 
    try 
      { 
       FileInputStream fstream = new FileInputStream("login.txt"); 
       // Use DataInputStream to read binary NOT text. 
       BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
       String strLine; 
       int count = 0; 

       while((strLine = br.readLine())!= null) 
       { 
        //Enter userName 
        String[] creds = strLine.split(","); 
        System.out.println("creds[0], creds[1]:" + creds[0] + "," +creds[1]); 
        //System.out.println("User name from the file is:"+ creds[0]); 
        if (creds[0].equals(username)) 
        { 
         //user name matches. So we need to check for password now 
         count++;       
         if (creds[1].equals (password)) 
         { 
          //Great... password also matches. Allow the user access to our repository 
          System.out.println("Allow access"); 
         } 
         else 
         { 
          // Password didn't match. Ask the user to reenter the password 
          System.out.println("Wrong password. Try Again."); 
         } 
         break; 
        } 

        //strLine = br.readLine(); 
        //count++; 
        //Enter Password 
        //System.out.println("Password from the file is:"+ creds[1]); 
       } 
       if (count == 0) 
       { 
        // No user name matched with the user name entered by the user. So user name itself is wrong 
        System.out.println("Your user name is wrong. Try Again."); 
       } 
       fstream.close(); 
       br.close(); 
      } 
      catch (Exception e) 
      { 
       System.err.println("Error: " + e.getMessage()); 
      } 
     } 

} 

は、どのように私は、ユーザー名が間違っているとき、版画「ユーザ名が間違っている」と、JavaScriptコードを書くことができます。パスワードが間違っていると、 "パスワードが間違っています"と表示されます。両方が正しい場合は、リソースが保存されているページへのハイパーリンク参照を置くことができます。

jspファイルの代わりにjavascriptのサンプルコードをいただければ幸いです。私はまだこのすべてを学んでいます、どんな助けも本当に感謝します。前もって感謝します。

+0

を送信することに関連するリンクである


// Responseオブジェクト:[「ユーザー名および/またはパスワードが無効です。」 - なぜウェブサイトを行いますどのようなものが間違っているかをユーザに知らせるのではなく、このようなメッセージを表示してください。](https://security.stackexchange.com/questions/17816/username-and-or-password-invalid-why-do-websites-show-thisメッセージの種類-i /) – Andreas

+0

@ Andreas私は応答に応じてJavaScriptコードを書こうと思っていました。 –

答えて

0

私が正しく理解していれば、JSP経由で送信するのではなく、サーバー側からクライアント側に直接応答オブジェクト(またはメッセージ)を送信したいと考えています。あなたは、次の手順に従うことができ
...あなたが行うにはいくつかのより多くの努力を必要とすることを行うために

1.応答オブジェクトを作成します。
2.そのオブジェクトをJSON形式に変換します。
3.応答コンテンツタイプをtext/jsonとして設定し、応答を設定します。 JavaScriptに

  public class ResponseMessage { 
       private boolean isLoginSuccess; 
       private String errorMessage; 

       // Getters and setters ... 
      } 

      // Servlet code 

      ResponseMessage message = new ResponseMessage(); 
      message.setError(true); 
      message.setErrorMessage("Your error message"); 
      Gson gson = new Gson(); // GSON: library to convert Java object to JSON 
      String content = gson.toJson(message); 
      response.setContentType("text/json"); 
      response.getWriter().print(content); 

JSコード

function processRequest() { 
var result = jQuery.ajax ({ 
    url: "your.url", 
    method: "post", 
    async: false, 
    data: "" 
}); 

// Create JS object from JSON 
var message = jQuery.parseJSON(result.responseText); 

// Now you can show your message 
if(message.isLoginSuccess) { 
    alert("Welcome"); 
}else{ 
    alert("Login Failed"); 
} 
} 
+0

um、先生、system.outです。印刷ラインは、サーブレットにあるテキストを印刷していないなど、私のコードで動作していません。なぜなら私はこれに非常に新しいので、ゲッターズとセッターズによく熟していないからです。 –

+0

こんにちは、ゲッターとセッターは、クラス属性の値をそれぞれ返す単純なメソッドだけです。 Like public getMessage(){ 返すthis.mesage; } – Krishnan

+0

@RashSrivastava私はサーブレットの基本的な概念を理解することをお勧めします。いくつかのオンラインチュートリアルサイトを参照して、先進的な概念から始めることができます。がんばろう! – Krishnan

関連する問題