`
utyphoon
  • 浏览: 11676 次
  • 性别: Icon_minigender_1
  • 来自: 福建
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

在Eclipse下实践Struts+Hibernate 二

阅读更多
《在Eclipse下实践Struts+Hibernate 一》只是对数据库进行插入操作,现在来个从数据库中查询并显示,
在Action类中添加getName()引用,CommonExample.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的,修改后的全文如下:
<!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页面的内容如下:
<%@ 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>

也是个超级简单的页面,就显示一个查询出来的值,注意看黑体字部分。
运行一下看看吧。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics