【问题标题】:Is it Possible to Populate a Dropdown (In HTML/JSP) From a Servlet?是否可以从 Servlet 填充下拉列表(在 HTML/JSP 中)?
【发布时间】:2012-09-19 19:47:54
【问题描述】:

好的,所以我创建了我的第一个 jsp 页面,它基本上创建了 3 个下拉菜单,并使用从数据库中提取的信息填充它们。

但是,我被告知这是错误的代码,我应该使用 servlet 来处理该数据库功能和错误处理,并让 jsp 严格执行显示。

jsp原代码如下:

<%@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>

到目前为止,这就是我在新的 jsp 和 servlet 页面中所拥有的:

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
    }

}

所以现在,在这一点上,我不确定如何从我的 html 页面访问该下拉列表元素。谷歌搜索,我没有看到任何似乎表明这已经完成的东西。此外,从我读到的内容看来,大多数时候 servlet 只是在处理来自 html/jsp 页面的信息。我现在正在做的是code+=("&lt;option value=\"" + rs.getString(1) + "\"&gt;" + rs.getString(1) + " " + rs.getString(2) + "&lt;/option&gt;");。那是对的吗?如果是这样,我如何将它与 html/jsp 页面链接?或者甚至无法在加载时访问该 html 页面并使用 servlet 填充它?

【问题讨论】:

  • 很抱歉,您的代码看起来很丑。将所有这些数据库内容放在 JSP 中会使它变得庞大和混乱,并且很难在此处查找错误。为什么不让 servlet 代替所有的数据库工作和异常处理,而专注于在 JSP 端显示?
  • 老实说,这是我第一次写一个jsp,所以任何cmets都非常感谢。完成后我会尝试并重新发布我的代码。 :)
  • 我不确定你在哪里学习 HTML/JSP,但所有那些大写的 HTML 标签和&lt;center&gt; 标签表明这本书/资源是 10~20 年的。这也暗示了由于各种原因而不好的老式 JSP scriptlet 样式。我强烈建议您仔细注意您尝试学习新内容的书籍/资源的出版日期。它应该最好不早于当前 JSP (2.2) / HTML (5) 版本。将鼠标放在您放置在问题上的 [jsp][servlets] 标签上方,直到出现黑框,然后单击其中的 info 链接。
  • 我只是根据我在网上找到的模板来构建代码选择器 jsp。不知道关于大写与小写。很有趣。
  • 自 1998 年的 HTML 4.01 起,&lt;center&gt; 元素已被弃用。去看看吧。

标签: java html eclipse jsp servlets


【解决方案1】:

这方面的经典模式是:

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

Servlet 用来向 JSP 传递信息的机制是通过将值放入实际请求中。

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);
}

那么你可以使用JSP EL(表达语言):

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

EL 表达式${name} 在多个位置查找name 键,其中一个是请求(您可以查找其他位置),并替换JSP 中的值。

这适用于简单的标量、java bean、集合。

但这是如何将数据从 Servlet 获取到 JSP 的基本机制。查找 JSTL 标记,例如迭代和条件逻辑。

【讨论】:

  • 所以最初对于我想要做的事情,我在想当用户点击表单上的按钮时,它会将他们重定向到这个 html/jsp 页面,该页面从数据库中检索信息并填充下拉菜单。但是,您是说该按钮应该调用 servlet 将其转发到要显示的 JSP 页面?
  • 实际上,我开始了解如何使用您建议的方法来做到这一点。但是,在弄清楚如何使用迭代和条件逻辑使其工作方面似乎需要做很多工作。如果我的原始 JSP 页面有效(仅在该页面中集成了所有内容),那么这样做的缺点可能是什么(除了风格原因)?
  • 值得您花时间转换为“模型 2”样式,其中 Servlet 进行工作,JSP 进行渲染。它们更易于调试,使您的 JSP 更简洁,更易于模块化等。最重要的是,从 Servlet 模型迁移到现代动作框架(Stripes、Struts 2)比纯 JSP 模型容易得多。在您对 Servlet 的工作流程有所了解之后,如果您打算做任何严肃的工作,那么值得您花时间转向其中一个框架。
【解决方案2】:

您应该使用 JSTL 标签。 scriptlet 是不可靠的,并且很难维护。 check this link 用于 JSTL SQL 相关标签

【讨论】:

  • 你没有具体回答这个问题。不鼓励使用 JSTL SQL 标记,它们与 scriptlets 属于同一类别。您可能打算建议&lt;c:forEach&gt;。另请参阅stackoverflow.com/tags/jstl/info 但即便如此,仅发布 oneliner/link-only 答案也不会给您带来太多声誉/尊重。至少,不是来自我。
  • scriptlet 没有被弃用,只是因为风格问题而被劝阻。该平台为他们提供全面支持,并且不会消失。
  • 关于 scriptlet,请阅读 Sun/Oracle 在this answer 中的引用。关于JSTL SQL,请阅读this Java EE tutorial chapter的第一段。
  • @BalusC 感谢您的链接。我前一阵子用过scriptlet。除了核心标签之外,从未真正使用过 JSTL。
  • 它们仍然占有一席之地,我主要在标签文件中使用它们。我发现如果我在 JSP 中需要它们,最好制作一个包装逻辑的标记文件并将它们放在那里。
猜你喜欢
  • 2016-12-14
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多