是否可以返回 ResultSet 以在 JSTL 中使用?

发布于 2024-10-05 03:25:26 字数 2231 浏览 4 评论 0原文

是否可以将 ResultSet 变量返回到 JSTL foreach 标记?我收到空点错误,并且由于错误的原因,它说 db2.MyServ 类不存在,即使它就在那里。有人知道我做错了什么以及如何在 jstl 上迭代我的 ResultSet rs 吗?

MyServ2 类(导入等省略)

     package db2;

public class MyServ2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       private DBClass db;
       private ResultSet rs;

    public MyServ2() {
        super();
        db = new DBClass();
        db.dbConnect("jdbc:oracle:thin:@elanweb:1510:xxxxx", "xxxxx", "xxx");

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        rs = db.getResultSet(request.getParameter("query"));
        try {
            while(rs.next()){
                System.out.println(rs.getString(1).toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    public ResultSet getRs()
    {
        return rs;
    }

}

index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <%@ page import="db2.MyServ2" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
</head>
<body>
successful login
<jsp:useBean id="myserv2" class="db2.MyServ2"/>

<c:if test="${myserv2.rs.Next()}">
<c:forEach var="person" items="${myserv2.rs}">
<c:out value="${myserv2.rs.string(1).toString()}"></c:out>
</c:forEach>
</c:if>
</body>
</html>

我创建了一个 bean 并将字符串保存到其中。当我从 MyServ2 类调用它们进行调试时,它们工作正常,但是当我从我的网页作为 jstl 调用它们时,它们返回 null,就好像 bean 未填充一样。当我重定向回网页后,所有内容都会重置吗?

<jsp:useBean id="mybean" class="beans.UserBean"></jsp:useBean>

<c:out value="${mybean.name}"></c:out><br></br>

在 MyServ 类中添加以下内容

rs = db.getResultSet(request.getParameter("query"));
    try {
        while(rs.next()){
            mybean.SetName(rs.getString(1).toString());
            mybean.Setsurname( rs.getString(2).toString());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

is it possible to return ResultSet variable to JSTL foreach tag? I am getting null point error and for the wrong reason, it's saying that db2.MyServ class doesn't exist even though its right there. anyone know what i'm doing wrong and how to itterate over my ResultSet rs on jstl?

MyServ2 class(imports etc omitted)

     package db2;

public class MyServ2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       private DBClass db;
       private ResultSet rs;

    public MyServ2() {
        super();
        db = new DBClass();
        db.dbConnect("jdbc:oracle:thin:@elanweb:1510:xxxxx", "xxxxx", "xxx");

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        rs = db.getResultSet(request.getParameter("query"));
        try {
            while(rs.next()){
                System.out.println(rs.getString(1).toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    public ResultSet getRs()
    {
        return rs;
    }

}

index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <%@ page import="db2.MyServ2" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
</head>
<body>
successful login
<jsp:useBean id="myserv2" class="db2.MyServ2"/>

<c:if test="${myserv2.rs.Next()}">
<c:forEach var="person" items="${myserv2.rs}">
<c:out value="${myserv2.rs.string(1).toString()}"></c:out>
</c:forEach>
</c:if>
</body>
</html>

I've created a bean and saved strings to it. When i call them from my MyServ2 class for debugging, they work fine, but when i call them from my webpage as jstl they return null as if the bean is no populated. Does everything reset as soon as i redirect back to the webpage?

<jsp:useBean id="mybean" class="beans.UserBean"></jsp:useBean>

<c:out value="${mybean.name}"></c:out><br></br>

added in MyServ class the following

rs = db.getResultSet(request.getParameter("query"));
    try {
        while(rs.next()){
            mybean.SetName(rs.getString(1).toString());
            mybean.Setsurname( rs.getString(2).toString());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抚你发端 2024-10-12 03:25:26

这不是一个好主意。一点也不。

在哪里关闭结果集?还有连接?您应该提供一种可靠的方式来释放这些资源,否则可能会导致您的应用程序出现严重问题。

此外,将连接设置为 HttpServlet 的实例值通常被认为是一种不好的做法,因为您必须在所有 Servlet 活动时保持它处于活动状态。另外,如果存在通信问题,您需要重新启动应用程序以使 servlet 重新连接。更不用说在 servet 实例级别保存结果集,以及它可能导致的所有并发问题。

将 rs 行映射到 JavaBean 以便在 JSP 中使用并不那么困难。并尝试重构代码以进行正确的数据库连接处理。

编辑:在您的最后一段代码中,我看到您仍然在 servlet 实例中保存数据。这可能会导致并发问题。
检查一下:

Resultset rs=null; //declare a local variable
try {
    //wrong code get the query from the request parameter! 
    // rs = db.getResultSet(request.getParameter("query"));
    String query="select col from table where a='b'"; // whatever
    rs = db.getResultSet(query);
    //just one value? no need of while
    if(rs.next()){
        MyBean bean=new MyBean();
        bean.setName(rs.getString(1));
        bean.setSurname(rs.getString(2));
        //here is where you put your bean to the request
        request.setAttribute("myBean", bean);
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //Don't forget closing your Rs
    if(rs!=null) {rs.close();}
}

然后,使用 JSTL,您已经可以访问请求属性,与上一个 JSP 示例非常相似,使用在 setAttribute 方法中设置的名称:

<c:out value="${myBean.name}" /><br></br>
<c:out value="${myBean.surname}" /><br></br>

This is not a good idea. Not at all.

Where do you close the Resultset? And the Connection? You should provide a reliable way to release this resources, which otherwise could cause serious problems at your app.

Moreover, setting a connection as an instance value at an HttpServlet is generally considered as a bad practice, because you have to keep it alive for all the Servlet live. Also, if there are communication issues, you'll need to restart your application to make your servlet reconnect. Not to talk about saving the resultset at serlvet instance level, and all the concurrency issues it can cause.

Mapping your rs rows at a JavaBean to be used at the JSP won't be so hard. And try to refactorize your code for a proper database connection handling.

EDIT: At your last snippet of code, I see you still save data at the servlet instance. This can drive to concurrency problems.
Check this:

Resultset rs=null; //declare a local variable
try {
    //wrong code get the query from the request parameter! 
    // rs = db.getResultSet(request.getParameter("query"));
    String query="select col from table where a='b'"; // whatever
    rs = db.getResultSet(query);
    //just one value? no need of while
    if(rs.next()){
        MyBean bean=new MyBean();
        bean.setName(rs.getString(1));
        bean.setSurname(rs.getString(2));
        //here is where you put your bean to the request
        request.setAttribute("myBean", bean);
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //Don't forget closing your Rs
    if(rs!=null) {rs.close();}
}

And then, using JSTL you can already access the request attrbitue, very similar as you last JSP example, using the name set at the setAttribute method:

<c:out value="${myBean.name}" /><br></br>
<c:out value="${myBean.surname}" /><br></br>
云柯 2024-10-12 03:25:26

我的简单答案是否定的,出于各种原因:

  • ResultSet 不符合 JavaBeans 规范(它没有 getters/setters 方法,并且不可序列化)。

相反,将 ResultSet 填充到 bean 中并使用 JSTL 从 bean 检索数据。


对于您编辑过的帖子,我建议将其全部废弃(正如 BalusC 评论的那样,它可能导致 SQL 注入)并遵循 JavaBeans 规范。

这是我的意思的一个例子:

JavaBean 用户:

public class UserEntity implements Serializable {

 private String firstName;
 private String middleName = "";
 private String lastName;
 private Gender gender;
 private String emailAddress;
 private Date birthDate;
        private boolean searchable = false;

        //Getters and Setters here...

}

MySQLUserDAO 中,我从 ResultSet 映射了我的实体 (javabean)。

protected UserEntity mapEntity(ResultSet rs) throws SQLException {
  // TODO Auto-generated method stub
  UserEntity user = null;

  if (rs != null) {
   user = new UserEntity();

   user.setId(rs.getLong("USER_ID"));
   user.setFirstName(rs.getString("FIRST_NAME"));
   user.setMiddleName(rs.getString("MIDDLE_NAME"));
   user.setLastName(rs.getString("LAST_NAME"));
   user.setEmailAddress(rs.getString("EMAIL_ADDRESS"));

   String gender = rs.getString("GENDER");
   if ("M".equals(gender)) {
    user.setGender(Gender.MALE);
   } else if ("F".equals(gender)) {
    user.setGender(Gender.FEMALE);
   }

   user.setBirthDate(rs.getDate("DOB"));
   user.setCreationDate(rs.getDate("CREATION_DATE"));
                        user.setSearchable(rs.getBoolean("SEARCHABLE"));
  }

  return user;
 }

最后是 retrieve() 方法(来自 MySQLUserDAO)。

public UserEntity retrieve(Long id) throws DAOException {
  // TODO Auto-generated method stub
  PreparedStatement ps = null;
  ResultSet rs = null;
  UserEntity user = null;

  try {
   ps = getConnection().prepareStatement(SQL_RETRIEVE);
   ps.setLong(1, id);
   rs = ps.executeQuery();
   if (rs != null && rs.next()) {
    user = mapEntity(rs);
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   throw new DAOException(e);
  } finally {
   try {
    close(rs, ps);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    logger.error("Error closing statement or resultset.", e);
   }
  }

  return user;
 }

现在,要使用 UserEntity 到 JSP,我可以......

UserEntity user = MySQLUserDAO.retrieve(userId); //Pseudocode....
request.setAttribute("user", user);

并使用 JSTL,我可以这样做:

<c:out value="${user.firstName}">

其中 user 是请求中的属性名称(它返回 UserEntity user)和 firstName 调用 user.getFirstName()(来自 UserEntity 的方法)。

希望你能效仿 BalusC 的榜样。

My simple answer is no, for the various reasons:

  • ResultSet doesn't conform to JavaBeans specification (it has no getters/setters method and it's not serializable).

Rather, populate your ResultSet into a bean and use JSTL to retrieve data from the bean.


For your edited post, I suggest scrapping it all together (as BalusC commented, it can lead to SQL Injection) and follow the JavaBeans spefication.

This is an example of what I meant:

JavaBean user:

public class UserEntity implements Serializable {

 private String firstName;
 private String middleName = "";
 private String lastName;
 private Gender gender;
 private String emailAddress;
 private Date birthDate;
        private boolean searchable = false;

        //Getters and Setters here...

}

From MySQLUserDAO, I mapped my entity (javabean) from ResultSet.

protected UserEntity mapEntity(ResultSet rs) throws SQLException {
  // TODO Auto-generated method stub
  UserEntity user = null;

  if (rs != null) {
   user = new UserEntity();

   user.setId(rs.getLong("USER_ID"));
   user.setFirstName(rs.getString("FIRST_NAME"));
   user.setMiddleName(rs.getString("MIDDLE_NAME"));
   user.setLastName(rs.getString("LAST_NAME"));
   user.setEmailAddress(rs.getString("EMAIL_ADDRESS"));

   String gender = rs.getString("GENDER");
   if ("M".equals(gender)) {
    user.setGender(Gender.MALE);
   } else if ("F".equals(gender)) {
    user.setGender(Gender.FEMALE);
   }

   user.setBirthDate(rs.getDate("DOB"));
   user.setCreationDate(rs.getDate("CREATION_DATE"));
                        user.setSearchable(rs.getBoolean("SEARCHABLE"));
  }

  return user;
 }

And finally, the retrieve() method (from MySQLUserDAO).

public UserEntity retrieve(Long id) throws DAOException {
  // TODO Auto-generated method stub
  PreparedStatement ps = null;
  ResultSet rs = null;
  UserEntity user = null;

  try {
   ps = getConnection().prepareStatement(SQL_RETRIEVE);
   ps.setLong(1, id);
   rs = ps.executeQuery();
   if (rs != null && rs.next()) {
    user = mapEntity(rs);
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   throw new DAOException(e);
  } finally {
   try {
    close(rs, ps);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    logger.error("Error closing statement or resultset.", e);
   }
  }

  return user;
 }

Now, to use UserEntity to JSP, I do....

UserEntity user = MySQLUserDAO.retrieve(userId); //Pseudocode....
request.setAttribute("user", user);

and using JSTL, I can do:

<c:out value="${user.firstName}">

where user is the attribute name from the request (which returns UserEntity user) and firstName calls user.getFirstName() (the method from UserEntity).

Hope you follow BalusC's example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文