引言:
struts是apache software foundation支持的jakarta项目的一部分,它一个优秀的web应用框架。该框架的主要体系设计师和开发者者是craig r.mcclanahan,craig是tomcat4的主设计师和java web services developer pack实现包的主设计师,他领导着sun的javaserver faces规范开发,同时也是java ee平台的web layer archiecture。
hibernate是一个优秀的orm中间件,它可以为任何一个需要访问关系数据库的java应用服务,它的工作原理是通过文件把值对象和数据库表之间建立起一个映射关系,这样,我们只需要通过操作这些值对象和hibernate提供的一些基本类,就可以达到使用数据库的目的。
下面我们通过使用这两种技术来实现一个简单的文章发布应用,在该应用中,我们可以浏览文章,可以发布文章。
step1:
在jbuilder中新建一个名为myarticles的工程,接着在工程中新建一个名为myarticlesweb的web module,选中支持struts1.1。
step2:
往工程中添加需要的jar文件,包括hibernate3.jar和hibernate下载包lib目录下的全部jar文件,以及mysql数据库的驱动。
step3:
创建数据库myhibernate和表articles,创建的schema如下:
create database myhibernate;
use myhibernate;
create table articles( id bigint not null, title varchar(255) not null, content text not null, writedate date, primary key(id));
step4:
创建持久化类entityarticle.java,代码如下:
package com.ouxingning.hibernate;
/** * <p>title: articlesmanage project</p> * * <p>description: manage articles</p> * * <p>copyright: copyright (c) 2005</p> * * <p>company: </p> * * @author ouxingning * @version 1.0 */import java.io.*;
import java.sql.date;
public class entityarticle implements serializable {
private long id;
private string title;
private string content;
private string remark;
private date writedate;
public entityarticle() {
}
private void readobject(objectinputstream ois) throws ioexception,
classnotfoundexception {
ois.defaultreadobject();
}
private void writeobject(objectoutputstream oos) throws ioexception {
oos.defaultwriteobject();
}
public void setid(long id) {
this.id = id;
}
public void settitle(string title) {
this.title = title;
}
public void setcontent(string content) {
this.content = content;
}
public void setremark(string remark) {
this.remark = remark;
}
public void setwritedate(date writedate) {
this.writedate = writedate;
}
public long getid() {
return id;
}
public string gettitle() {
return title;
}
public string getcontent() {
return content;
}
public string getremark() {
return remark;
}
public date getwritedate() {
return writedate;
}}
step5:
创建对象-关系映射文件entityarticle.hbm.xml,如下:
<?xml version="1.0"?><!doctype hibernate-mapping public
"-//hibernate/hibernate mapping dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping
package="com.ouxingning.hibernate">
<class name="entityarticle" table="articles" lazy="false">
<comment>article elements.</comment>
<id name="id">
<generator class="increment"/>
</id>
<property name="title" column="title" type="string" not-null="true"/>
<property name="content" column="content" type="text" not-null="true"/>
<property name="writedate" column="writedate" type="date"/>
</class></hibernate-mapping>
step6:
创建hibernate配置文件hibernate.cfg.xml,如下:
<!doctype hibernate-configuration public
"-//hibernate/hibernate configuration dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration>
<session-factory >
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
<property name="connection.driver_class">com.mysql.jdbc.driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/myhibernate?useunicode=true&characterencoding=gbk</property>
<property name="connection.username">root</property>
<property name="connection.password">ouxingning</property>
<mapping resource="com/ouxingning/hibernate/entityarticle.hbm.xml"/>
</session-factory></hibernate-configuration>
step7:
创建hibernate的业务逻辑businessservice.java,供struts的action调用,代码如下:
package com.ouxingning.hibernate;
/** * <p>title: articlesmanage project</p> * * <p>description: manage articles</p> * * <p>copyright: copyright (c) 2005</p> * * <p>company: </p> * * @author ouxingning * @version 1.0 */import org.hibernate.*;
import org.hibernate.cfg.*;import java.sql.date;
import java.util.*;
import com.ouxingning.hibernate.entityarticle;
public class businessservice {
private static sessionfactory sessionfactory;
static {
//create the sessionfactory
try {
sessionfactory = new configuration().configure().
buildsessionfactory();
} catch (exception ex) {
ex.printstacktrace();
}
}
//find all instances of entityarticle
public list findallarticles() {
list articles = new arraylist();
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
articles = session.createquery("from entityarticle").list();
tx.commit();
session.close();
return articles;
}
//save an persistent instance of entityanticle
public void savearticle(entityarticle article) {
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
entityarticle myarticle = new entityarticle();
myarticle.settitle(article.gettitle());
myarticle.setcontent(article.getcontent());
myarticle.setwritedate(article.getwritedate());
myarticle.setremark(article.getremark());
session.save(myarticle);
tx.commit();
session.close();
}
//find an instance of entityarticle by its indentifier property
public entityarticle findarticlebyid(long id) {
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
entityarticle ea = (entityarticle) session.load(entityarticle.class, id);
tx.commit();
session.close();
return ea;
}
//delete the instance of entityarticle
public void deletearticle(entityarticle ea) {
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
session.delete(ea);
tx.commit();
session.close();
}
//update the instance of entityarticle public void updatearticle(entityarticle ea) {
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
session.update(ea);
tx.commit();
session.close();
}
public businessservice() {
}
public static void main(string args[]) {
businessservice bs = new businessservice();
entityarticle ea = new entityarticle(); /*
ea.settitle("欧兴宁'title");
ea.setcontent("欧兴宁的内容");
ea.setremark("欧兴宁的备注");
//change the type java.util.date to java.sql.date
java.util.date ud = new java.util.date();
ea.setwritedate(new java.sql.date(ud.gettime()));
bs.savearticle(ea);
system.out.println("good");
list results = bs.findallarticles();
for(int i=0;i<results.size();i++){
ea = (entityarticle)results.get(i);
system.out.print(ea.getid() + "/t");
system.out.print(ea.gettitle() + "/t");
system.out.print(ea.getcontent() + "/t");
system.out.println(ea.getwritedate());
}*/ for (int i = 0; i < 9; i++) {
long id = new long(i);
ea = bs.findarticlebyid(id);
system.out.print(ea.getid() + "::");
system.out.print(ea.gettitle() + "/t");
system.out.print(ea.getwritedate() + "/t");
system.out.println(ea.getcontent());
}
system.out.println("end");
}}
step8:
创建用于显示列表的表现层文件articlelist.jsp,代码如下:
<%@taglib uri="/web-inf/struts-tiles.tld" prefix="tiles"%><%@taglib uri="/web-inf/struts-nested.tld" prefix="nested"%><%@taglib uri="/web-inf/struts-logic.tld" prefix="logic"%><%@taglib uri="/web-inf/struts-template.tld" prefix="template"%><%@taglib uri="/web-inf/struts-bean.tld" prefix="bean"%><%@taglib uri="/web-inf/struts-html.tld" prefix="html"%><!doctype html public "-//w3c//dtd html 4.01 transitional//en""http://www.w3.org/tr/html4/loose.dtd"><%@page contenttype="text/html;
charset=gbk"%><%@page import="com.ouxingning.hibernate.*"%><%@page import="java.util.*"%><html:html locale="true"><head>
<meta http-equiv="content-type" content="text/html;
charset=gb2312"><title>文章列表</title>
<html:base/></head><body>
<table width="780" border="0" align="center">
<tr>
<td align="center" valign="middle">
<h1>文章列表</h1>
</td>
</tr>
<tr>
<td align="center" valign="middle">
<hr size="1">
</td>
</tr>
<logic:iterate id="article" name="articles" type="com.ouxingning.hibernate.entityarticle">
<tr> <td align="left" valign="middle" bgcolor="#ffffff">
<bean:write name="article" property="id"/>
、
<html:link forward="showarticle" paramid="articleid" paramname="article" paramproperty="id">
<bean:write name="article" property="title"/>
</html:link>
[
<bean:write name="article" property="writedate"/>
]
</td>
</tr>
</logic:iterate>
</table></body></html:html>
step9:
创建用于显示每篇文章内容的表现层文件showarticle.jsp,代码如下:
<%@taglib uri="/web-inf/struts-tiles.tld" prefix="tiles"%><%@taglib uri="/web-inf/struts-nested.tld" prefix="nested"%><%@taglib uri="/web-inf/struts-logic.tld" prefix="logic"%><%@taglib uri="/web-inf/struts-template.tld" prefix="template"%><%@taglib uri="/web-inf/struts-bean.tld" prefix="bean"%><%@taglib uri="/web-inf/struts-html.tld" prefix="html"%><!doctype html public "-//w3c//dtd html 4.01 transitional//en""http://www.w3.org/tr/html4/loose.dtd"><%@page contenttype="text/html; charset=gbk"%><%@page import="com.ouxingning.hibernate.*"%><%@page import="java.util.*"%><html:html locale="true"><head> <meta http-equiv="content-type" content="text/html;
charset=gb2312"><title><bean:write name="article" property="title"/></title>
<html:base/></head><body>
<table width="780" border="0" align="center">
<tr>
<td align="center" valign="middle">
<h1><bean:write name="article" property="title"/></h1>
</td>
</tr>
<tr>
<td align="center" valign="middle">
<hr size="1">
</td>
</tr>
<tr>
<td align="left" valign="middle" bgcolor="#ffffff">
<bean:write name="article" property="content"/>
</td>
</tr>
<tr>
<td align="center" valign="middle">
<hr size="1">
</td>
</tr>
<tr>
<td align="right" valign="middle">
created at: <bean:write name="article" property="writedate"/>
</td>
</tr>
</table></body></html:html>
step10:
创建用于提交文章的表现层文件writearticle.jsp,代码如下:
<%@taglib uri="/web-inf/struts-tiles.tld" prefix="tiles"%><%@taglib uri="/web-inf/struts-nested.tld" prefix="nested"%><%@taglib uri="/web-inf/struts-logic.tld" prefix="logic"%><%@taglib uri="/web-inf/struts-template.tld" prefix="template"%><%@taglib uri="/web-inf/struts-bean.tld" prefix="bean"%><%@taglib uri="/web-inf/struts-html.tld" prefix="html"%><!doctype html public "-//w3c//dtd html 4.01 transitional//en""http://www.w3.org/tr/html4/loose.dtd"><%@page contenttype="text/html; charset=gbk"%><html:html locale="true"><head> <meta http-equiv="content-type" content="text/html; charset=gb2312"><title>写文章</title> <html:base/></head><body>
<html:errors/> <html:form action="/writearticleaction" method="post">
<table width="780" border="0" align="center">
<tr>
<td colspan="2" align="center" valign="middle">
<h1>写文章</h1>
</td>
</tr>
<tr>
<td colspan="2" align="center" valign="middle">
<hr size="1">
</td>
</tr>
<tr>
<td align="right" valign="middle">文章标题:</td>
<td align="left" valign="middle">
<html:text property="title" size="81"/>
</td>
</tr>
<tr>
<td align="right" valign="top">文章内容:</td>
<td align="left" valign="middle">
<html:textarea cols="80" rows="20" property="content"> </html:textarea>
</td>
</tr>
<tr align="center" valign="middle">
<td align="right" valign="top">
<html:submit value="发表文章" property="submit"/>
</td>
<td align="left" valign="middle">
<html:reset value="清除内容" property="reset"/>
</td>
</tr>
</table>
</html:form></body></html:html>
step11:
创建articleactionform.java,代码如下:
package com.ouxingning.struts;import org.apache.struts.action.actionform;import org.apache.struts.action.actionerrors;import org.apache.struts.action.actionmapping;import javax.servlet.http.httpservletrequest;import org.apache.struts.*;import org.apache.struts.action.*;public class articleactionform extends actionform {
private string content;
private string title;
public string getcontent() {
return content;
}
public void setcontent(string content) {
this.content = content;
}
public void settitle(string title) {
this.title = title;
}
public string gettitle() {
return title;
}
public actionerrors validate(actionmapping actionmapping,
httpservletrequest httpservletrequest) {
actionerrors errors = new actionerrors();
if ((title == null) || (title.length() < 1)) {
errors.add("title", new actionerror("writearticle.err.title"));
}
if ((content == null) || (content.length() < 1)) {
errors.add("content", new actionerror("writearticle.err.content"));
}
return errors;
} public void reset(actionmapping actionmapping,
httpservletrequest servletrequest) {
content = null;
title = null;
}}
step12:
创建writearticleaction.java,代码如下:
package com.ouxingning.struts;import org.apache.struts.action.actionmapping;
import org.apache.struts.action.actionform;import javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import org.apache.struts.action.actionforward;
import org.apache.struts.action.action;import com.ouxingning.hibernate.*;
import com.ouxingning.struts.*;public class writearticleaction extends action {
public actionforward execute(actionmapping actionmapping,
actionform actionform,
httpservletrequest servletrequest,
httpservletresponse servletresponse) {
articleactionform articleactionform = (articleactionform) actionform;
businessservice bs = new businessservice();
entityarticle ea = new entityarticle();
articleactionform aaf = (articleactionform)actionform;
ea.settitle(aaf.gettitle());
ea.setcontent(aaf.getcontent());
//change java.util.date to java.sql.date
java.util.date ud = new java.util.date();
ea.setwritedate(new java.sql.date(ud.gettime()));
//persistant the instance of entityarticle
bs.savearticle(ea);
return actionmapping.findforward("success");
}}
step13:
创建articlelistaction.java,代码如下:
package com.ouxingning.struts;
import org.apache.struts.action.actionmapping;
import org.apache.struts.action.actionform;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.struts.action.actionforward;
import org.apache.struts.action.action;import java.util.*;
import com.ouxingning.hibernate.*;
public class articlelistaction extends action {
public actionforward execute(actionmapping actionmapping,
actionform actionform,
httpservletrequest servletrequest,
httpservletresponse servletresponse) {
businessservice bs = new businessservice();
list articles = bs.findallarticles();
servletrequest.setattribute("articles",articles);
return actionmapping.findforward("showarticles");
}}
step14:
创建showarticleaction.java,代码如下:
package com.ouxingning.struts;import org.apache.struts.action.actionmapping;import org.apache.struts.action.actionform;import javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import org.apache.struts.action.actionforward;import org.apache.struts.action.action;import com.ouxingning.hibernate.*;public class showarticleaction extends action {
public actionforward execute(actionmapping actionmapping,
actionform actionform,
httpservletrequest servletrequest,
httpservletresponse servletresponse) {
businessservice bs = new businessservice();
entityarticle ea = new entityarticle();
ea = bs.findarticlebyid(new long(servletrequest.getparameter("articleid")));
servletrequest.setattribute("article", ea);
return actionmapping.findforward("showarticle");
}}
step15:
创建个名叫setcharacterencodingfilter.java的filter用于处理中文乱码问题,代码如下:
package com.ouxingning.struts;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;public class setcharacterencodingfilter extends httpservlet implements filter { private filterconfig filterconfig; //handle the passed-in filterconfig public void init(filterconfig filterconfig) throws servletexception {
this.filterconfig = filterconfig;
}
//process the request/response pair
public void dofilter(servletrequest request, servletresponse response,
filterchain filterchain) {
try {
request.setcharacterencoding("gbk");
filterchain.dofilter(request, response);
} catch (servletexception sx) {
filterconfig.getservletcontext().log(sx.getmessage());
} catch (ioexception iox) {
filterconfig.getservletcontext().log(iox.getmessage());
}
}
//clean up resources
public void destroy() {
}}
step16:
jbuilder自动生成的web.xml文件,如下:
<?xml version="1.0" encoding="utf-8"?><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <display-name>myarticles</display-name> <jsp-config> <taglib> <taglib-uri>/web-inf/struts-bean.tld</taglib-uri> <taglib-location>/web-inf/struts-bean.tld</taglib-location> </taglib> <taglib>
<taglib-uri>/web-inf/struts-html.tld</taglib-uri>
<taglib-location>/web-inf/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/web-inf/struts-logic.tld</taglib-uri>
<taglib-location>/web-inf/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/web-inf/struts-template.tld</taglib-uri>
<taglib-location>/web-inf/struts-template.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/web-inf/struts-tiles.tld</taglib-uri>
<taglib-location>/web-inf/struts-tiles.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/web-inf/struts-nested.tld</taglib-uri>
<taglib-location>/web-inf/struts-nested.tld</taglib-location>
</taglib>
</jsp-config>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.actionservlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/web-inf/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>application</param-name>
<param-value>applicationresources</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern> </servlet-mapping> <filter>
<filter-name>setcharacterencodingfilter</filter-name>
<filter-class>com.ouxingning.struts.setcharacterencodingfilter</filter-class>
</filter> <filter-mapping>
<filter-name>setcharacterencodingfilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>request</dispatcher>
<dispatcher>forward</dispatcher>
<dispatcher>include</dispatcher>
<dispatcher>error</dispatcher>
</filter-mapping>
<servlet>
step17:
jbuilder自动生成的struts-config.xml文件,如下:
<?xml version="1.0" encoding="utf-8"?><!doctype struts-config public "-//apache software foundation//dtd struts configuration 1.1//en" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config>
<form-beans>
<form-bean name="articleactionform" type="com.ouxingning.struts.articleactionform" /> </form-beans> <global-forwards>
<forward contextrelative="true" name="articles" path="/articlelistaction.do" redirect="true" />
<forward contextrelative="true" name="showarticle" path="/showarticleaction.do" /> </global-forwards> <action-mappings>
<action input="/pages/articlelist.jsp" path="/articlelistaction" scope="request" type="com.ouxingning.struts.articlelistaction">
<forward contextrelative="true" name="showarticles" path="/pages/articlelist.jsp" redirect="false" />
</action>
<action input="/pages/writearticle.jsp" name="articleactionform" path="/writearticleaction" scope="request" type="com.ouxingning.struts.writearticleaction">
<forward name="success" path="/index.jsp" />
</action>
<action input="/pages/articlelist.jsp" path="/showarticleaction" scope="request" type="com.ouxingning.struts.showarticleaction">
<forward contextrelative="true" name="showarticle" path="/pages/showarticle.jsp" />
</action> </action-mappings></struts-config>
总结:
在这个简单的文章发布应用中,我们使用了struts作为表现层框架,使用了hibernate作为持久化层框架,大大增强的应用的可扩展性和可维护性。各位对struts或hibernate感兴趣的朋友可以继续扩展该应用,在扩展过程中,《struts in action》,《hibernate in action》以及hibernate的文档都是很好的参考资料。
闽公网安备 35060202000074号