import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import com.brainysoftware.java.StringUtil;
public class SessionLoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
sendLoginForm(response, false);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (login(userName, password)) {
//send cookie to the browser
HttpSession session = request.getSession(true);
session.setAttribute("loggedIn", new String("true"));
response.sendRedirect("Content2Servlet");
}
else {
sendLoginForm(response, true);
}
}
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("If you think you have entered the correct user name" +
" and password, the cookie setting in your browser might be off." +
"
Click here for information" +
" on how to turn it on.
");
}
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("");
}
public static boolean login(String userName, String password) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");
Statement s = con.createStatement();
String sql = "SELECT UserName FROM Users" +
" WHERE UserName='" + StringUtil.fixSqlFieldValue(userName) + "'" +
" AND Password='" + StringUtil.fixSqlFieldValue(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;
}
}