Topic: [实战+疑问]一个Struts+Hibernate的例子

  Print this page

1.[实战+疑问]一个Struts+Hibernate的例子 Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:32

介绍:很简单的一个功能,添加一段内容到数据库,
浏览添加的内容。
添加页面:input.jsp
浏览页面:list.jsp

数据库结构:

CREATE TABLE book (
id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL default '',
PRIMARY KEY (id)
) TYPE=MyISAM;


目录结构如下:

├─src
│ │ hibernate.cfg.xml
│ │
│ └─com
│ └─book
│ ├─hibernate
│ │ AbstractBook.java
│ │ Book.hbm.xml
│ │ Book.java
│ │ BookService.java
│ │ SessionFactory.java
│ │
│ └─struts
│ │ ApplicationResources.properties
│ │
│ ├─action
│ │ InputAction.java
│ │
│ └─form
│ InputForm.java

└─WebRoot
│ inc.jsp
│ list.jsp

├─form
│ input.jsp

├─META-INF
│ MANIFEST.MF

└─WEB-INF
│ .struts-config.mex
│ struts-bean.tld
│ struts-config.xml
│ struts-html.tld
│ struts-logic.tld
│ struts-nested.tld
│ struts-template.tld
│ struts-tiles.tld
│ validator-rules.xml
│ web.xml

├─classes
│ │ hibernate.cfg.xml
│ │
│ └─com
│ └─book
│ ├─hibernate
│ └─struts
│ ├─action
│ └─form
└─lib
ant-1.5.3.jar
ant-optional-1.5.3.jar
c3p0-0.8.4.5.jar
cglib-full-2.0.1.jar
commons-beanutils.jar
commons-collections-2.1.jar
commons-collections.jar
commons-dbcp-1.1.jar
commons-digester.jar
commons-fileupload.jar
commons-lang-1.0.1.jar
commons-lang.jar
commons-logging-1.0.3.jar
commons-logging.jar
commons-pool-1.1.jar
commons-validator.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.4.jar
ehcache-0.7.jar
hibernate2.jar
jaas.jar
jakarta-oro.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-system.jar
jcs-1.0-dev.jar
jdbc2_0-stdext.jar
jgroups-2.2.1.jar
jta.jar
junit-3.8.1.jar
log4j-1.2.8.jar
odmg-3.0.jar
oscache-2.0.jar
proxool-0.8.3.jar
struts-legacy.jar
struts.jar
swarmcache-1.0rc2.jar
xalan-2.4.0.jar
xerces-2.4.0.jar
xml-apis.jar


下面是相关代码:

2.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:34

inc.jsp


<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@taglib uri="/tags/struts-bean" prefix="bean" %>
<%@taglib uri="/tags/struts-html" prefix="html" %>
<%@taglib uri="/tags/struts-logic" prefix="logic" %>


/form/input.jsp


<%@ include file="../inc.jsp" %>

<html>
[$nbsp][$nbsp]<head>
[$nbsp][$nbsp][$nbsp][$nbsp]<title>JSP for inputForm form</title>
[$nbsp][$nbsp]</head>
[$nbsp][$nbsp]<body>
[$nbsp][$nbsp][$nbsp][$nbsp]<html:form action="/input">
[$nbsp][$nbsp][$nbsp][$nbsp][$nbsp][$nbsp]name : <html:text property="name"/><html:errors property="name"/></br>
[$nbsp][$nbsp][$nbsp][$nbsp][$nbsp][$nbsp]<html:submit/><html:cancel/>
[$nbsp][$nbsp][$nbsp][$nbsp]</html:form>
[$nbsp][$nbsp][$nbsp][$nbsp]
[$nbsp][$nbsp]</body>
</html>


list.jsp


<%@ include file="inc.jsp"%>

<%@ page import="com.book.hibernate.*" %>
<%@ page import="java.util.*" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
</head>

