Как проверить пользователя, когда он входит в систему и хочет изменить свой старый пароль на новый пароль - PullRequest
0 голосов
/ 05 февраля 2020

Я создаю динамический c веб-проект, в котором пользователь сначала регистрируется, а затем может войти в систему. В LoginServlet я создал сеанс для запрашивающего пользователя Также он может сменить пароль здесь я использовал текстовый файл в локальной системе для хранения пользовательских данных Моя проблема в том, что я не могу применить logi c в сервлете с измененным паролем, посмотрите в этом сервлете , в котором я упоминаю , не в состоянии применить logi c, что как Я должен проверить данные пользователя из текстового файла и сравнить со старым паролем новый пароль, повторить пароль и обновить новый пароль.

Домашняя страница Html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>HomePage</h1>
<a href="Registration.html">Click to Register</a><br>
<a href="LogIn.html">Click to Login</a>
</body>
</html>

changePassword Html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>changePassword</h1>
<form action="changePassword" method="post">
Enter Your OldPassword<input type="password" name="pass"><br>
Enter Your NewPassword<input type="password" name="npass"><br>
Enter Your Password<input type="password" name="rpass"><br>
<input type="submit">
</form>
</body>
</html>

LogServlet

package com.satateMng.com;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

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



/**
 * Servlet implementation class LogInServlet
 */
public class LogInServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogInServlet() {
        super();
        System.out.println("In no-arg constr() of LS");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("In doGet() of LS");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("In doPost() of Ls");
        /*
         * access user inputs validate if validation succeed,create session and
         * store email if validation failed,show error msg
         */
        String email = request.getParameter("email");
        String pass = request.getParameter("pass");

        StringBuilder sb = new StringBuilder();
        if (email == null || email.trim().equals(""))
            sb.append("Enter Correct email<br/>");
        if (pass == null || pass.trim().equals(""))
            sb.append("Enter your password<br/>");

        PrintWriter pw = response.getWriter();

        String msg = sb.toString();
        if (!msg.equals("")) {
            // validation failed
            pw.write("<html><body><h1><b>" + msg + "</b></h1></body></html>");
        } 
        else
        {
            // success
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(Constants.USERFILE));
                String line;
                while ((line = br.readLine()) != null)
                {
                    System.out.println("coming line=" + line);
                    String[] sa=line.split("=");
                    if (email.equals(sa[0]) && pass.equals(sa[1])) 
                    {
                        // valid user
                        // create session
                        HttpSession session = request.getSession(true);
                        session.setAttribute(Constants.USER, email);

                        pw.write("<html><body><h1>Welcome " + email+ " </h1><a href='logout'>LogOut</a><br/><a href='ChangePassword.html'>Change Password</a></body></html>");
                        return;
                    }
                }
                pw.write(
                        "<html><body><h1><b>Your email/password combination is incorrect!try again..</b></h1></body></html>");
            }
            catch (IOException e)
            {
                // TODO: handle exception
                e.printStackTrace();
                pw.write("<html><body><h1>Error</h1><b>Oops something gone complex" + e.getMessage()
                        + "</b></body></html>");
                return;
            }
            finally
            {
                if (br != null)
                    br.close();
            }
        }
    }

}

ChangePasswordServlet

package com.satateMng.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ChangePasswordServlet
 */
public class ChangePasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangePasswordServlet() {
        super();
        System.out.println("In no-arg constr() of CP..");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("In doPost() of CP..");
        /*
         * get the session for client
         * if session doesn't exist,then scold the user
         * if session exist,open the file,validate if old password is correct and 
         * then update the file contents to reflect new password change for email id of user
         * 
         */
        HttpSession session=request.getSession(false);
        PrintWriter pw=response.getWriter();
        if(session==null)
        {
            pw.write("<html><body><h1>we dont know who you are..</h1></body></html>");
        }
        else
        {
            String email=(String) session.getAttribute(Constants.USER);
            String opass=request.getParameter("pass");
            String npass=request.getParameter("npass");
            String rpass=request.getParameter("rpass");


            /*
             * validate if email is correct by looking into file
             * and then update
             */
            BufferedReader br=null;
            try
            {
                br=new BufferedReader(new FileReader(Constants.USERFILE));
                String line=br.readLine();
               while(line!=null)
               {
                   System.out.println("coming line"+line);
                   String[] sa=line.split("=");
                   if(email.equals(sa[0]) || opass.equals(sa[1]))
                   {
                     //not able to apply logic what I should write code over here thank you
                   }

               }

            }
            catch(IOException e)
            {
                // TODO: handle exception
                e.printStackTrace();

            }
            finally
            {
                if(br!=null)
                    br.close();
            }
            pw.write("<html><body><h1><b>your password has changed successfully..</b></h1></body></html>");
        }
    }

}

1 Ответ

2 голосов
/ 05 февраля 2020

После того, как вы проверите, что адрес электронной почты и старый пароль пользователя верны, вы можете проверить, равен ли npass rpass, если это правда, тогда просто обновите пароль, в противном случае, если оба они различны, дайте сообщение пользователю не тот же пароль .ie:

if(email.equals(sa[0]) && opass.equals(sa[1]))         
      { 
     //if new password and retype password is same do below      
     if(npass.equals(rpass)){

             //write your update code   
           BufferedWriter bw = null;
        try 
        {
         bw = new BufferedWriter(new FileWriter(Constants.USERFILE));
         bw.write(rpass);
        bw.newLine();
        }
        catch (IOException e)
        {
        e.printStackTrace();
        } 
        finally 
        {
        if (bw != null)
            bw.close();
        }
       }
      }   
      else
      {
        //if new password and retype password is not same 
           if(!npass.equals(rpass)){
                    //setting some message
                   request.setAttribute("passerrormsg2", "Password Mismatch");
                  //redirect to changePassword.Html

            } 
               //if old pass is not equal 
            if( !opass.equals(sa[1])){  
                   //set some message
                   request.setAttribute("passerrormsg1", "Old Password is not correct");
                  //redirect to changePassword.html         
            } 

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