【问题标题】:Servlet, JSP, JavaBeans and HTML formServlet、JSP、JavaBeans 和 HTML 表单
【发布时间】:2011-01-23 21:48:04
【问题描述】:

我正在开发一个 servlet,它与数据库建立连接,获取其中一个表的信息,然后将此信息发送到 jsp 文件。该文件将在浏览器上打印信息表,并添加单选按钮,让我们可以选择其中一行。

servlet 如下所示:

List<InfoBean> items = new ArrayList<InfoBean>();
if (!conexion.isClosed()){
  Statement st = (Statement) conexion.createStatement();          
  ResultSet rs = st.executeQuery("select * from lista_audio" );
  while (rs.next())
  {items.add(getRow(rs));}
  conexion.close();}
req.getSession().setAttribute("items", items);

在 JSP 文件中,我可以打印包含信息的表格,添加单选按钮,用户将使用这些单选按钮选择 1 行并使用我可以添加的表单将所选信息发送到 servlet:

< form action="administ" method=get enctype=multipart/form-data>    
< table>
 < table border=\"1\">< tr>< th>Title< /th>< th>Author< /th>< th>Album< /th>< /tr>
 < c:forEach items="${items}" var="item">
 < tr>< td><input type="radio" name="SongInfo" value=${item.title}>
 < td>${item.title}< /td>
 < td>${item.author}< /td>
 < td>${item.album}< /td>< /tr>
 < /c:forEach>
< /table>

在“值”字段中,我应该能够将存储在 ${item.title} 中的信息发送到 servlet。当我设置 value = ${item.title} 并且标题是,例如“保镖”时,在 servlet 中我可以检索的信息只是“The”。看起来它发送位于字符串第一个空格之前的字符。我怎样才能得到整个字符串?

谢谢

【问题讨论】:

    标签: java html forms jsp servlets


    【解决方案1】:

    检查生成的 HTML 输出(在浏览器中右键单击页面,选择查看源代码)。你不会错过什么吗?

    <input type="radio" name="SongInfo" value=The bodyguard>
    

    是的,引号(注意突出显示颜色的区别,bodyguard 成为属性)。

    所以,修复它:

    <input type="radio" name="SongInfo" value="${item.title}">
    

    这样生成如下:

    <input type="radio" name="SongInfo" value="The bodyguard">
    

    简单的修复,不是吗? :)


    也就是说,您的 JDBC 代码容易发生资源泄漏。您应该关闭所有资源 ConnectionStatementResultSet 在您获得的 try 块的 finally 块中。有关更多提示,请参阅this article。此外,列表不一定需要放在会话范围内。 HTML在语法上也是无效的,但这可能只是一个复制粘贴错误,否则它不会起作用。

    此外,您的 HTML 表单被声明为使用GET 的请求方法,但它也被声明为使用multipart/form-data 的编码类型。这完全没有意义。 在您有 &lt;input type="file"&gt; 时使用此编码类型,如果是这种情况,请求方法应为 POST

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2012-07-31
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多