【问题标题】:What causes a 'Type expected' error in JSP?是什么导致 JSP 中出现“预期类型”错误?
【发布时间】:2010-06-21 20:39:07
【问题描述】:

在一个 JSP 文件中,我得到一个:

Type expected (found 'try' instead)

尝试建立连接时出错。这给我留下了两个问题。这里出了什么问题?更一般地说,是什么导致 JSP 中的“预期类型”错误?因为我在谷歌搜索中找不到错误的解释。这是代码。

<%!
class ThisPage extends ModernPage
{
     try{
        Connection con=null;
        PreparedStatement pstmt=null;
        con = HomeInterfaceHelper.getInstance().getConnection();
        pstmt = con.prepareStatement("sql goes here");
        ResultSet rs = pstmt.executeQuery();
        con.close();  
    }
    catch (Exception e){
        System.out.println("sql error: exception thrown");
    }
}
%>

编辑显示更多代码

【问题讨论】:

  • 听起来你在某处有语法错误;你能在try之前的几行粘贴吗?
  • 听起来像缺少';'在尝试之前给我在线...
  • 感谢Zoogie 的建议。但除此之外,这是整个文件。会不会是这个问题?
  • 如果有人想知道“什么导致类型预期错误?”标题的字面意思。我发现了这个:mindprod.com/jgloss/compileerrormessages.html#TYPEEXPECTED
  • 我只想告诉大家,这不是做数据库工作的最佳方法。 1) 此代码属于真正的 Java 类,而不是 JSP 文件。 2) 关闭资源(全部三个!)应该在finally 中完成。另见this article

标签: jsp


【解决方案1】:

通常您不能在类声明中添加try .. catch 块,您至少应该将其放在类的构造函数或static { } 块之类的方法中。

我不知道 JSP 的语法是否不同,但您是否尝试过类似的方法:

class ThisPage extends ModernPage {
  Connection con;
  PreparedStatement pstmt;


  ThisPage() {
    try{
      con=null;
      pstmt=null;
      con = HomeInterfaceHelper.getInstance().getConnection();
      pstmt = con.prepareStatement("sql goes here");
      ResultSet rs = pstmt.executeQuery();
      con.close();  
    }
    catch (Exception e){
        System.out.println("sql error: exception thrown");
    }
  }
}

如果您查看Java Language Specification,您会发现 TryStatement 无法插入到类声明中。..

【讨论】:

  • 另一种方法是初始化块。 try-catch 块周围的另一个 {}
猜你喜欢
  • 1970-01-01
  • 2016-06-17
  • 2017-01-17
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多