简体   繁体   English

如何从JAVA httpSession获取参数并在dao类上使用/设置它?

[英]How to get a parameter from JAVA httpSession and use/set it on a dao class?

I need to use a servlet to validate login/password. 我需要使用servlet来验证登录名/密码。 That's fine already. 很好

I have a method in a DAO class that returns a resultSet list of values through a prepareStatement. 我在DAO类中有一个方法,该方法通过prepareStatement返回值的resultSet列表。

I'm using a query that brings this filtered result with a where clause (by user's name). 我正在使用一个查询,该查询通过where子句(按用户名)带来此过滤后的结果。

The problem is: how can I get the servlet parameter (name of the user who logged in) and set it on the prepareStatement ? 问题是:如何获取servlet参数(登录用户的名称)并将其设置在prepareStatement上?

The code follows: 代码如下:

public class DaoPojoJoin extends Dao {

public List<PojoJoin> listUserDegrees() {
    List<PojoJoin> dg = new ArrayList<PojoJoin>();
    if (openConnection()) {
        try {
            st = cn.prepareStatement("SELECT USER, MATTER, DEGREE FROM DEGREES x "
                    + "right outer join USERS y on x.idUser=y.idUser "
                    + "right outer join MATTER z on idMatter=z.idMatter "
                    + "where x.iduser=?"); // filter result by user's name

            // How can I have something like this:
            // st.setString(1,usr.request.getParameter("user"));

            // or this:
            // st.setString(1,.getAttribute(user));

            rs = st.executeQuery();
            while (rs.next()) {
                PojoJoin pj = new PojoJoin();
                rs.getString("USER"); 
                rs.getString("MATTER");
                rs.getDouble("DEGREE");
                pj.setUsuario(rs.getString("USER"));
                pj.setDisciplina(rs.getString("MATTER"));
                pj.setNota(rs.getDouble("DEGREE"));
                nota.add(pj);
            }
        } catch (Exception ex) {
            err = ex.getMessage();
        } finally {
            closeConnection();
        }
    }
    return dg;
}

} }

Thanks in advance. 提前致谢。

Ask for it as method argument. 要求它作为方法参数。 The DAO should not care about the context it is sitting in and is supposed to be reuseable everywhere else (eg a plain vanilla Java Application which doesn't use servlets). DAO不必关心它所在的上下文,并且应该在其他任何地方都可以重用(例如,不使用servlet的普通Java应用程序)。

Thus so 因此

public List<PojoJoin> listUserDegrees(String username) {
    // ...
}

or 要么

public List<PojoJoin> listUserDegrees(Long userId) {
    // ...
}

or 要么

public List<PojoJoin> listUserDegrees(User user) {
    // ...
}

Finally just let the caller (the servlet) pass it in. 最后,只需让调用者(servlet)将其传递。


Unrelated to the concrete problem, your DB resource handling doesn't seem to be threadsafe. 具体问题无关 ,您的数据库资源处理似乎不是线程安全的。 I'd work on that to avoid serious problems whenever your webapp starts to be used by multiple users. 我将努力避免在您的Web应用程序开始被多个用户使用时出现严重问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM