1

Okay, so I had created my first jsp page which basically created 3 drop downs and populated them with information pulled from a database.

However, I was told that this was bad code and I should use a servlet for that database function and error handling, and let the jsp strictly do the displaying.

The original jsp code is below:

<%@page import="java.sql.*"%>
<!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=ISO-8859-1">
                <title>Code Selector</title>
        </head>
        <body> 
            <h1>Please select the applicable codes:</h1> 
            <select name='Code' onchange="showState(this.value)">  
            <option value="none">Select a code</option>  
            <%
                //Pulls the ids and decriptions from the codes table and stores them in the first drop down
                try
                {
                    Class.forName("driverName").newInstance();  
                    Connection con = DriverManager.getConnection("serverURL","username","password");  
                    Statement stmt = con.createStatement();  
                    ResultSet rs = stmt.executeQuery("select id, descr from codes");

                    while(rs.next())
                    {
                        %>
                            <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%> <%=rs.getString(2)%></option>  
                        <%
                    }

                    //Closes the database connection
                    stmt.close();
                    con.close();
                }
                catch (ClassNotFoundException e)
                {
                    System.err.println("ClassNotFoundException: " + e.getMessage());
                } 
                catch (SQLException e)
                {
                    System.err.println("SQLException: " + e.getMessage());
                }
                catch (Exception e)
                {
                    System.err.println("Generic Exception: " + e.getMessage());
                }       
            %>
            </select>  
            <br>
            <br>
            <select name='Code2' onchange="showState(this.value)">  
            <option value="none">Select a code</option>  
            <%
                //Pulls the ids and decriptions from the codes table and stores them in the second drop down
                try
                {
                    Class.forName("driverName").newInstance();  
                    Connection con = DriverManager.getConnection("serverURL","username","password");  
                    Statement stmt = con.createStatement();  
                    ResultSet rs = stmt.executeQuery("select id, descr from codes");

                    while(rs.next())
                    {
                        %>
                            <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%> <%=rs.getString(2)%></option>  
                        <%
                    }

                    //Closes the database connection
                    stmt.close();
                    con.close();
                }
                catch (ClassNotFoundException e)
                {
                    System.err.println("ClassNotFoundException: " + e.getMessage());
                } 
                catch (SQLException e)
                {
                    System.err.println("SQLException: " + e.getMessage());
                }
                catch (Exception e)
                {
                    System.err.println("Generic Exception: " + e.getMessage());
                }       
             %>
            </select>
            <br>
            <br>
            <select name='otherCode' onchange="showState(this.value)">  
            <option value="none">Select a other code</option>  
            <%

                //Pulls the ids and decriptions from the other codes table and stores them in the third drop down
                try
                {
                    Class.forName("driverName").newInstance();  
                    Connection con = DriverManager.getConnection("serverURL","username","password");  
                    Statement stmt = con.createStatement();
                    ResultSet rs2 = stmt.executeQuery("select id, descr from other_codes");

                    while(rs2.next())
                    {
                        %>
                            <option value="<%=rs2.getString(1)%>"><%=rs2.getString(1)%> <%=rs2.getString(2)%></option>  
                        <%
                    }

                    //Closes the database connection
                    stmt.close();
                    con.close();
                }
                catch (ClassNotFoundException e)
                {
                    System.err.println("ClassNotFoundException: " + e.getMessage());
                } 
                catch (SQLException e)
                {
                    System.err.println("SQLException: " + e.getMessage());
                }
                catch (Exception e)
                {
                    System.err.println("Generic Exception: " + e.getMessage());
                }       
            %>
      </select>
      <br> 
      <br>
      <form method = "post">
        <input type="submit" value="Submit">
        <%
            try
            {
                String Code = request.getParameter("Code");
                String Code2 = request.getParameter("Code2");
                String otherCode = request.getParameter("otherCode");

                Class.forName("driverName").newInstance();  
                Connection con = DriverManager.getConnection("serverURL","username","password");  
                Statement stmt = con.createStatement();
                //ResultSet rs3 = stmt.executeQuery();

                System.out.println("This is the first code: " + Code);
                System.out.println("This is the second code: " + Code2);
                System.out.println("This is the other code: " + otherCode);

                con.close();
                stmt.close();

            }
            catch (ClassNotFoundException e)
            {
                System.err.println("ClassNotFoundException: " + e.getMessage());
            } 
            catch (SQLException e)
            {
                System.err.println("SQLException: " + e.getMessage());
            }
            catch (Exception e)
            {
                System.err.println("Generic Exception: " + e.getMessage());
            } 
        %>
        <script>
            window.close();
        </script>
      </form>
      </body> 
