OiO.lk Blog java Login servlet app with session and cookies
java

Login servlet app with session and cookies


I need to codificate a login servlet in java, using cookies as well. These are the requirements:

-The page has to offer both registration and login (the user choose what to do). If they choose to register, they will be redirected to the login page after introducing the information (just name, username and password, the same for login and register).
-In the case of the login, the app needs to count the login attempts (up to 2 incorrect attempts) and then show a message for the user letting them know that there are no more attempts until 10 seconds later. This has to be done with a cookie.
-The app has to check if the user that is logging is already in the database (a fake one, just an ArrayList).
-When the login is successful, a message of "welcome" will be shown.
-The user has to be able to log out as well.

This is what I have so far:

@WebServlet("/loginservlet")
public class LoginServlet extends HttpServlet {

    private static final int ATTEMPTS_MAX = 2;
    private static final Logger logger = Logger.getLogger(LoginServlet.class.getName());
    ArrayList<User> list = new ArrayList<>();
 
    
    public LoginServlet() {
        User u1 = new User("Alba", "alba01", "pass");
        User u2 = new User("Maira", "maira01", "pass");
        User u3 = new User("Carol", "carol01", "pass");
        User u4 = new User("Debora", "debo01", "pass");
        list.add(u1);
        list.add(u2);
        list.add(u3);
        list.add(u4);
    }
 
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
       
        String task = request.getParameter("task");
        if (task == null) {
            response.sendRedirect("index.html");
            return;
        }
        switch (task) {
            case "formlog":
                showFormLog(request,response);
                break;
            case "formreg":
                showFormReg(request,response);
                break;
            case "register":
                processReg(request,response);
                break;
            case "login":
                processLog(request,response);
                break;
            case "default":
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid task");
                break;
        }
    }
 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    
    @Override
    public String getServletInfo() {
        return "Short description";
    }

    private void showFormLog(HttpServletRequest request, HttpServletResponse response) {
        try {
            RequestDispatcher dispatcher=null;
            dispatcher=request.getRequestDispatcher("/formlog.jsp");
            dispatcher.forward(request, response);
        } catch (ServletException | IOException ex) {
            logger.log(Level.SEVERE, "Error showing the log form", ex);
        }
    }
    private void showFormReg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            RequestDispatcher dispatcher = null;
            dispatcher=request.getRequestDispatcher("/formreg.jsp");
            dispatcher.forward(request, response);
        } catch (ServletException ex) {
            logger.log(Level.SEVERE, "Error showing the reg form", ex);
    }
}
 
    private void processReg(HttpServletRequest request, HttpServletResponse response) throws IOException {
                String nameReg=request.getParameter("name");
                String usernameReg=request.getParameter("username");
                String passReg=request.getParameter("password");
                
                if(nameReg !=null && usernameReg !=null && passReg !=null){
                    list.add(new User(nameReg, usernameReg, passReg));
                    response.sendRedirect("loginservlet?task=formlog");
                }else{
                    response.sendRedirect("loginservlet?task=formreg");
                }
    }
 
    private void processLog(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                String nameLog=request.getParameter("name");
                String usernameLog=request.getParameter("username");
                String passLog=request.getParameter("password");
                
                logger.info("Login attempt: name=" + nameLog + ", username=" + usernameLog);                
                
                if (nameLog == null || usernameLog == null || passLog == null) {
                request.setAttribute("error", "All info required");
                request.getRequestDispatcher("/formlog.jsp").forward(request, response);
                   return;
    }
                
                Cookie[] cookies = request.getCookies();
                int failedAttempts= 0;
                Cookie cookieAttempts = null;

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("failedAttempts")) {
                            failedAttempts= Integer.parseInt(cookie.getValue());
                            cookieAttempts = cookie;
                            break;
                        }
                    }
                }
                
                if (failedAttempts>= ATTEMPTS_MAX) {
                request.setAttribute("error", "Too many attempts. wait 10 seconds.");
                RequestDispatcher dispatcher = request.getRequestDispatcher("/formlog.jsp");
                dispatcher.forward(request, response);
                return;
                }
                
                boolean correctLogin= false;
                for (User user : list) {
                    if (user.getName().equals(nameLog) && user.getUsername().equals(usernameLog) && user.getPass().equals(passLog)) {
                    correctLogin= true;
                    break;
                    }
                }
                
                
                if (correctLogin) {
                    HttpSession session = request.getSession();
                session.setAttribute("username", usernameLog);
                    
                    if (cookieAttempts != null) {
                    cookieAttempts.setValue("0");
                    cookieAttempts.setMaxAge(0);
                    response.addCookie(cookieAttempts);
                    }
                response.sendRedirect("welcome.jsp");
                } else {failedAttempts++;
                
                
                if (cookieAttempts== null) {
                        cookieAttempts= new Cookie("failedAttempts", String.valueOf(failedAttempts));
                } else {
                    cookieAttempts.setValue(String.valueOf(failedAttempts));
                }
                cookieAttempts.setMaxAge(10);
                response.addCookie(cookieAttempts);
        
                request.setAttribute("error", "Incorrect user or pass. Intento " + failedAttempts+ " de " + ATTEMPTS_MAX);
                RequestDispatcher dispatcher = request.getRequestDispatcher("/formlog.jsp");
                dispatcher.forward(request, response);
    }
}
                               
}

I get to see the forms when I execute in a browser but it doesnt work at all.



You need to sign in to view this answers

Exit mobile version