如何实现Hibernate_Struts
v\:* { behavior: url(#default#VML) }
o\:* { behavior: url(#default#VML) }
.shape { behavior: url(#default#VML) }
Hibernate+Struts应用程序的JavaWebStudio 2005下快速、可视化开发
Struts中文论坛:http://www.javawebstudio.com/
JavaWebStudio 2005下载地址:http://www.javawebstudio.com/bbs/dispbbs.asp?boardID=5&ID=3&page=1
[目标]
本例的目标是实现一个简单的Struts
数据库应用程序。其功能是从SQLServer
2000中读取数据,并以表格的形式在输出页中显示出来。
定义一个名为“Test”表的字段:
录入一些测试数据:
[效果]
(1)全部显示:
输入页面:
输出页面:
(2)查询显示:
[背景知识]
[步骤]
1、打开Visual
Struts开发环境:
从桌面JavaWebStudio快揵或BIN目录下的JavaWebStudio.exe文件启动JavaWebStudio的Visual
Struts开发环境。
2、建立一个“空的Hibernate_Struts项目模板”应用程序:
选择菜单“文件”—“新建”—“新建项目”,弹出新建项目对话框,如图3-1所示:
在对话框中选择“空的Struts数据库应用模板”,在项目名称中输入“MyHibernate”,package
(包名)和位置(项目的路径)采用默认的值就行,当然也可以根据需要改变。最后点击“确定”按钮完成新项目的建立。
从文件管理器中可看出MyHibernate项目的文件结构如下:
在MyHibernate项目根目录下包含四个子目录和两个文件,这是JavaWebStudio项目的标准结构,最好不要改变它们默认的名称,否则会出现问题。
3、利用Struts数据库应用文件向导建立新的应用:
在JavaWebStudio文件管理器内点击鼠标右键,在弹出的菜单中选择“Hibernate”—“Hibernate_Struts文件向导”进入Struts文件向导对话框,也可以选择菜单“文件向导”—“
Hibernate_Struts文件向导”进入Hibernate文件向导对话框。如下图所示:
(1)输入文件名:
(2)从数据源中导入SQL语句及数据表的字段信息(字段名和字段类型):
(3)从数据据表中选择所需的表“Test”。
需要特别注意的是,这里的“从数据源中导入SQL语句及数据表的字段信息”及“从数据据表中选择所需的表”仅仅是为了自动生成SQL语句及读取字段信息,这里完成可以直接手工输入,与该项目的数据库连接池的配置无关,下面第(4)点将另行配置数据库连接池。
DAO文件、输入JSP文件、ActionForm文件、Action文件等选择默认就行了,主要是设置一下JSPOut文件,让它自动分页、每页显示4条记录,选择删除、编辑、链接和添加新记录功能。
接下来配置数据库连接池,其它属性页可采用默认的就行了,下面直接转去数据连接配置属性页即可。
(4)配置数据库连接池:
这里要特别注意的是Hibernate的数据库连接池配置文件是Hibernate.properties,并且dialect类名是org.hibernate.dialect.SQLServerDialect。
4、项目文件结构
项目目录结构分析见《如何实现最简单的Struts程序》,这次Hibernate文件向导自动生成了八个文件,其中web目录下是输入、输出两个JSP文件,src目录下是Java文件。除了文件名是我们输入之外,所有程序源代码都是文件向导自动生成的,所有的配置也是自动完成的。
刷新JavaWebStudio文件管理器,这时发现web目录下自动生成了两个文件,分别是Test.jsp.jsp、TestInsert.jsp和TestOut.jsp.jsp,分别是查询条件输入JSP文件、新记录添加JSP文件和表格输出JSP文件;src\emptyprj目录下自动生成了五个文件,分别是TestAction.java和TestForm.java,前者是Action文件,后者是FormAction文件;还有是数据库操作文件Test.java和TestDAO.java,前者用于保存数据表记录的Bean,后者是数据库操作DAO文件;还要特别注意的是还有一个xml文件,就是Test.hbm.xml,用于Hibernate对象与数据库的映射。
Test.jsp文件:
TestInsert.jsp文件:
TestOut.jsp文件:
5、编译、启动服务器、运行:
通过工具条上的按键分别编译项目及启动服务器,然后把开Test.jsp并通过工具条上的“运行”按键运行Test.jsp。
这里将采用调试状态下的运行方式:
(1)
显示调试工具条:
注:单步执行可跟踪进原函数执行;单过程执行按语句跟踪,一般选择单过程执行即可。
(2)选择调试状态下的“编译”:
输出栏中输出如下提示信息:
C:\Documents and Settings\Administrator\桌面>F:
F:\>cd
F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate
F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate>ant -buildfile build.xml
Buildfile:
build.xml
prepare:
[copy]
Copying 1 file to
F:\JavaWebStudio\jakarta-tomcat-5.5.4\webapps\MyHibernate\WEB-INF\classes
compile:
[javac]
Compiling 5 source files to
F:\JavaWebStudio\jakarta-tomcat-5.5.4\webapps\MyHibernate\WEB-INF\classes
[javac]
F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate\src\emptyprj\TestAction.java:68:
setUserID(int) in emptyprj.Test cannot be applied to (java.lang.String)
[javac] m_Test.setUserID(expression);
[javac] ^
[javac]
1 error
BUILD
FAILED
F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate\build.xml:34: Compile failed;
see the compiler error output for details.
Total time:
9 seconds
出现一个错误,原因是因为前面我们设置userID为整数类型,而这里的expression是字符串类型,所以要修改一下TestAction.java文件:
package
emptyprj;
import
emptyprj.TestDAO;
import
java.lang.reflect.InvocationTargetException;
import
java.util.Locale;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpSession;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
org.apache.commons.beanutils.PropertyUtils;
import
org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;
import
org.apache.struts.action.Action;
import
org.apache.struts.action.ActionError;
import
org.apache.struts.action.ActionErrors;
import
org.apache.struts.action.ActionForm;
import
org.apache.struts.action.ActionForward;
import
org.apache.struts.action.ActionMapping;
import
org.apache.struts.action.ActionServlet;
import
org.apache.struts.util.ModuleException;
import
org.apache.struts.util.MessageResources;
import
java.io.IOException;
import
java.sql.Connection;
import
java.sql.SQLException;
import
java.util.Collection;
public
final class TestAction extends Action
{
//
变量定义:
private
Log log = LogFactory.getLog("org.apache.struts.webapp.Example");
public
TestAction() {
}
//函数定义:
public
ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
//
Extract attributes and parameters we will need
Locale locale = getLocale(request);
MessageResources messages = getResources(request);
HttpSession session = request.getSession();
TestForm m_TestForm = (TestForm) form;
TestDAO m_TestDAO = TestDAO.getInstance(); //定义Hibernate__DAO对象,用于实现数据库的各种操作
String action=request.getParameter("action"); //动作类型
String search=request.getParameter("search"); //数据库查找方式
String expression=request.getParameter("expression"); //参数,这里用于保存记录(行)的ID数据
if(action==null)action="find";
if(search==null)search="UNsearch";
if(expression==null)expression="";
expression=toChinese(expression); //处理中文问题,实现编码转换
/////////
if("delete".equals(action)) //删除记录操作
{
Test m_Test= new Test();
//<delete>
m_Test.setUserID(expression);
//</delete>
m_TestDAO.removeID(m_Test);
}
////////////
if("update".equals(action)||"insert".equals(action)) //更新、添加记录操作
{
Test m_Test= new Test();
//<update>
m_Test.setUserID(m_TestForm.getUserID());
m_Test.setUsername(m_TestForm.getUsername());
m_Test.setPassword(m_TestForm.getPassword());
m_Test.setRole(m_TestForm.getRole());
//</update>
if("update".equals(action)) //调用DAO对象更新记录
m_TestDAO.update(m_Test,expression);
if("insert".equals(action)) //调用DAO对象添加记录
m_TestDAO.create(m_Test);
}
///////////////HQL_查找数据库
String sql="from emptyprj.Test Test";
////SQL字符处理,主要是加入查询条件,如果是全部显示,可把这部分代码删除。
if("search".equals(search))
{
String selectsql;
//<search>
sql+=" where ";
sql+="userID";
sql+="=";
if("NULL".equals(expression)||"".equals(expression))
{
sql+=m_TestForm .getUserID();
}
else
{
sql+=expression;
}
sql+="";
//</search>
}
//<分页>
m_TestDAO.setLength(4);//设置每页显示记录数
int ipage;//当前页
try
{
String page=request.getParameter("page");//分页参数,读取请求的当前页
ipage=java.lang.Integer.parseInt(page,10);
}
catch (Exception e)
{
ipage=m_TestForm.getPage();
}
if(ipage<1)ipage=1;
Collection col = m_TestDAO.findSQL("select Test "+sql,"select
count(Test) "+sql,ipage);//通过DAO对象查询数据
request.setAttribute("Test",col); //保存数据
String pagestr=m_TestDAO.getPagestr(ipage);//分页字符串,分页内容
String s_find,str;
if(!"search".equals(search)) //查找和全部显示两个不同的操作,其分页字符串不同,在此进行处理。如果是全部显示则去掉"search=search&"
{
s_find="search=search&";
while(pagestr.indexOf(s_find)!=-1)
{
str=pagestr.substring(0,pagestr.indexOf(s_find));
str+=pagestr.substring(pagestr.indexOf(s_find)+s_find.length(),pagestr.length());
pagestr=str;
}
}
m_TestForm.setPagestr(pagestr);
m_TestForm.setAction(action);
request.setAttribute("TestForm",m_TestForm);
//</分页>
return mapping.findForward("success");
}
public
String toChinese(String ss) {
//处理中文问题,实现编码转换
if (ss
!= null) {
try {
String temp_p = ss;
byte[] temp_t = temp_p.getBytes("ISO8859-1");
ss
= new String(temp_t);
}
catch
(Exception e) {
System.err.println("toChinese exception:" + e.getMessage());
System.err.println("The String is:" + ss);
}
}
return
ss;
}
}
把上述TestAction.java文件第68行:
m_Test.setUserID(expression);
修改成:
m_Test.setUserID(java.lang.Integer.parseInt(expression,10));
(3)启动调试状态下的服务器:
输出栏中输出如下提示信息:
C:\Documents and Settings\Administrator\桌面>F:
F:\>cd F:\JavaWebStudio\\jakarta-tomcat-5.5.4\bin\
F:\JavaWebStudio\jakarta-tomcat-5.5.4\bin>startup_jpda.bat
Using CATALINA_BASE: F:\JavaWebStudio\jakarta-tomcat-5.5.4
Using CATALINA_HOME: F:\JavaWebStudio\jakarta-tomcat-5.5.4
Using CATALINA_TMPDIR:
F:\JavaWebStudio\jakarta-tomcat-5.5.4\temp
Using JAVA_HOME: F:\JavaWebStudio\jdk
服务器启动成功。
(4)启动调试状态:
输出栏中输出如下提示信息:
下面将执行的命令是: JDB -attach
jdbconn
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
>
(5)设置断点:
打开TestAction文件,分别在127、136行设置两个断点。输出栏中输出如下提示信息:
下面将执行的命令是: JDB -attach
jdbconn
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
> 下面将执行的输入参数是:
stop at emptyprj.TestAction:127
Deferring breakpoint emptyprj.TestAction:127.
It will be set after the class is loaded.
> 下面将执行的输入参数是:
stop at emptyprj.TestAction:136
Deferring breakpoint emptyprj.TestAction:136.
It will be set after the class is loaded.
>
(6)打开Test.jsp文件,并运行:
运行结果:
试一下全部显示功能,点击“全部显示”接钮,如果如下图所示:
可见运行到了断点第128行处,再点击一下调试工具条中的单过程执行,这时的变量值从输出提示栏中可看出:
http-8080-Processor25[1]
下面将执行的输入参数是: locals
下面将执行的输入参数是:
next
Method arguments:
mapping = instance of
org.apache.struts.action.ActionMapping(id=1701)
form = instance of
emptyprj.TestForm(id=1702)
request = instance of
org.apache.catalina.connector.RequestFacade(id=1703)
response = instance of
org.apache.catalina.connector.ResponseFacade(id=1704)
Local variables:
locale = instance of
java.util.Locale(id=1705)
messages = instance of
org.apache.struts.util.PropertyMessageResources(id=1706)
session = instance of
org.apache.catalina.session.StandardSessionFacade(id=1707)
m_TestForm = instance of
emptyprj.TestForm(id=1702)
m_TestDAO = instance of
emptyprj.TestDAO(id=1708)
action = "search"
search = "UNsearch"
expression = "NULL"
sql = "from emptyprj.Test Test"
ipage = 1
http-8080-Processor25[1] >
Step completed:
"thread=http-8080-Processor25", emptyprj.TestAction.execute(), line=128 bci=509
http-8080-Processor25[1]
现在试一下单步执行:
http-8080-Processor25[1]
下面将执行的输入参数是: locals
下面将执行的输入参数是:
step
Method arguments:
mapping = instance of
org.apache.struts.action.ActionMapping(id=1752)
form = instance of
emptyprj.TestForm(id=1753)
request = instance of
org.apache.catalina.connector.RequestFacade(id=1754)
response = instance of
org.apache.catalina.connector.ResponseFacade(id=1755)
Local variables:
locale = instance of
java.util.Locale(id=1756)
messages = instance of
org.apache.struts.util.PropertyMessageResources(id=1757)
session = instance of
org.apache.catalina.session.StandardSessionFacade(id=1758)
m_TestForm = instance of
emptyprj.TestForm(id=1753)
m_TestDAO = instance of
emptyprj.TestDAO(id=1759)
action = "search"
search = "UNsearch"
expression = "NULL"
sql = "from emptyprj.Test Test"
ipage = 1
col = instance of
java.util.ArrayList(id=2326)
http-8080-Processor25[1] >
Step completed:
"thread=http-8080-Processor25",
org.apache.catalina.connector.RequestFacade.setAttribute(), line=346 bci=0
http-8080-Processor25[1]
这时执行到了org.apache.catalina.connector.RequestFacade.setAttribute(),RequestFacade.java文件的第246行。
点击一下调试工具条中的
“执行到下一个断点”,执行到第137行。
再点击一下调试工具条中的
“执行到下一个断点”,输出最后结果,如下图所示。
通过上述步骤,实现了预计的目标功能。
[程序源代码]
ConnectionFactory.java文件:
package emptyprj;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ConnectionFactory
{
private static ConnectionFactory
instance = null;
private SessionFactory
sessionFactory = null;
private ConnectionFactory()
{
try
{
//从这里装截映射文件
Configuration cfg =
new Configuration().
addClass(emptyprj.Test.class);
sessionFactory =
cfg.buildSessionFactory();
}
catch (MappingException e)
{
System.err.println("Mapping Exception" + e.getMessage());
throw new
RuntimeException(e);
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
}
public static synchronized
ConnectionFactory getInstance()
{
if (instance == null)
{
instance = new
ConnectionFactory();
}
return instance;
}
public Session getSession()
{
try
{
Session s =
sessionFactory.openSession();
return s;
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
}
}
Test.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>
<class name="emptyprj.Test"
table="users" >
<id name="userID"
column="userID" type="int" unsaved-value="null">
<generator
class="uuid.hex"/>
</id>
<property name="username"
column="username" type="java.lang.String" />
<property name="password"
column="password" type="java.lang.String" />
<property name="role"
column="role" type="java.lang.String" />
</class>
</hibernate-mapping>
hibernate.properties数据库连接池配置文件:
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.connection.driver_class=com.microsoft.jdbc.sqlserver.SQLServerDriver
hibernate.connection.url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=EDB
hibernate.dbcp.min_size=5
hibernate.dbcp.max_size=20
hibernate.dbcp.timeout=1800
hibernate.dbcp.max_statements=50
hibernate.connection.username=sa
hibernate.connection.password=sa
///////////////////////////////////////////////////////////////////////////////////////////////////
Test.java文件:
这样定义一个用于保存数据表数据的Bean,它的变量与数据库表的字段完全对应,也就是与数据库应用文件向导中的SQL语句要查找的字段完全对应。
package emptyprj;
import java.io.Serializable;
public class Test implements
Serializable
{
private String role;
private String password;
private String username;
private int userID;
//myfiledata;
public int getUserID()
{
return (this.userID);
}
public void setUserID(int
userID)
{
this.userID=userID;
}
public String getUsername()
{
return (this.username);
}
public void setUsername(String
username)
{
this.username=username;
}
public String getPassword()
{
return (this.password);
}
public void setPassword(String
password)
{
this.password=password;
}
public String getRole()
{
return (this.role);
}
public void setRole(String role)
{
this.role=role;
}
}
TestDAO.java文件:
这里定义一个DAO类,用于实现数据加的查找、删除、更新、添加及生成分页字符串等功能。
package emptyprj;
import emptyprj.Test;
import org.hibernate.HibernateException;
import
org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import java.util.List;
import java.util.Iterator;
public class TestDAO {
private int rowCount;
private int pageCount;
private int length;
private String pagestr;
public int getLength() { return
(this.length); }
public void setLength(int length) {
this.length=length; }
private static TestDAO instance =
null;
private TestDAO ()
{
}
public static synchronized
TestDAO getInstance()
{
if (instance == null)
{
instance = new
TestDAO ();
}
return instance;
}
public Test getTest(Long id)
{
Session session =
ConnectionFactory.getInstance().getSession();
try
{
return (Test)
session.load(Test.class, id);
}
catch
(ObjectNotFoundException onfe)
{
return null;
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
finally
{
if (session !=
null)
{
try
{
session.close();
}
catch
(HibernateException e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw
new RuntimeException(e);
}
}
}
}
public void update(Test
Test,String keyID)
{
Session session =
ConnectionFactory.getInstance().getSession();
try
{
session.update(Test);
session.flush();
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
finally
{
if (session !=
null)
{
try
{
session.close();
}
catch
(HibernateException e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw
new RuntimeException(e);
}
}
}
}
public void removeID(Test Test) {
Session session =
ConnectionFactory.getInstance().getSession();
try
{
session.delete(Test);
session.flush();
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
finally
{
if (session !=
null)
{
try
{
session.close();
}
catch
(HibernateException e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw
new RuntimeException(e);
}
}
}
}
public List findSQL(String
sql,String countsql,int ipage)
{
Session session =
ConnectionFactory.getInstance().getSession();
try
{
//提取记录总数
Iterator results =
session.createQuery(countsql).iterate();
while (
results.hasNext() ) {
//Object[] row
= results.next();
//rowCount= (Integer) row[0];
rowCount=
(Integer) results.next();
}
//rowCount=10;
int offset=1;
int
pagesize=getLength();
if(getLength()<1)
{
pagesize=rowCount;
pageCount=1;
}
else
{
pageCount=rowCount/getLength()+((rowCount%getLength())>0?1:0);
offset=(ipage-1)*getLength()+1;
if(offset<1)offset=1;
if(offset>rowCount)offset=rowCount;
}
//提取数据
Query query =
session.createQuery(sql);
query.setFirstResult((ipage-1)*getLength());
query.setMaxResults(pagesize);
return
query.list();
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
finally
{
if (session !=
null)
{
try
{
session.close();
}
catch
(HibernateException e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw
new RuntimeException(e);
}
}
}
}
//添加一条新记录
public void create(Test Test)
{
Session session =
ConnectionFactory.getInstance().getSession();
try
{
session.save(Test);
session.flush();
}
catch (HibernateException
e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw new
RuntimeException(e);
}
finally
{
if (session !=
null)
{
try
{
session.close();
}
catch
(HibernateException e)
{
System.err.println("Hibernate Exception" + e.getMessage());
throw
new RuntimeException(e);
}
}
}
}
//分页字符串处理
public String getPagestr(int ipage)
{
String strPage="";
if(getLength()>0)
{
strPage+="共";
strPage+=String.valueOf(rowCount);
strPage+="条记录,共";
strPage+=String.valueOf(pageCount);
strPage+="页,当前是第";
strPage+=String.valueOf(ipage);
strPage+="页,
";
int istart,iend;
istart=ipage-5;
if(istart<0)
{istart=0;}
iend=istart+10;
if(iend>pageCount)
{iend=pageCount;}
istart=iend-10;
if(istart<0)
{istart=0;}
for(int
i=istart;i<iend;i++)
{
strPage+="<a
href='TestAction.do?action=find&search=search&page=";
strPage+=String.valueOf(i+1);
strPage+="'>";
strPage+=String.valueOf(i+1);
strPage+="</a>";
strPage+=" ";
}
}
this.pagestr=strPage;
return strPage;
}
}
TestForm.java文件:
这里定义一个ActionForm
Bean,除了包含与数据库表的字段完全对应的变量外(例如可用于保存查询条件中相应字段的变量的值、保存某行记录的数据等),还包含了与分页相关的变量,例如当前页码、分页字符串等变量。
package emptyprj;
import
javax.servlet.http.HttpServletRequest;
import
org.apache.struts.action.ActionError;
import
org.apache.struts.action.ActionErrors;
import
org.apache.struts.action.ActionForm;
import
org.apache.struts.action.ActionMapping;
public final class TestForm extends
ActionForm
{
private String role;
private String password;
private String username;
private int userID;
private int page;
private String pagestr;
private String action;
private String
mybeanvariable1;
//myfiledata;
public String
getMybeanvariable1()
{
return
(this.mybeanvariable1);
}
public void
setMybeanvariable1(String mybeanvariable1)
{
this.mybeanvariable1=mybeanvariable1;
}
public String getAction()
{
return (this.action);
}
public void setAction(String
action)
{
this.action=action;
}
public String getPagestr()
{
return (this.pagestr);
}
public void setPagestr(String
pagestr)
{
this.pagestr=pagestr;
}
public int getPage()
{
return (this.page);
}
public void setPage(int page)
{
this.page=page;
}
public int getUserID()
{
return (this.userID);
}
public void setUserID(int
userID)
{
this.userID=userID;
}
public String getUsername()
{
return (this.username);
}
public void setUsername(String
username)
{
this.username=username;
}
public String getPassword()
{
return (this.password);
}
public void setPassword(String
password)
{
this.password=password;
}
public String getRole()
{
return (this.role);
}
public void setRole(String role)
{
this.role=role;
}
}
TestAction.java文件:
这里定义一个Action类,用于实现页面的转发功能,另外还包括了不同请求类型的不同操作。其中action变量表示操作类型,相当于事件类型。通过这个变量,实现了类似于.NET中的“事件驱动”的功能。
package emptyprj;
import emptyprj.TestDAO;
import
java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import
org.apache.struts.action.ActionError;
import
org.apache.struts.action.ActionErrors;
import
org.apache.struts.action.ActionForm;
import
org.apache.struts.action.ActionForward;
import
org.apache.struts.action.ActionMapping;
import
org.apache.struts.action.ActionServlet;
import
org.apache.struts.util.ModuleException;
import
org.apache.struts.util.MessageResources;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
public final class TestAction extends
Action
{
//
变量定义:
private Log log =
LogFactory.getLog("org.apache.struts.webapp.Example");
public TestAction() {
}
//函数定义:
public ActionForward
execute(ActionMapping mapping,
ActionForm
form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
// Extract attributes and
parameters we will need
Locale locale =
getLocale(request);
MessageResources messages =
getResources(request);
HttpSession session =
request.getSession();
TestForm m_TestForm = (TestForm)
form;
TestDAO m_TestDAO =
TestDAO.getInstance(); //定义Hibernate__DAO对象,用于实现数据库的各种操作
String
action=request.getParameter("action"); //动作类型
String
search=request.getParameter("search"); //数据库查找方式
String
expression=request.getParameter("expression"); //参数,这里用于保存记录(行)的ID数据
if(action==null)action="find";
if(search==null)search="UNsearch";
if(expression==null)expression="";
expression=toChinese(expression); //处理中文问题,实现编码转换
/////////
if("delete".equals(action)) //删除记录操作
{
Test m_Test= new
Test();
//<delete>
m_Test.setUserID(java.lang.Integer.valueOf(expression));
//</delete>
m_TestDAO.removeID(m_Test);
}
////////////
if("update".equals(action)||"insert".equals(action)) //更新、添加记录操作
{
Test m_Test= new
Test();
//<update>
m_Test.setUserID(m_TestForm.getUserID());
m_Test.setUsername(m_TestForm.getUsername());
m_Test.setPassword(m_TestForm.getPassword());
m_Test.setRole(m_TestForm.getRole());
//</update>
if("update".equals(action)) //调用DAO对象更新记录
m_TestDAO.update(m_Test,expression);
if("insert".equals(action)) //调用DAO对象添加记录
m_TestDAO.create(m_Test);
}
///////////////HQL_查找数据库
String sql="from
emptyprj.Test Test";
////SQL字符处理,主要是加入查询条件,如果是全部显示,可把这部分代码删除。
if("search".equals(search))
{
String selectsql;
//<search>
sql+=" where ";
sql+="userID";
sql+="=";
if("NULL".equals(expression)||"".equals(expression))
{
sql+=m_TestForm .getUserID();
}
else
{
sql+=expression;
}
sql+="";
//</search>
}
//<分页>
m_TestDAO.setLength(4);//设置每页显示记录数
int ipage;//当前页
try
{
String
page=request.getParameter("page");//分页参数,读取请求的当前页
ipage=java.lang.Integer.parseInt(page,10);
}
catch (Exception e)
{
ipage=m_TestForm.getPage();
}
if(ipage<1)ipage=1;
Collection col =
m_TestDAO.findSQL("select Test "+sql,"select count(Test) "+sql,ipage);//通过DAO对象查询数据
request.setAttribute("Test",col); //保存数据
String
pagestr=m_TestDAO.getPagestr(ipage);//分页字符串,分页内容
if(!"search".equals(search)) //查找和全部显示两个不同的操作,其分页字符串不同,在此进行处理。如果是全部显示则去掉"search=search&"
{
pagestr=pagestr.replaceAll("search=search&","");
}
m_TestForm.setPagestr(pagestr);
m_TestForm.setAction(action);
request.setAttribute("TestForm",m_TestForm);
//</分页>
return
mapping.findForward("success");
}
public String toChinese(String ss) {
//处理中文问题,实现编码转换
if (ss != null) {
try {
String temp_p = ss;
byte[] temp_t =
temp_p.getBytes("ISO8859-1");
ss = new String(temp_t);
}
catch (Exception e) {
System.err.println("toChinese
exception:" + e.getMessage());
System.err.println("The String
is:" + ss);
}
}
return ss;
}
}
web.xml文件:
这里除了普通的Struts项目的配置之外,还包括数据库连接池的配置,见暗体字部分的代码。
<?xml version="1.0"
encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD
Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<!-- Standard Action Servlet
Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>Set Character
Encoding</filter-name>
<filter-class>javawebstudio.struts_db.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character
Encoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<!-- Standard Action Servlet Mapping
-->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts Tag Library Descriptors
-->
<taglib>
<taglib-uri>/bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/template</taglib-uri>
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
</web-app>
struts-config.xml文件:
<?xml version="1.0"
encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software
Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="TestForm"
type="emptyprj.TestForm"
/>
</form-beans>
<action-mappings>
<action path="/TestAction"
type="emptyprj.TestAction"
name="TestForm"
scope="request"
input="/Test.jsp">
<forward name="success" path="/TestOut.jsp"
/></action>
</action-mappings>
<!-- ========== Message Resources
Definitions =========================== -->
<message-resources parameter="ApplicationResources_ch.properties"/>
<message-resources parameter="AlternateApplicationResources"
key="alternate">
</message-resources>
</struts-config>