最近几天,自己在研究Struts、Hibernate和Ajax的整合,对于Hibernate和Ajax对我来说还是比较新鲜的技术,也颇有兴趣,在这里把步骤简单整理一下:
环境:
JDK 1.5
Eclipse 3.2
MyEclipse 5.0 M1
Tomcat 5.5.23
MySQL 5.0.19
1. 在MySQL中建表:
Create Database users;
USE users;
Create table user (
userID int not null auto_increment,
userName varchar(20) not null unique,
password varchar(20) not null,
lastLogon timestamp,
primary key(userID)
);
2. 打开Eclipse,新建一个Web Project:
鉴于要完成的是Struts+Hibernate+Ajax,把项目名取为:sha
其他的什么都不用改。“完成”
2. 配置MyEclipse Database Explorer
Eclipse界面-窗口-打开透视图-MyEclipse Database Explorer-New:
测试,出现:
连接后出现上图,完成。
3. 为项目添加Struts和Hibernate。
3.1 右键项目,MyEclipse,Add Struts...
把默认的company改成sha后,完成。(不改也行)
3.2 右键项目,MyEclipse,Add Hibernate...
默认不作修改,下一步,下一步,选择DB profile:
下一步:
SessionFactory Class:com.sha.HibernateSessionFactory,完成。
3. 生成数据库-XML映射:
打开MyEclipse Database Explorer,选择表user,右键,Hibernate Reverse...选择默认的com后,完成。
4. 创建Action,Form,JSP。
打开struts-config.xml,右键新建"Form Action and JSP":
下一步,在Forwards里面添加:Name:success;Path:/jsp/success.jsp
完成:
在jsp文件夹下,新建success.jsp文件。内容任意。
添加新的资源文件:
1<message-resources parameter="com.sha.struts.ApplicationResources_Err" key="error"/>
5. 在/src/com/sha下创建UserDAOFactory.java
1package com.sha;
2
3import org.hibernate.HibernateException;
4import org.hibernate.Session;
5import org.hibernate.Transaction;
6
7import com.sha.HibernateSessionFactory;
8import com.User;
9
10public class UserDAOFactory {
11 Session session;
12 Transaction tx;
13 public void add(User user) throws HibernateException {
14
15 try {
16 session = HibernateSessionFactory.currentSession();
17 tx = session.beginTransaction();
18 //Add a new user
19 session.save(user);
20 tx.commit ();
21 }catch(HibernateException e){
22 throw e;
23 }finally{
24 if (tx!=null) {
25 tx.rollback();
26 }
27 HibernateSessionFactory.closeSession();
28 }
29 }
30}
31
32
6. 修改addUserAction.java:
1/**//*
2 * Generated by MyEclipse Struts
3 * Template path: templates/java/JavaClass.vtl
4 */
5package com.sha.struts.action;
6
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9import org.apache.struts.action.Action;
10import org.apache.struts.action.ActionForm;
11import org.apache.struts.action.ActionForward;
12import org.apache.struts.action.ActionMapping;
13
14import com.User;
15import com.sha.UserDAOFactory;
16import com.sha.struts.form.AddUserForm;
17
18/** *//**
19 * MyEclipse Struts
20 * Creation date: 05-21-2008
21 *
22 * XDoclet definition:
23 * @struts.action path="/addUser" name="addUserForm" input="/form/addUser.jsp" scope="request" validate="true"
24 * @struts.action-forward name="success" path="/jsp/success.jsp"
25 */
26public class AddUserAction extends Action {
27 /**//*
28 * Generated Methods
29 */
30
31 /** *//**
32 * Method execute
33 * @param mapping
34 * @param form
35 * @param request
36 * @param response
37 * @return ActionForward
38 */
39 public ActionForward execute(ActionMapping mapping, ActionForm form,
40 HttpServletRequest request, HttpServletResponse response) {
41 AddUserForm addUserForm = (AddUserForm) form;// TODO Auto-generated method stub
42 User user = new User();
43 user.setUserName(addUserForm.getUserName ());
44 user.setPassword(addUserForm.getPassword ());
45 UserDAOFactory userDAO = new UserDAOFactory ();
46 userDAO.add(user);
47
48 return mapping.findForward("success");
49 }
50}
7. 修改addUserForm.java:
1 public ActionErrors validate(ActionMapping mapping,
2 HttpServletRequest request) {
3 ActionErrors errors = new ActionErrors();
4
5 if(userName == "" || userName.length() < 1)
6 errors.add("usernameErr",new ActionError("err.username.null"));
7
8 if(password == "" || password.length() < 1)
9 errors.add("userpasswordErr",new ActionError("err.password.null"));
10
11 Session session = HibernateSessionFactory.currentSession();
12 Transaction tx = session.beginTransaction ();
13 Query query = session.createQuery("SELECT user FROM User AS user WHERE user.userName = '" + this.userName + "'");
14 Iterator it = query.iterate ();
15 if (it.hasNext()){
16 errors.add ("usernameErr",new ActionError("err.username.exist"));
17 }
18 tx.commit();
19 HibernateSessionFactory.closeSession ();
20 return errors;
21 }
22
23public void reset(ActionMapping mapping, HttpServletRequest request) {
24 this.userName = null;
25 this.password = null;
26 }
导入相应的包。
8. 修改资源文件:
修改ApplicationResources.properties,内容:
test.button.reset=reset
test.button.submit=submit
test.passsord=password\:
test.username=userName\:
新建ApplicationResources_Err.properties,内容:
err.password.null=The password is Null\!
err.username.exist=The userName is exist\!
err.username.null=The username is Null\!
9. 修改addUser.jsp:
1<%@ page language="java"%>
2<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
3<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
4
5<html>
6 <head>
7 <title>add User</title>
10 </head>
11 <body>
12 <html:form action="/addUser.do">
13 <table border="1" align="center">
14 <tr>
15 <td>
16 <bean:message key="test.username"/>
17 </td>
18 <td>
19 <html:text property="userName" onblur="retrieveURL('/sha/checkName.do?userName=' + this.value);"/>
20 <font color = "RED">
21 <span id = "nField"></span>
22 <html:errors property="usernameErr" bundle = "error"/>
23 </font>
24 </td>
25 </tr>
26 <tr>
27 <td>
28 <bean:message key="test.passsord"/>
29 </td>
30 <td>
31 <html:password property="password"/>
32 <font color = "RED">
33 <html:errors property="userpasswordErr" bundle = "error"/>
34 </font>
35 </td>
36 </tr>
37 <tr>
38 <td colspan="2" align = "center">
39 <html:submit>
40 <bean:message key = "test.button.submit"/>
41 </html:submit>
42 <html:reset/>
43 </td>
44 </tr>
45 </table>
46 </html:form>
47 </body>
48</html>
49
50
10. 项目-右键MyEclipse-Add and Remove...
Tomcat 中需要指定JDK的路径。
目前为止,完成了Struts和Hibernate的配置。接下来:
11. 在WebRoot下,新建/js/ajax.js,内容:
1 var req;
2 var which;
3
4 function retrieveURL(url) {
5 if (window.XMLHttpRequest) { // Non-IE browsers
6 req = new XMLHttpRequest();
7 req.onreadystatechange = processStateChange;
8 try {
9 req.open("GET", url, true);
10 } catch (e) {
11 alert(e);
12 }
13 req.send(null);
14 } else if (window.ActiveXObject) { // IE
15 req = new ActiveXObject("Microsoft.XMLHTTP");
16 if (req) {
17 req.onreadystatechange = processStateChange;
18 req.open("GET", url, true);
19 req.send();
20 }
21 }
22 }
23
24 function processStateChange() {
25 if (req.readyState == 4) { // Complete
26 if (req.status == 200) { // OK response
27 document.getElementById("nField").innerHTML = req.responseText;
28 } else {
29 alert("Problem: " + req.statusText);
30 }
31 }
32 }
12. 修改/jsp/addUser.jsp,在Head中添加:
1<SCRIPT LANGUAGE="JavaScript" src="../js/ajax.js"> </SCRIPT>
13. 在action目录下添加CheckNameAction.java:
1package com.sha.struts.action;
2
3import java.io.IOException;
4import java.io.PrintWriter;
5import java.util.Iterator;
6
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9import org.apache.struts.action.Action;
10import org.apache.struts.action.ActionForm;
11import org.apache.struts.action.ActionForward;
12import org.apache.struts.action.ActionMapping;
13import org.hibernate.Query;
14import org.hibernate.Session;
15import org.hibernate.Transaction;
16
17import com.sha.HibernateSessionFactory;
18
19public class CheckNameAction extends Action {
20
21 public ActionForward execute(ActionMapping mapping, ActionForm form,
22 HttpServletRequest request, HttpServletResponse response) {
23
24 String userName = request.getParameter("userName");
25
26 Session session = HibernateSessionFactory.currentSession();
27 Transaction tx = session.beginTransaction ();
28 Query query = session.createQuery("SELECT user FROM User AS user WHERE user.userName = '" + userName + "'");
29 Iterator it = query.iterate ();
30 String msg = "";
31 if (it.hasNext()){
32 msg = "This username has been used!";
33 }
34 tx.commit();
35 HibernateSessionFactory.closeSession ();
36
37 response.setContentType("text/html");
38 PrintWriter out = null;
39 try {
40 out = response.getWriter();
41 } catch (IOException e) {
42 e.printStackTrace();
43 }
44 out.println(msg);
45 out.flush();
46 return null;
47 }
48}
14. 修改 struts-config.xml,在action-mapping里面添加:
1 <action
2 path="/checkName"
3 type="com.sha.struts.action.CheckNameAction"
4 parameter="/jsp/addUser.jsp"/>
至此,简单的Strust + Hibernate + Ajax 应用例子已经完成了。
打开浏览器,输入:
http://localhost:8080/sha/jsp/addUser.jsp进行访问。
小弟初学,欢迎大家提出宝贵意见及建议。
posted on 2008-05-21 21:48
胡昆栄 阅读(2192)
评论(1) 编辑 收藏 所属分类:
Java 、
JavaScript 、
Eclipse 、
Struts 、
Ajax 、
MySQL 、
Hibernate