</html>

And so far, this is what I have with the new jsp and servlet page:

codes-selector.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
    <HEAD>
        <TITLE>
            Codes
        </TITLE>
    </HEAD>
    <BODY BGCOLOR="#FDF5E6">
        <H2 ALIGN="CENTER">
            Please select the applicable codes:
        </H2>
        <FORM ACTION="http://localhost:8088/SomeProgram" METHOD="GET">
            <CENTER>
                <select name='code' onchange="showState(this.value)">  
                    <option value="none">Select a code</option>  
                </select>
                <BR>
                <BR>
                <select name='code2' onchange="showState(this.value)">  
                    <option value="none">Select a code</option>  
                </select>
                <BR>
                <BR>
                <select name='otherCode' onchange="showState(this.value)">  
                    <option value="none">Select an other code</option>  
                </select>
                <BR>
                <BR>
                <!-- Press this to submit form -->
                <INPUT TYPE="SUBMIT" VALUE="Submit"/>
            </CENTER>
        </FORM>
    </BODY>
</HTML>

PullCodes.java (servlet):

package com.firstservlet.alfresco;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

/**
 * Servlet implementation class PullCodes
 */
@WebServlet("/PullCodes")
public class PullCodes extends HttpServlet 
{
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PullCodes() 
    {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        String code = request.getParameter("code");
        String code2 = request.getParameter("code2");
        String otherCode = request.getParameter("otherCode");

        try
        {
            Class.forName("driverName").newInstance();  
            Connection con = DriverManager.getConnection("url","username","password");  
            Statement stmt = con.createStatement();  
            ResultSet rs = stmt.executeQuery("select id, descr from ref_codes");
            ResultSet rs2 = stmt.executeQuery("select id, descr from ref_other_codes");

            try
            {
                while(rs.next())
                {
                    //Is this correct?
                                    code+=("<option value=\"" + rs.getString(1) + "\">" + rs.getString(1) + " " + rs.getString(2) + "</option>");
                }

                //Closes the database connection
                stmt.close();
                con.close();
            }
            catch (Exception e)
            {
                System.err.println("Insertion Exception: " + e.getMessage());
            }       
        }
        catch (ClassNotFoundException e)
        {
            System.err.println("ClassNotFoundException: " + e.getMessage());
        } 
        catch (SQLException e)
        {
            System.err.println("SQLException: " + e.getMessage());
        }
            catch (Exception e)
        {
            System.err.println("Generic Exception: " + e.getMessage());
        }   
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        // TODO Auto-generated method stub
    }

}

So now, at this point, I'm not sure how to access that dropdown list element from my html page. And Googling around, I was not seeing anything that appeared to show this being done. Also, from what I read it seems most of the time a servlet is just processing information from the html/jsp page. What I'm doing right now is code+=("<option value=\"" + rs.getString(1) + "\">" + rs.getString(1) + " " + rs.getString(2) + "</option>");. Is that correct? And if so, how do I link that with the html/jsp page? Or is it not even possible to access that html page on load and populate it using the servlet?

