import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { sendLoginForm(response, false); } private void sendLoginForm(HttpServletResponse response, boolean withErrorMessage) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Login"); out.println(""); out.println(""); out.println("
"); if (withErrorMessage) out.println("Login failed. Please try again.
"); out.println("
"); out.println("

Login Page

"); out.println("
"); out.println("
Please enter your user name and password."); out.println("
"); out.println("
"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("
User Name:
Password:
"); out.println("
"); out.println("
"); out.println("
"); out.println(""); out.println(""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String password = request.getParameter("password"); if (login(userName, password)) { RequestDispatcher rd = request.getRequestDispatcher("AnotherServlet"); rd.forward(request, response); } else { sendLoginForm(response, true); } } boolean login(String userName, String password) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb"); System.out.println("got connection"); Statement s = con.createStatement(); String sql = "SELECT UserName FROM Users" + " WHERE UserName='" + userName + "'" + " AND Password='" + password + "'"; ResultSet rs = s.executeQuery(sql); if (rs.next()) { rs.close(); s.close(); con.close(); return true; } rs.close(); s.close(); con.close(); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } catch (SQLException e) { System.out.println(e.toString()); } catch (Exception e) { System.out.println(e.toString()); } return false; } }