Java Server Pages - Applying VO, DAO 2
In application development, common design challenges can be tackled using software design patterns.
This post will discuss:
- Applying VO, DAO contd.
Applying VO and DAO contd.
The entire bulk of scriptlet code can be replaced with these design patterns:
First, a page that displays a table containing information from the SQL query:
SELECT * FROM userinfo;
The previously seen code is written in the DAO class:
highlightjs is broken: public class DAO{ private Variables; public DAO{ Class.forName(dbInfo); } //the below method creates a list that contains VO objects with values from a table public List
getAllVO(){ Connection con = null; PreparedStatement pSt = null; ResultSet rSt = null; List listVO = new ArrayList<>(); String query = "query"; try{ }catch(Exception e){} finally{ con.close(); pSt.close(); rSt.close(); //in try-catch block } return listVO; } }
And called in the JSP page:
<%
UserDAO dao = new UserDAO(); //constructor executes commands in constructor
List<UserVO> userList = dao.getAllUserList(); //execute dao method for class UserDAO
System.out.println(userList);
for(UserVO board : userList){ %>
<tr>
<td>
<%= board.getUserId() %>
</td>
<td>
<%= board.getUserPw() %>
</td>
<td>
<%= board.getUserName() %>
</td>
<td>
<%= board.getEmail() %>
</td>
</tr>
<% } %>
Avoiding scriptlets, the below JSTL code is identical in function:
</code></pre>
And called in the JSP page:
<c:forEach items="${userList}" var="element">
<tr>
<td><c:out value="${element.getUserId}"/></td>
<td><c:out value="${element.getUserPw}"/></td>
<td><c:out value="${element.getUserName}"/></td>
<td><c:out value="${element.getEmail}"/></td>
</tr>
</c:forEach>
JSTL searches for the setter/getter methods.
Another application of the patterns:
String insertU = null;
String insertP = null;
String redirectURL = null;
/* Handle request */
String formUserId = request.getParameter("userId");
String formUserPw = request.getParameter("userPw");
/* DB connection */
UserDAO dao = new UserDAO();
UserVO user = dao.getUserInfo(formUserId);
insertU = user.getUserId();
insertP = user.getUserPw();
if((formUserId.equals(insertU))&&(formUserPw.equals(insertP))){
session.setAttribute("s_id",formUserId);
redirectURL = "loginWelcome.jsp";
} else if((formUserId.equals(insertU))&&(!(formUserPw.equals(insertP)))){
redirectURL = "userPwFail.jsp";
} else if(!(formUserId.equals(insertU)) || (insertU == null)){
/* pass if Id null or incorrect */
redirectURL = "userIdFail.jsp";
}
response.sendRedirect(redirectURL);
Note that while the comparison logic remains the same, the data (business-side) logic is hoisted completely off to their respective classes.
An unrelated use of the patterns can also be seen in the below diagram (including code):
-gonkgonk