import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FormLogin extends HttpServlet {
public static String USER_KEY = "ServletLogin.user";
public static String FIELD_USER = "username";
public static String FIELD_PASSWORD = "password";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
java.io.IOException {
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter();
resp.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");
String uri = req.getRequestURI();
HttpSession session = req.getSession();
String user = (String) session.getAttribute(USER_KEY);
if (user == null) {
login(out, uri);
return;
}
out.println("");
out.println("");
out.println("Welcome ");
out.println("");
out.println("");
out.println("Welcome to our site!
");
out.println("
");
out.println("");
out.println("");
out.flush();
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
java.io.IOException {
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(true);
String user = (String) session.getAttribute(USER_KEY);
if (user == null) {
String username = req.getParameter(FIELD_USER);
String password = req.getParameter(FIELD_PASSWORD);
if (!validUser(username, password)) {
out.println("");
out.println("Invalid User ");
out.println("" + "Invalid User!
");
out.println("Press the 'Back' button to try again");
out.println(" ");
out.flush();
return;
}
session.setAttribute(USER_KEY, username);
}
resp.sendRedirect(req.getRequestURI());
}
protected void login(java.io.PrintWriter out, String uri) throws java.io.IOException {
out.println("");
out.println("");
out.println("Login ");
out.println("Welcome! Please login
");
out.println("
");
}
protected boolean validUser(String username, String password) {
boolean valid = false;
if ((username != null) && (username.length() > 0)) {
valid = username.equals(password);
}
return valid;
}
}