// File: LoginHandler.java // This servlet checks the username and password for validity. // If the client fails the check, they are told that access is denied. // If the client passes, that fact is recorded in their session object // and they are immediately redirected to the original target (obtained // from the Session object). import java.io.*; import java.util.*; import java.net.URL; import javax.servlet.*; import javax.servlet.http.*; public class LoginHandler extends HttpServlet { private Properties passwords; private String passwordFile; public void init(ServletConfig config) throws ServletException { super.init(config); try { // config.getInitParameter is specified within the servlet's // spec in the web.xml file passwords = new Properties(); passwords.load(getServletContext(). getResourceAsStream("/WEB-INF/passwords")); } catch(IOException ioe) { } catch(Exception excpt) { } } 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("Access Denied"); out.println("Your login and password are invalid.
"); out.println("Login"); } else { out.println("Welcome "+name+"
"); // 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) { out.println("Redirect failed!"); } // Couldn't redirect to the target. Redirect to the site's home page. res.sendRedirect(req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()); } out.println(""); } protected boolean allowUser(String user, String passwd) { String realPassword = passwords.getProperty(user); if (realPassword != null && realPassword.equals(passwd)) return true; // trust everyone return(false); } }