---
title: "在Eclipse下实践Struts+Hibernate 二"
author: "utyphoon"
date: "2008-09-26T10:52:44Z"
tags: []
categories: ["非技术"]
slug: "eclipse-struts-hibernate"
draft: false
lastmod: "2008-09-26T10:52:44Z"
id: 246959
url: "https://ujava.iteye.com/blog/246959"
---

《在Eclipse下实践Struts+Hibernate 一》只是对数据库进行插入操作，现在来个从数据库中查询并显示，
在Action类中添加getName()引用，CommonExample.java全文如下：

```java
package com.yeepal.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.opensymphony.xwork2.ActionSupport;

public class CommonExample extends ActionSupport {

    private static final long serialVersionUID = 1L;
    Configuration cfg = new Configuration().configure();
    SessionFactory sessions = cfg.buildSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = session.beginTransaction();

    Customer customer = new Customer();
    public String rname;

    public String execute() throws Exception {
        customer.setName("phengchen");
        customer.setEmail("utyphoon@126.com");
        customer.setPassword("12345678");
       
        rname = customer.getName();

        session.save(customer);

        tx.commit();
        session.close();
        return SUCCESS;
    }

}
```


注意看中间两行黑体字部分，先定义一个变量，然后调用getName方法，就可以从数据表里得到一个查询结果，虽然方法是粗旷了点，不过结果还是成功的。
然后为了显示，我们需要做一个JSP页面，在做页面之前，我们还是需要修改一下struts.xml的，修改后的全文如下：

```xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml" />

    <package name="default" extends="struts-default">
        <action name="hello"
            class="com.yeepal.test.HelloAction">
            <result name="success">success.jsp</result>
            <result name="input">index.jsp</result>
        </action>
       
        <action name="commonexample"
            class="com.yeepal.test.CommonExample">
            <result name="success">s2.jsp</result>
            <result name="input">index.jsp</result>
        </action>

    </package>
</struts>
```


注意看黑体字那行，也就是说如果action返回一个success的话，就调用s2.jsp页面，然后s2.jsp页面的内容如下：

```html
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:property value="rname" /> <br>
</body>
</html>
```

也是个超级简单的页面，就显示一个查询出来的值，注意看黑体字部分。
运行一下看看吧。