9 Replies Latest reply: Apr 23, 2008 2:30 PM by 807601 RSS

    Simple J2EE Design patterns for newbies

    807601
      Hey

      I've managed to get a basic understanding of how J2EE web applications are put together. I've done some simple stuff like jsp's posting to servlets to do database inserts for example.

      In an effort to get a more well rounded understanding of whats going on I want to write a simple phonebook web app. As my previous adventures in web development have been php pages that mixed php and html. I really want to get away from the bad habits that people say PHP can encourage and get a proper MVC setup going. I'll describe my plan and then all you guys can rip it apart and hopefully in the process I will learn something Smile

      In the case of a user wishing to insert a new record. I imagine the process to be the following.

      JSP/HTML form that posts to a servlet, the servlet then uses a bean to handle the database interaction and once the bean has finished the jdbc work the servlet forwards the user to another jsp that displays the current contents of the table.

      So, for example I will write a bean that has 4 methods. One to read the full contents of the table, one to insert a new record, one to update and finally one to delete.

      Depending on what parameters are passed to the servlet via HTTP POST it will call the corresponding javabean method.

      Am I on the right track?

      Thanks
        • 1. Re: Simple J2EE Design patterns for newbies
          800435
          It's ok!

          You can also take a look at [Expression Language|http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html] to avoid scriptlets mixed with html.

          Later you can start looking at some frameworks like Spring and Struts
          • 2. Re: Simple J2EE Design patterns for newbies
            807601
            Eamo wrote:
            Am I on the right track?
            Yes basically. Look into DAO pattern for all the database access. This will put 1 more layer in your application so: jsp -> servlet -> action class (POJO where all your business logic is) -> DAO (only has database access code in it).

            When you have this working you will want to look at something similar to Spring MVC or Struts 2 which will do all the wiring together for you. Also Spring is really good for configuring your DAO's.
            • 3. Re: Simple J2EE Design patterns for newbies
              807601
              I also suggest your servlet (which acts as a controller in MVC design) take in all url requests for all JSP pages, update button clicks, and hyperlink clicks, calls the appropriate business logic, put data in request scope, then dispatch to the appropriate JSP page. However, when a request first comes in, first verify the person is authenicated (logged in), and authorized to view the requested JSP page (what role he's in). If not, dispatch to an error page. This will add basic security to your project.
              • 4. Re: Simple J2EE Design patterns for newbies
                796254
                Learn Spring:

                http://www.springframework.org

                %
                • 5. Re: Simple J2EE Design patterns for newbies
                  807601
                  Ok well this is what I have come up with so far

                  Servlet
                  public void doGet (HttpServletRequest req, HttpServletResponse resp)
                       throws ServletException, IOException
                       {
                          out = resp.getWriter();
                          
                          String action = req.getParameter("action");
                              String name = req.getParameter("name");
                              String phone = req.getParameter("phone");
                              DbWorker db = new phonebook.DbWorker();
                              if (action.equals("insert")){
                              db.doInsert(name,phone);    
                              } else if (action.equals("delete")){
                              db.doDelete(name,phone);    
                              } else {
                              out.println("you didnt ask me to do anything");    
                              }  
                  And the "Bean" it uses to do the database work is below. Note: The term java bean is used all in all the books and online forums I have seen. Whats so strange about its use today (just curious). Anyway the db stuff
                  public void doInsert(String name, String phone){
                          String query = "Insert into test(name,email) values(?,?)";
                          try{    
                              PreparedStatement stmt = con.prepareStatement (query);
                              stmt.setString(1, name);
                              stmt.setString(2, phone);
                              stmt.executeUpdate();
                          } catch (SQLException e){
                              
                          }
                      }
                          public void doDelete(String name, String phone){
                              String query = "delete from test where name = ? and email = ?";
                              try{    
                              PreparedStatement stmt = con.prepareStatement (query);
                              stmt.setString(1, name);
                              stmt.setString(2, phone);
                              stmt.executeUpdate();
                          } catch (SQLException e){
                              
                          }  
                  The code above works without any problems. However I now want to write a method to execute a select statement and I want it to be able to return the results to a jsp that can then iterate through and print out the results. My guess is that i create a method to return the resultsset array that a jsp page picks up by using the standard tag library to go through it and print out the results?
                  • 6. Re: Simple J2EE Design patterns for newbies
                    807601
                    I've created the following method in the bean
                    public ResultSet doResultSet(){
                                String query = "select * from test";
                                try{
                                Statement stmt = con.createStatement ();
                                ResultSet rs = stmt.executeQuery (query);
                                return rs;
                                
                            } catch (SQLException e){
                                
                            }
                     
                    First problem is that my ide is complaining that there is no return statement set?!?! I thought I had done that with "return rs;"

                    From doing some reading I've seen this the following code which I think I could take as an example of how to do what i want. This is a cut and paste from a site i found googling. Obviously things will need to change! but is what is being done here what Im looking for?
                     <html>
                    <%@page import ="java.sql.*" %>
                    <jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/>
                    <%@ page buffer=35 %>
                    <%@ page errorPage="error.jsp" %>
                    <html>
                    <head>
                    <title>Phone Book Search Results</title>
                    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head>
                    <body bgcolor="#FFFFFF"> <b>Search Results</b> <p>
                    <% String q = request.getParameter("query");
                    ResultSet rs = phone.getResultSet(q);
                    %>
                    <% if (rs.wasNull()) {
                    %>
                    "NO RESULTS FOUND"
                    <%
                    } else
                    %>
                    <table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td> <div align="center">Email</font></b></div> </td> </tr>
                    
                    <% while(rs.next()) { %> <tr> <td>
                    <%= rs.getString("first_name") %></td> <td><%= rs.getString("last_name") %></td> <td><%= rs.getString("phone_number") %>
                    </td> <td>
                    <%= rs.getString("e_mail") %>
                    </td> </tr>
                    <% } %>
                    </table> 
                    • 7. Re: Simple J2EE Design patterns for newbies
                      807601
                      First problem is that my ide is complaining that there is no return statement set?!?! I thought I had done that with "return rs;"
                      At the end of method, that's outside the try-catch block add an empty return statement: return null;
                      • 8. Re: Simple J2EE Design patterns for newbies
                        807601
                        Hi
                        I'm designing an application using spring MVC 1.2.
                        I'm facing some serious prob.How do i transfer the control to either success or failure page after validating the form input with the database. I'm using SimpleFormController's onSubmit() method.Though the input form elements r getting saved using spring:bind on the jsp but the onSubmit() method is always returning the success page mapped in theapp-servlet.xml file.
                        How do i decide whether to display the success or failure page based on validation with the database and how to display database values on the success page?
                        Kindly help.
                        • 9. Re: Simple J2EE Design patterns for newbies
                          796254
                          rohitturs wrote:
                          Hi
                          I'm designing an application using spring MVC 1.2.
                          Spring's up to version 2.5.4 now. Why 1.2?
                          I'm facing some serious prob.How do i transfer the control to either success or failure page after validating the form input with the database. I'm using SimpleFormController's onSubmit() method.Though the input form elements r getting saved using spring:bind on the jsp but the onSubmit() method is always returning the success page mapped in theapp-servlet.xml file.
                          How do i decide whether to display the success or failure page based on validation with the database and how to display database values on the success page?
                          Kindly help.
                          A Validator is usually the way to do it.

                          But Validators are usually a server-side form validation to make sure that required fields are in place, formats are correct, etc. When you say "validating form input with the database", it sounds like deeper business logic than that.

                          You can still use the Validator framework. Just create a DataBinder and create Errors as needed.

                          %