import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; 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("Access Denied"); out.println("Your login and password are invalid.
"); out.println("You may want to try again"); out.println(""); } 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. String scheme = req.getScheme(); String serverName = req.getServerName(); int p = req.getServerPort(); String port = (p == 80) ? "" : ":" + p; res.sendRedirect(scheme + "://" + serverName + port); } } protected boolean allowUser(String user, String passwd) { return true; // trust everyone } }