<body>
This is my JSP page. <br>
<%
      /*
       * This code will generate a list of objects from the
       * database and place a reference to this list in the
       * request object.
       *
       */
      List bookList = BookService.getInstance().getBookList();
      request.setAttribute("book", bookList);
   %>

<p>List of vips in <code>Vipdata</code> table of database <code>Vipinfo</code>.</p>
<table border=1>
<logic:iterate id="element" name="book" scope="request" type="com.book.hibernate.Book" >
<tr>
<td><bean:write name="element" property="name" /></td>
</tr>
</logic:iterate>
</table>
<html:link href="input.do">input</html:link>
</body>
</html>


3.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:35

/com/book/struts/action
InputAction.java

package com.book.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.book.struts.form.InputForm;
import com.book.hibernate.*;/**

public class InputAction extends Action {

// --------------------------------------------------------- Instance Variables

// --------------------------------------------------------- Methods

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
InputForm inputForm = (InputForm) form;

Book book = new Book();
if(inputForm.getName()!=null){
book.setName(inputForm.getName());
BookService.getInstance().addBook(book);

}
return mapping.findForward("list");
//throw new UnsupportedOperationException(
// "Generated method 'execute(...)' not implemented.");
}

}


com/book/struts/form
InputForm.java


class package com.book.struts.form;

import org.apache.struts.action.ActionForm;

public class InputForm extends ActionForm {

/** name property */
private String name;

/**
* Returns the name.
* @return String
*/
public String getName() {
return name;
}

/**
* Set the name.
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}

}


4.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:37

AbstractBook.java

package com.book.hibernate;

import java.io.Serializable;

public abstract class AbstractBook
implements Serializable
{

/** The value of the simple id property. */
private java.lang.Integer id;

/** The value of the simple name property. */
private java.lang.String name;

/**
* Simple constructor of AbstractBook instances.
*/
public AbstractBook()
{
}
public AbstractBook(java.lang.Integer id)
{
this.setId(id);
}


/**
* Return the value of the id column.
* @return java.lang.Integer
*/
public java.lang.Integer getId()
{
return this.id;
}

/**
* Set the value of the id column.
* @param id
*/
public void setId(java.lang.Integer id)
{
this.id = id;
}

/**
* Return the value of the name column.
* @return java.lang.String
*/
public java.lang.String getName()
{
return this.name;
}

/**
* Set the value of the name column.
* @param name
*/
public void setName(java.lang.String name)
{
this.name = name;
}
}


Book.java


// Book.java
package com.book.hibernate;

import java.io.Serializable;

/**
* A class that represents a row in the 'book' table.
* This class may be customized as it is never re-generated
* after being created.
*/
public class Book
extends AbstractBook
implements Serializable
{
/**
* Simple constructor of Book instances.
*/
public Book()
{
}
public Book(java.lang.Integer id)
{
super(id);
}

/* Add customized code below */

}


Book.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<hibernate-mapping package="com.book.hibernate">

<class name="Book" table="book">
<id name="id" column="id">
<generator class="increment" />
</id>

<property name="name" column="name" type="java.lang.String"
not-null="true" />
</class>

</hibernate-mapping>


5.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:39

SessionFactory.java


package com.book.hibernate;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class SessionFactory {

/**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();

/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();

/** The single instance of hibernate SessionFactory */
private static net.sf.hibernate.SessionFactory sessionFactory;

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}

return session;
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* Default constructor.
*/
private SessionFactory() {
}

}


BookService.java


package com.book.hibernate;

import java.util.List;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.ObjectNotFoundException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import com.book.hibernate.Book;

/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class BookService {

private static BookService instance = null;

private BookService() {

}
/**
*
* @return
*/
public static synchronized BookService getInstance() {
if (instance == null) {
instance = new BookService();
}
return instance;
}
/**
*
* @param id
* @return
*/
public Book getBook(Long id) {
Session session = null;
try {
session = SessionFactory.currentSession();
return (Book) session.load(Book.class, id);
} catch (ObjectNotFoundException onfe) {
return null;
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException();
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
}
}
}

