// Login.java // Login.java is the gate for entering the site. It checks if user is a valid // one and redirects the user to the appropriate pages. If user is not a valid one // then we show an error message and post it to the main page package com.project; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; public class Login extends HttpServlet { static final private String CONTENT_TYPE = "text/html; charset=iso-8859-9"; private Connection connection; private PreparedStatement getInfo; //Initialize global variables public void init() throws ServletException { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/project"); // prepare the PreparedStatement to get the students info getInfo = connection.prepareStatement("SELECT id,firstname,lastname,password " + "FROM students WHERE id = ?"); } // we throw an UnavailableException to indicate that servlet is // not available catch (Exception ex) { ex.printStackTrace(); throw new UnavailableException(ex.getMessage()); } } //Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); ResultSet result; // get the comming "post" variables String id = request.getParameter("id"); String password = request.getParameter("password"); String dbid = ""; String dbpassword = ""; out.println(""); out.println("Login"); out.println(""); // if both the student number and password are send if (id != null && password != null){ try { // attach id part to the prepared statement getInfo.setString(1,id); // execute PreparedStatement result = getInfo.executeQuery(); // if result has returns a ResultSet if(result.next()){ dbid = result.getString(1); dbpassword = result.getString(4); // if the user is valid one if (dbid.equals(id) && dbpassword.equals(password)){ String dbfirstname = result.getString(2); String dblastname = result.getString(3); // We here create session values for each user // create a session (true) because there exist no previous session // if one exists use it HttpSession session = request.getSession(true); session.setAttribute("id",dbid); session.setAttribute("firstname",dbfirstname); session.setAttribute("lastname",dblastname); session.setAttribute("password",dbpassword); } // user id is mathcing but password is wrong if (dbid.equals(id) && !(dbpassword.equals(password))) { // HERE WE WILL HANDLE THE WRONG PASSWORD CONDITION out.println("WRONG PASSWORD"); } } // no such a user else { // HERE WE WILL HANDLE THE NO SUCH A USER CONDITION out.println("No such a user!"); } } catch (Exception ex) { ex.printStackTrace(); } } out.println(""); } //Clean up resources public void destroy() { } }//EN">