This 0ne Pr0grammer
  • 2,632
  • 14
  • 57
  • 81
  • 1
    I'm sorry to say your code looks just ugly. Putting all that database stuff in a JSP makes it bulky and confusing, and it's difficult to look for errors here. Why not let a servlet do all the database stuff and exception handling instead, and focus on displaying on the JSP side? – f_puras Sep 28 '12 at 07:40
  • Honestly, this is my first time writing a jsp, so any comments are appreciated. I'll give that a try and re-post my code when I'm done. :) – This 0ne Pr0grammer Sep 28 '12 at 12:32
  • 1
    I'm not sure where you learnt HTML/JSP, but all those uppercase HTML tags and `
    ` tag suggest that the book/resource is 10~20 years old. This also implies the old school JSP scriptlet style which is bad for various reasons. I strongly recommend to carefully pay attention to the publication date of the book/resource from where you're trying to learn the new stuff. It should *preferably* not be older than the **current** JSP (2.2) / HTML (5) version. Put your mouse above `[jsp]` and `[servlets]` tags which you placed on the question until a black box shows and click therein *info* link.
    – BalusC Sep 28 '12 at 16:07
  • I was just basing that code-selector jsp off a template I found online. Did not know that about uppercase vs lower case. Interesting. – This 0ne Pr0grammer Sep 28 '12 at 16:12
  • 1
    The `
    ` element is deprecated since HTML 4.01 at 1998. Go figure.
    – BalusC Sep 28 '12 at 16:14

2 Answers2

1

The classic pattern for this is:

Browser -- request --> Servlet -- forward --> JSP

The mechanism that the Servlet uses to pass information to the JSP is via putting values in to the actual request.

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    String id = req.getParameter("id");
    String name = getNameFromDBForId(id);
    req.setAttribute("name", name);
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/page.jsp");
    rd.forward(request, response);
}

Then you can use JSP EL (Expression Language):

<html>
  <body>
    <h1>Hello ${name}</h1>
  </body>
</html>

The EL expression ${name} looks for the name key in several places, one of which is the request (you can look up the others), and replaces the value in the JSP.

This works for simple scalars, java beans, collections.

But this is the basic mechanism of how to get data from a Servlet in to a JSP. Look up the JSTL tags for example of iteration and conditional logic.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • So originally for what I'm trying to do, I was thinking when a user clicks a button on a form, it would redirect them to this html/jsp page which retrieves information from the database and populates the dropdowns. However, you are saying that button should make a call to the servlet which forwards it to the JSP page to be displayed? – This 0ne Pr0grammer Sep 28 '12 at 16:18
  • Actually, I'm starting to get an idea of how I'd do this using the method you suggested. However, it seems like it might be a lot of work in terms of figuring out how to get it to work using iteration and conditional logic. If my original JSP page works (with everything integrated in that page alone), what might be the drawbacks of doing it that way (aside from stylistic reasons)? – This 0ne Pr0grammer Sep 28 '12 at 16:44
  • 1
    It is worth your time to convert to the "Model 2" style where the Servlet does the work and the JSP does the rendering. They are easier to debug, they make your JSPs cleaner, easier to make them modular, etc. Most importantly, it's far easier to move to a modern action framework (Stripes, Struts 2) from the Servlet model than a pure JSP model. After you get the feel for the work flow with a Servlet, it is worth your time to move on to one of those frameworks if you're going to be doing any serious work. – Will Hartung Sep 28 '12 at 16:54
0

you should be using JSTL tags. scriptlets are discreadited and pretty hard for maintanence. check this link for JSTL SQL related tags

PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 1
    You're not concretely answering the question. JSTL SQL tags are discouraged and fall in the same category as *scriptlets*. You perhaps meant to suggest ``. See also http://stackoverflow.com/tags/jstl/info But even then, only posting oneliner/link-only answers won't give you much reputation/respect. At least, not from me. – BalusC Sep 28 '12 at 16:09
  • 1
    scriptlets are not deprecated, they're simply discouraged as a matter of style. The platform has full support for them and that is not going away. – Will Hartung Sep 28 '12 at 16:11
  • 1
    As to scriptlets, read the citation from Sun/Oracle in [this answer](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files/3180202#3180202). As to JSTL SQL, read the 1st paragraph of [this Java EE tutorial chapter](http://docs.oracle.com/javaee/5/tutorial/doc/bnald.html). – BalusC Sep 28 '12 at 16:17
  • 1
    @BalusC thanks for the links. i used scriptlets a while back. never really used JSTL other than core tags. – PermGenError Sep 28 '12 at 16:19
  • 1
    They still have their place, I mostly use them within tag files. I find if I need them in a JSP, it's better to make a tag file that wraps the logic and put them in there. – Will Hartung Sep 28 '12 at 16:51