JSPExample
JSPExample
JSPExample
As mentioned in the application description, the user will have to enter his username and password, so first of all, we need a JSP that asks the user to input his username and password in their corresponding fields. To have this JSP, please follow these steps:
y y y y
Open eclipse Create a new "Dynamic Web Project" Name it "LoginExample" Create the JSP o In the "Web Content" folder, create a new JSP o Name it "LoginPage" o Place this code <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows1256"> <title>Login Page</title> </head> <body> <form action="LoginServlet"> Please enter your username <input type="text" name="un"/><br> Please enter your password <input type="text" name="pw"/> <input type="submit" value="submit"> </form> </body> </html>
y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y
As you can see; (in the LoginPage) when the user submits, the JSP calls "LoginServlet".This LoginServlet is intended to handle the Business logic associated with the request.
In the "src" folder, create a new "Package" Name it "ExamplePackage" In the "ExamplePackage", create a new "Servlet" Name it "LoginServlet" Place this code
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { try { UserBean user = new UserBean(); user.setUserName(request.getParameter("un")); user.setPassword(request.getParameter("pw")); user = UserDAO.login(user); if (user.isValid()) { HttpSession session = request.getSession(true); session.setAttribute("currentSessionUser",user); response.sendRedirect("userLogged.jsp"); //logged-in page } else response.sendRedirect("invalidLogin.jsp"); //error page }
y y
The login servlet instantiates a Bean that is of type "UserBean", and then calls the DAO named "UserDAO".
y y
Our UserBean is a class representing the User table in our Database (where each column in the user table has a corresponding instance variable with a setter and a getter method). The DAO, as said before, contains methods needed to communicate with the data source. In our example, the only needed method is the login method that checks if the username and password inputted by the user are valid or not.
Before implementing the DAO, you need to prepare your Data Source. 1. 2. 3. 4. Create a table in your DB Name it users Create the columns: 'FirstName', 'LastName', 'username', and 'password' Refer to your DB as a data source from "Administrative tools" in Control Panel
Please follow these steps to implement the Bean and the DAO
y
Create the "UserBean" class 1. In the " ExamplePackage ", create a new "Class" 2. Name it "UserBean" 3. Place this code 4. 5. 6. public class UserBean { 7. 8. private String username; 9. private String password; 10. private String firstName; 11. private String lastName; 12. public boolean valid; 13. 14. 15. public String getFirstName() { 16. return firstName; 17. } 18. 19. public void setFirstName(String newFirstName) { 20. firstName = newFirstName; 21. } 22. 23. 24. public String getLastName() { 25. return lastName; 26. } 27. 28. public void setLastName(String newLastName) {
29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. } 59.
lastName = newLastName; } public String getPassword() { return password; } public void setPassword(String newPassword) { password = newPassword; } public String getUsername() { return username; } public void setUserName(String newUsername) { username = newUsername; } public boolean isValid() { return valid; } public void setValid(boolean newValid) { valid = newValid; }
Create the "UserDAO" class 1. In the " ExamplePackage ", create a new "Class" 2. Name it "UserDAO" 3. Place this code 4. 5. 6. import java.text.*; 7. import java.util.*; 8. import java.sql.*; 9. 10. public class UserDAO 11. { 12. static Connection currentCon = null; 13. static ResultSet rs = null; 14. 15. 16. 17. public static UserBean login(UserBean bean) { 18.
19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72.
//preparing some objects for connection Statement stmt = null; String username = bean.getUsername(); String password = bean.getPassword(); String searchQuery = "select * from users where username='" + username + "' AND password='" + password + "'"; // "System.out.println" prints in the console; Normally used to trace the process System.out.println("Your user name is " + username); System.out.println("Your password is " + password); System.out.println("Query: "+searchQuery); try { //connect to DB currentCon = ConnectionManager.getConnection(); stmt=currentCon.createStatement(); rs = stmt.executeQuery(searchQuery); boolean more = rs.next(); // if user does not exist set the isValid variable to false if (!more) { System.out.println("Sorry, you are not a registered user! Please sign up first"); bean.setValid(false); } //if user exists set the isValid variable to true else if (more) { String firstName = rs.getString("FirstName"); String lastName = rs.getString("LastName"); System.out.println("Welcome " + firstName); bean.setFirstName(firstName); bean.setLastName(lastName); bean.setValid(true); } } catch (Exception ex) { System.out.println("Log In failed: An Exception has occurred! " + ex); } //some exception handling finally {
73. if (rs != null) { 74. try { 75. rs.close(); 76. } catch (Exception e) {} 77. rs = null; 78. } 79. 80. if (stmt != null) { 81. try { 82. stmt.close(); 83. } catch (Exception e) {} 84. stmt = null; 85. } 86. 87. if (currentCon != null) { 88. try { 89. currentCon.close(); 90. } catch (Exception e) { 91. } 92. 93. currentCon = null; 94. } 95. } 96. 97. return bean; 98. 99. } 100. } 101.
The DAO uses a class named "ConnectionManager" to get a connection with the DB. Create the "ConnectionManager" class: 1. In the " ExamplePackage ", create a new "Class" 2. Name it "ConnectionManager" 3. Place this code 4. 5. 6. import java.sql.*; 7. import java.util.*; 8. 9. 10. public class ConnectionManager { 11. 12. static Connection con; 13. static String url; 14. 15. public static Connection getConnection() 16. { 17.
18. try 19. { 20. String url = "jdbc:odbc:" + "DataSource"; 21. // assuming "DataSource" is your DataSource name 22. 23. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 24. 25. try 26. { 27. con = DriverManager.getConnection(url,"username","password"); 28. 29. // assuming your SQL Server's username is "username" 30. // and password is "password" 31. 32. } 33. 34. catch (SQLException ex) 35. { 36. ex.printStackTrace(); 37. } 38. } 39. 40. catch(ClassNotFoundException e) 41. { 42. System.out.println(e); 43. } 44. 45. return con; 46. } 47. } 48.
49. In the pasted code, Replace o "DataSource" with your Data Source name o "username" with your SQL Server username o "password" with your SQL Server password Finally, we are done with the logic and accessing the DB. So back to the interface, we need two JSPs; one for the valid login and another for the invalid. The two JSPs are
y y
userLogged.jsp: Displays a message to welcome the user, using his first and last names (retrieved from the DB) invalidLogin.jsp: Displays a message to inform the user that he is not a registered user
Steps to create the "userLogged" JSP 1. In the "WebContent" folder, create a new "JSP" 2. Name it "userLogged" 3. Place this code 4. 5. <%@ page language="java"
6. contentType="text/html; charset=windows-1256" 7. pageEncoding="windows-1256" 8. import="ExamplePackage.UserBean" 9. %> 10. 11. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 12. "http://www.w3.org/TR/html4/loose.dtd"> 13. 14. <html> 15. 16. <head> 17. <meta http-equiv="Content-Type" 18. content="text/html; charset=windows-1256"> 19. <title> User Logged Successfully </title> 20. </head> 21. 22. <body> 23. 24. <center> 25. <% UserBean currentUser = (UserBean (session.getAttribute("currentSessionUser"));%> 26. 27. Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %> 28. </center> 29. 30. </body> 31. 32. </html> 33.
Steps to create the "invalidLogin" JSP 1. In the "WebContent" folder, create a new "JSP" 2. Name it "invalidLogin" 3. Place this code 4. 5. <%@ page language="java" 6. contentType="text/html; charset=windows-1256" 7. pageEncoding="windows-1256" 8. %> 9. 10. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 11. "http://www.w3.org/TR/html4/loose.dtd"> 12. 13. <html> 14. 15. <head> 16. <meta http-equiv="Content-Type" 17. content="text/html; charset=windows-1256"> 18. <title>Invalid Login</title> 19. </head>
<body> <center> Sorry, you are not a registered user! Please sign up first </center> </body> </html>
Run the application , If you do not know any of the following steps, please check Steps 5-8 in the JSP Example
y y y y y
Set LoginPage.jsp to be your Home page (from web.xml) Add your Project to Tomcat Start Tomcat Go to http://Localhost/loginExample Test your project
Now your project should be working; if you would like to take a look at how the process went, go to the next page.