Analysis and Design
If you do not have the database table created or do not have any user in that table, please refer the analysis and design from the article Simple Login Application for details.
Taking inspiration from the previous article, we will create similar components for our simple login app using struts 2.
So, below are the identified components:
Let us look at each identified component and it’s role in our application:
- Login.jsp – It would present the login screen to enter user id and password. It also displays any validation errors and login failure message.
- Home.jsp – Simple JSP which displays a welcome message after successful login
While we take inspiration from LogonServlet of our previous example, we improve the design to not include any database connectivity code in our Action class. To achieve this, we will refactor all the DB access / calls to a Helper class by the name DBHelper.java. This also helps in modifying the code, if we tomorrow decide to use Entity Beans (EJB) or hibernate to access the database instead of raw JDBC code with minimum impact on our Action class. The LogonAction performs the following tasks.
• Perform basic empty check on server side before calling the database
• Call our DB Helper class, with user name and password to check, if the combination exists.
It will perform all task related to getting connection to the DB, executing a query and method to return Boolean indicating, if record was available or not in the DB. We do not write method like, isUserPasswordValid in this class, as it is a generic low level class, and should not be aware about the logic implemented in the classes calling it. Below would be the methods:
public boolean containsResults(String query, String params) – The params we have created as a String array, which will have both user name and password. If the values required for the where clause of the SQL query are of different datatype, we might need a different approach. This method is invoked by the LogonAction
private Connection getConnection() – Internally used to get a Connection object for the DB call.
private void closeConnection(Connection conn) - Closes an open connection after the query has been executed.