public void updateBook(Book book) {
/*
* Use the ConnectionFactory to retrieve an open Hibernate Session.
*
*/

Session session = null;
try {
session = SessionFactory.currentSession();
/*
* Update the state of the item using the Hibernate session's update
* method.
*
* Call the flush method to ensure that the object in saved.
*
*/
session.update(book);
session.flush();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
/*
* Regardless of whether the above processing resulted in an Exception
* or proceeded normally, we want to close the Hibernate session. When
* closing the session, we must allow for the possibility of a Hibernate
* Exception.
*
*/
finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}

}
}

}

public List getBookList() {
/*
* Use the ConnectionFactory to retrieve an open Hibernate Session.
*
*/
Session session = null;

try {
session = SessionFactory.currentSession();
/*
* Build HQL (Hibernate Query Language) query to retrieve a list of
* all the items currently stored by Hibernate.
*/
Query query = session
.createQuery("select Book from com.book.hibernate.Book Book order by Book.id");
return query.list();

} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
/*
* Regardless of whether the above processing resulted in an Exception
* or proceeded normally, we want to close the Hibernate session. When
* closing the session, we must allow for the possibility of a Hibernate
* Exception.
*
*/
finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}

}
}
}

/**
* addItem() inserts new <code>Item</code> into the database through
* Hibernate.
*
* @param item
* A new <code>Item</code> to be added.
*/
public void addBook(Book data) {

Session session = null;

try {
session = SessionFactory.currentSession();
session.save(data);
session.flush();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}
/*
* Regardless of whether the above processing resulted in an Exception
* or proceeded normally, we want to close the Hibernate session. When
* closing the session, we must allow for the possibility of a Hibernate
* Exception.
*
*/
finally {
if (session != null) {
try {

session.close();
} catch (HibernateException e) {
System.err.println("Hibernate Exception" + e.getMessage());
throw new RuntimeException(e);
}

}
}

}
}

6.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:43

很多内容都是参照别人的例子写的。

感觉没什么错,
但是部署到tomcat,就是报错,刚刚接触,
想用个简单的例子实践一下,但是老失败。实在是受打击。

还请高手看看。哪里有问题。谢谢

提交input之后,tomcat提示:

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException
org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:545)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:486)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

root cause

java.lang.NullPointerException
com.book.hibernate.SessionFactory.currentSession(SessionFactory.java:56)
com.book.hibernate.BookService.addBook(BookService.java:162)
com.book.struts.action.InputAction.execute(InputAction.java:46)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)



看来好像是SessionFactory出问题了,我看别人也差不多是这种模式写的呢。实在想不出什么问题。
单独试验Struts or Hibernate,好像问题不多,但是一结合起来。问题太多。
即使是个很简单的例子,都问题很多。真是....
Black EyeBlack Eye

7.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: seaboy
Posted on: 2004-09-01 10:47

SessionFactory 好像并不能建立session???

现在数据库有数据,浏览list,也报错,

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException
  org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)
  org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
  org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

root cause

java.lang.NullPointerException
  com.book.hibernate.SessionFactory.currentSession(SessionFactory.java:56)
  com.book.hibernate.BookService.getBookList(BookService.java:117)
  org.apache.jsp.list_jsp._jspService(list_jsp.java:117)
  org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
  org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
  org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
  org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

8.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: hua123456
Posted on: 2004-09-15 17:43

关注中..

9.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: ming500
Posted on: 2004-09-15 18:10


10.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: cyfboy
Posted on: 2004-10-12 14:55

关注中!!

11.Re:[实战+疑问]一个Struts+Hibernate的例子 [Re: seaboy] Copy to clipboard
Posted by: LostParadise
Posted on: 2004-10-14 12:55

我只是花了2分钟看了一下,不一定准确。
session = SessionFactory.currentSession();
如果在没有初始化session之前就运行到这里,一定会出现java.lang.NullPointerException的。所以要确保先创建了一个Seesion先。具体你查查hibernate的教程吧。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923