Java ResultSet 无法解析为类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22685651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:16:27  来源:igfitidea点击:

ResultSet cannot be resolved to a type

javajspresultset

提问by lcazarre

I am refactoring two .jsp pages to place some common code to a Java class. The purpose of the common code is to connect to a database.

我正在重构两个 .jsp 页面以将一些公共代码放置到 Java 类中。公共代码的目的是连接到数据库。

Both pages were working well before the change. But I now get an "ResultSet cannot be resolved to a type" error on one page, whereas the other page runs without error. I do not understand why, as I think I made similar changes to both pages.

两个页面在更改前都运行良好。但是我现在在一个页面上收到“ResultSet 无法解析为类型”错误,而另一页运行时没有错误。我不明白为什么,因为我认为我对两个页面都做了类似的更改。

Could anyone help me explain why the first page does not work, while the first one does?

谁能帮我解释为什么第一页不起作用,而第一页却起作用?

Here is the page that no longer works after the change:

这是更改后不再有效的页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB" xml:lang="en-GB">
<%@page pageEncoding="utf-8" %>

<head>
    <meta charset="UTF-8" /> 
    <title>Forum</title>
    <link rel="stylesheet" type="text/css" href="stocktails.css" />
</head>
<body>

    <%@ include file="navigation.html" %>

    <div id="maindiv">
        <header>
            <h1> Discussion forum </h1>
            <p>Bounce your investing ideas off the community</p>
        </header>

        <div class="left-col">

            <div id='post'>
                <form action='post.jsp' method="get">
                    User name: <input type="text" name="userName"><br>
                    Password: <input type="password" name="pwd">
                    <textarea id="postText" name="textarea" rows="10" cols="50">Type here</textarea>
                    <input type="submit" value="Submit">
                </form>
            </div>

            <%@ page import="com.stocktails.*" %>
            <%
                dbConnect dbConnection = new dbConnect();
                String sqlStr = "SELECT * FROM Posts ORDER BY Id ASC";
                ResultSet rset = dbConnection.executeQuery(sqlStr);
            %>

            <div id="tablePlaceholder">
                <form method="get" action="forum.jsp">
                    <table class='forumTable'>
          <%
              while (rset.next()) {
          %>
                        <tr>
                            <td class="postDate">Posted on: <%= rset.getDate("Date") %></td>
                            <td class="postId">Post #<%= rset.getInt("Id") %></td>
                        </tr>
                        <tr>
                            <td class="postMember"><%= rset.getString("Member") %></td>
                            <td class="postText"><%= rset.getString("Text") %></td>
                        </tr>
                        <tr>
                            <td class="postEmpty"></td>
                        </tr>
          <%
              }
          %>
                </table>
                <br>
              </form>
            </div>

         <% dbConnection.closeAll(); %>

        </div>

        <div class="right-col">
            <aside class="aside-forum">
                <header>
                    <h1> Forum etiquette </h1>
                    <p> Thou shall not troll </p>
                </header>
                <section>
                    <h1> No promotion </h1>
                    <p> Do not use this forum to promote your own business. </p>
                </section>
                <section>
                    <h1> Keep calm and carry on </h1>
                    <p> Be courteous. Personal disagreements should be handled through email and not through public posts. </p>
                </section>
                <section>
                    <h1> No hiHymaning </h1>
                    <p> Do not hiHyman someone else's thread and interrupt a topic of discussion. </p>
                </section>
                <section>
                    <h1> You say /t??me?to?/, we say /t??mɑ?t??/ </h1>
                    <p> Please refrain from using American spelling. </p>
                </section>
            </aside>
        </div>

        <div class="clear"></div>
    </div>

    <%@ include file="footer.html" %>

</body>
</html>

Here is the error message if get:

如果获取,这是错误消息:

HTTP Status 500 - Unable to compile class for JSP:

type Exception report

message Unable to compile class for JSP:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 37 in the jsp file: /forum.jsp
ResultSet cannot be resolved to a type
34:             <%
35:                 dbConnect dbConnection = new dbConnect();
36:                 String sqlStr = "SELECT * FROM Posts ORDER BY Id ASC";
37:                 ResultSet rset = dbConnection.executeQuery(sqlStr);
38:             %>
39: 
40:             <div id="tablePlaceholder">


Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:468)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.52 logs.

Here is the other page that still works even after I moved some code to a separate class:

这是另一个页面,即使在我将一些代码移动到单独的类后仍然有效:

