Java 如何将数据库记录列表(通过 Hibernate 检索)显示到 Struts 2 中的 JSP 页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18678866/
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-12 10:06:09  来源:igfitidea点击:

How to display a list of database records (retrieved via Hibernate) to a JSP page in Struts 2?

javahibernatejspstruts2xml-configuration

提问by Eva Mariam

I am trying to display the database records to my JSP page in Struts 2 using Hibernate. I have done the retrieval part successfully.

我正在尝试使用 Hibernate 在 Struts 2 中将数据库记录显示到我的 JSP 页面。我已经成功完成了检索部分。

But no matter what I do, I can't seem to display the data in the JSP page.

但是无论我做什么,我似乎都无法在JSP页面中显示数据。

I have tried various solution found in internet. But cant understand whats seems to be the problem. I can see the tables column name but there is no data in it. I have all the required getters and setters in my User POJO class.

我尝试了在互联网上找到的各种解决方案。但无法理解似乎是问题所在。我可以看到表列名,但其中没有数据。我的 User POJO 类中有所有必需的 getter 和 setter。

I have attached my code:

我附上了我的代码:

Register action:

注册动作:

public class RegisterAction extends ActionSupport{
    String name,pwd,email,address;
    int phno;

    public RegisterAction() {}

    List<User> users = new ArrayList<User>();
    UserDao udao = new UserDao();

    //Getters and setters.

    public String execute() throws Exception {
        User u=new User();
        u.setName(name);
        u.setEmail(email);
        u.setAddress(address);
        u.setPhno(phno);
        u.setPwd(pwd);
        udao.addUser(u);
        return "success";
    }

    public String listAllUsers(){
        users = udao.getUsers();
        System.out.println("In Action, "+users);
        return "success";
    }
}

UserDao:

UserDao

public class UserDao{        

    List<User> allUsers = new ArrayList<User>();

    public UserDao() {}

    //Getter and setter.

    public Session getSession(){
        return HibernateUtil.getSession();
    }

    public void closeSession(){
        HibernateUtil.closeSession();
    }

    public void addUser(User u) {
        Session session= getSession();
        Transaction t = session.beginTransaction();
        int i = (Integer)session.save(u);
        t.commit();
        closeSession();
    }

    public List<User> getUsers() {
        Session session=getSession();
        Transaction t = session.beginTransaction();
        allUsers = (List<User>)session.createQuery("from User").list();
        t.commit();
        closeSession();
        System.out.print(allUsers);
        return allUsers;
    }
}

User.java//Entity Class:

User.java//实体类:

@Entity
@Table(name="tbl_user")
public class User {
    @Id
    @GeneratedValue
    @Column(name="user_id")
    private int id;
    @Column(name="user_phno")
    int phno;
    @Column(name="user_name")
    private String name;
    @Column(name="user_pwd")
    private String pwd;
    @Column(name="user_email")
    private String email;
    @Column(name="user_address")
    private String address;

    public User(){}

    public User(String name,String pwd,String email,String address,int phno){
        this.name = name;
        this.pwd = pwd;
        this.email = email;
        this.address =address;
        this.phno = phno;

    }

    //Getters and setters.
}

home.jsp:

home.jsp

<table>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Address</th>
        <th>Phone No</th>
    </tr>
    <s:iterator value="users">
        <tr>
            <td><s:property value="name"/></td>
            <td><s:property value="email"/></td>
            <td><s:property value="address"/></td>
            <td><s:property value="phno"/></td>
        </tr>
    </s:iterator>

</table>

struts.xml:

struts.xml

<action name="register" class="action.RegisterAction" method="execute">
    <result name="success" type="redirect">listUsers</result>
</action>
<action name="listUsers" class="action.RegisterAction" method="listAllUsers">
    <result name="success">/home.jsp</result>
</action>

HibernateUtil:

HibernateUtil

public class HibernateUtil {

    static SessionFactory sessionFactory;
    static Session session;

    public static Session getSession() {
        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        session= sessionFactory.openSession();
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public static void closeSession(){
        session.close();
    }
}

The server log contains

服务器日志包含

[models.User@9c0fad, models.User@1c94f2c, models.User@16d06ef]

INFO: In Action, [models.User@9c0fad, models.User@1c94f2c, models.User@16d06ef]

采纳答案by Roman C

May be you understand, but don't know why you didn't any attempt to resolve it. If you want to display data, first you should put it in the database. Check the data is available, connecting to it via the client application. There's many ways to connect to the database, including a JDBC client application supplied with the IDE. It also takes a connection properties right from your hibernate.cfg.xmland has capability to test the connection. Also, make sure the credential used to connect to the database has DML/DDL access privileges to the schema which should be probably created manually.

可能你明白了,但不知道为什么你没有尝试解决它。如果要显示数据,首先应该将其放入数据库中。检查数据是否可用,通过客户端应用程序连接到它。有很多方法可以连接到数据库,包括 IDE 提供的 JDBC 客户端应用程序。它还直接从您那里获取连接属性,hibernate.cfg.xml并具有测试连接的能力。此外,请确保用于连接到数据库的凭据对可能应该手动创建的模式具有 DML/DDL 访问权限。

This file is for hibernate configuration, that you should take attention on it, to be valid due to a correctDTD corresponding to the version of hibernate.

该文件用于hibernate配置,需要注意,正确的DTD对应hibernate的版本才有效。

Then, you are using annotation based mapping, and it also should be configured in the configuration file.

然后,您使用的是基于注解的映射,它也应该在配置文件中进行配置。

Next, DAO is not supposed to extend the HibernateUtiland putting a staticproperty for the sessionis a disaster. DAOs should not have staticproperties. If you want to get a session use HibernateUtil.getSession()and don't forget to close session at the end of transaction. I guess you still didn't implement what I have proposed in the previous answer, so you don't know how to get the session from thread. Anyway opening a session in the constructor is only works a first time you use the session, and it's not longer available after you close it. Open a session in the method before you start a transaction.

接下来,DAO 不应该扩展HibernateUtil和放置static属性session是一场灾难。DAO 不应具有static属性。如果您想获得会话使用HibernateUtil.getSession()并且不要忘记在事务结束时关闭会话。我猜你仍然没有实现我在上一个答案中提出的内容,所以你不知道如何从线程中获取会话。无论如何,在构造函数中打开一个会话仅在您第一次使用该会话时有效,并且在您关闭它后不再可用。在开始事务之前在方法中打开一个会话。

Next, ModelDrivenis better described by @Quaternion, a few words about your model: your model is only used to view a userand doesn't contain properties to display users.

接下来,ModelDriven由@Quaternion 更好地描述,关于您的模型的几句话:您的模型仅用于查看 auser并且不包含要显示的属性users

Lastly, method executeis a default method used by the action configuration, you shouldn't map this method, unless you know what are you doing.

最后,methodexecute是 action 配置使用的默认方法,除非您知道自己在做什么,否则不应映射此方法。

回答by Azhar_Born4Java

What I found is that your property name of list of jsp and variable name of action class should match. As per my understanding this should resolve your issue.....!

我发现你的jsp列表的属性名和动作类的变量名应该匹配。根据我的理解,这应该可以解决您的问题......!

回答by user3160142

Override toString()method in User.java

覆盖toString()User.java 中的方法