LoginHandler.java 1.95 KB
Newer Older
1 2 3 4 5 6 7 8
package com.roshka.proyectofinal;

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import java.io.*;

public class LoginHandler extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        // Get the user's name and password
        String name = req.getParameter("name");
        String passwd = req.getParameter("passwd");

        // Check the name and password for validity
        if (!allowUser(name, passwd)) {
            out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
            out.println("<BODY>Your login and password are invalid.<BR>");
            out.println("You may want to <A HREF=\"/login.html\">try again</A>");
            out.println("</BODY></HTML>");
        }
        else {
            // Valid login. Make a note in the session object.
            HttpSession session = req.getSession(true);
            session.putValue("logon.isDone", name);  // just a marker object

            // Try redirecting the client to the page he first tried to access
            try {
                String target = (String) session.getValue("login.target");
                if (target != null)
                    res.sendRedirect(target);
                return;
            }
            catch (Exception ignored) { }

            // Couldn't redirect to the target. Redirect to the site's home page.
            res.sendRedirect(req.getScheme() + "://" +
                    req.getServerName() + ":" + req.getServerPort());
        }
    }

    protected boolean allowUser(String user, String passwd) {
        return true;  // trust everyone
    }
}