<html>
<head>
  <title>Quote Query</title>
</head>
<body>
  <h1>retrieve stock quotes</h1>
  <h3>Choose Ticker(s):</h3>
  <form method="get">
    <input type="checkbox" name="ticker" value="AAPL">AAPL
    <input type="checkbox" name="ticker" value="MSFT">MSFT
    <input type="submit" value="Query">
  </form>

  <%
    String[] tickers = request.getParameterValues("ticker");
    if (tickers != null) {
  %>


        <%@ page import="com.stocktails.*" %>
        <%
            dbConnect dbConnection = new dbConnect();

            String sqlStr = "SELECT * FROM Quotes WHERE Ticker IN (";
            sqlStr += "'" + tickers[0] + "'";  // First ticker
            for (int i = 1; i < tickers.length; ++i) {
                sqlStr += ", '" + tickers[i] + "'";  // Subsequent tickers need a leading commas
            }
            sqlStr += ") ORDER BY Date ASC";

            // for debugging
            System.out.println("Query statement is " + sqlStr);

            ResultSet rset = dbConnection.executeQuery(sqlStr);
        %>

      <hr>
      <form method="get" action="quotes.jsp">
        <table border=1 cellpadding=5>
          <tr>
            <th>Ticker</th>
            <th>Date</th>
            <th>PriceOpen</th>
            <th>PriceHigh</th>
            <th>PriceLow</th>
            <th>PriceClose</th>
            <th>Volume</th>
            <th>PriceAdjClose</th>
          </tr>
  <%
      while (rset.next()) {
  %>
          <tr>
            <td><%= rset.getString("Ticker") %></td>
            <td><%= rset.getString("Date") %></td>
            <td>$<%= rset.getInt("PriceOpen") %></td>
            <td><%= rset.getInt("PriceHigh") %></td>
            <td><%= rset.getString("PriceLow") %></td>
            <td><%= rset.getString("PriceClose") %></td>
            <td>$<%= rset.getInt("Volume") %></td>
            <td><%= rset.getInt("PriceAdjClose") %></td>
          </tr>
  <%
      }
  %>
        </table>
        <br>
        <input type="submit" value="Order">
        <input type="reset" value="Clear">
      </form>
      <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
  <%
        dbConnection.closeAll();
    }
  %>

    <%@ include file="footer.html" %>
</body>
</html>

Here is the Java class:

这是Java类:

import javax.naming.*;
import java.sql.*;
import javax.sql.*;

public class dbConnect
{
    private Context init;
    private Context env;
    private DataSource data;
    private Connection conn;
    private Statement stmt;
    private ResultSet rset;

    public dbConnect()
    {
        try {
            init = new InitialContext();
        }
        catch (NamingException e)
        {
            System.out.println("Cannot create initial environment");
        };

        try {
            env = (Context) init.lookup("java:/comp/env/");
        }
        catch (NamingException e)
        {
            System.out.println("Cannot create context");
        };

        try {
            data = (DataSource) env.lookup("jdbc/mydb");
        }
        catch (NamingException e)
        {
            System.out.println("Cannot create data source");
        };

        try {
            conn = data.getConnection();            
        }
        catch (SQLException e)
        {
            System.out.println("Cannot get connection");
        }

        try {
            stmt = conn.createStatement();          
        }
        catch (SQLException e)
        {
            System.out.println("Cannot create statement");
        }

    }

    public ResultSet executeQuery(String sqlStr)
    {
        try {
            rset = stmt.executeQuery(sqlStr);
        }
        catch (SQLException e)
        {
            System.out.println("Cannot execute query");
        }
        return rset;
    }

    public void closeAll()
    {
        try {
            rset.close();
            stmt.close();
            conn.close();                       
        }
        catch (SQLException e)
        {
            System.out.println("Cannot close connection");
        }
    }
}

采纳答案by Charaf JRA

You should also import java.sql.ResultSetclass in your JSP :

您还应该java.sql.ResultSet在 JSP 中导入类:

<%@ page import="java.sql.ResultSet" %>

make sure that you included the jdbc JAR.

确保包含 jdbc JAR。

PS:You should learn how to organize your code , never access database through JSP,Read more about RequestDispatcher,request.setAttribute..., Google about MVC.

PS:你应该学习如何组织你的代码,永远不要通过 JSP 访问数据库,阅读更多关于RequestDispatcherrequest.setAttribute...,谷歌关于MVC