一,数据表(因为是一个小例子,所以只有一个表,毕竟这不是一个讲怎么配置hibernate级联的例子。)
CREATE TABLE `members` (
`id` int(7) NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`password` varchar(20) default NULL,
`sex` varchar(10) default NULL,
`mail` varchar(50) default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
二,hibernate持久化类及映射文件、数据库操作封装DAO
package com.yang.product.booksonline.dao;
/**
* Members
*/
public class Members implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private String password;
private String sex;
private String mail;
// Constructors
/** default constructor */
public Members() {
}
/** minimal constructor */
public Members(String name) {
this.name = name;
}
/** full constructor */
public Members(String name, String password, String sex, String mail) {
this.name = name;
this.password = password;
this.sex = sex;
this.mail = mail;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
<?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>
<class name="com.yang.product.booksonline.dao.Members" table="members" catalog="books">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="name" length="20" not-null="true" unique="true" />
</property>
<property name="password" type="string">
<column name="password" length="20" />
</property>
<property name="sex" type="string">
<column name="sex" length="10" />
</property>
<property name="mail" type="string">
<column name="mail" length="50" />
</property>
</class>
</hibernate-mapping>
package com.yang.product.booksonline.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.Example;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* Data access object (DAO) for domain model class Members.
* @see com.yang.product.booksonline.dao.Members
* @author lanxincao
*/
public class MembersDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(MembersDAO.class);
protected void initDao() {
//do nothing
}
public void save(Members transientInstance) {
log.debug("saving Members instance");
try {
getHibernateTemplate().saveOrUpdate(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Members persistentInstance) {
log.debug("deleting Members instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Members findById( java.lang.Integer id) {
log.debug("getting Members instance with id: " + id);
try {
Members instance = (Members) getHibernateTemplate()
.get("com.yang.product.booksonline.dao.Members", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Members instance) {
log.debug("finding Members instance by example");
try {
List results = getSession()
.createCriteria("com.yang.product.booksonline.dao.Members")
.add(Example.create(instance))
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public Members merge(Members detachedInstance) {
log.debug("merging Members instance");
try {
Members result = (Members) getHibernateTemplate()
.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Members instance) {
log.debug("attaching dirty Members instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Members instance) {
log.debug("attaching clean Members instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public List findByMembersName(String name){
log.debug("finding by members' name.");
try {
return getHibernateTemplate().find("from Members as members where members.name = ?"
,new String[]{name});
} catch (RuntimeException re) {
log.error("finding by members' name failed",re);
throw re;
}
}
public static MembersDAO getFromApplicationContext(ApplicationContext ctx) {
return (MembersDAO) ctx.getBean("MembersDAO");
}
}
三,spring配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/books</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>snrdcqmq</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/yang/product/booksonline/dao/Members.hbm.xml</value>
</list>
</property>
</bean>
<bean id="MembersDAO" class="com.yang.product.booksonline.dao.MembersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean name="/members" class="com.yang.product.booksonline.action.MembersAction">
<property name="membersDAO">
<ref bean="MembersDAO"/>
</property>
</bean>
</beans>
四,struts配置及action类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="membersForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="sex" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
<form-property name="mail" type="java.lang.String" />
<form-property name="name" type="java.lang.String" />
</form-bean>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="membersForm"
name="membersForm"
parameter="action"
path="/members"
scope="request"
type="org.springframework.web.struts.DelegatingActionProxy" >
<forward name="loginSuccess" path="/index.jsp" />
<forward name="registerSuccess" path="/index.jsp" />
<forward name="logoutSuccess" path="/index.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.yang.product.booksonline.ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
<set-property property="stopOnFirstError" value="true" />
</plug-in>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/springContext.xml" />
</plug-in>
</struts-config>
package com.yang.product.booksonline.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import com.yang.product.booksonline.dao.Members;
import com.yang.product.booksonline.dao.MembersDAO;
/**
* XDoclet definition:
* @struts.action path="/members" name="membersForm" parameter="action" scope="request" validate="true"
*/
public class MembersAction extends DispatchAction {
private MembersDAO membersDAO;
public MembersDAO getMembersDAO() {
return membersDAO;
}
public void setMembersDAO(MembersDAO membersDAO) {
this.membersDAO = membersDAO;
}
public ActionForward login (ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
// String url = request.getParameter("url");
String name = (String)((DynaActionForm)form).get("name");
String password = (String)((DynaActionForm)form).get("password");
List members = membersDAO.findByMembersName(name);
if (members != null && members.size() >0) {
Members member = (Members)members.get(0);
if (password.equals(member.getPassword())) {
request.getSession().setAttribute("member",name);
//return new ActionForward(url);
return mapping.findForward("loginSuccess");
} else {
return null;
}
} else {
return null;
}
}
public ActionForward logout (ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
request.getSession().removeAttribute("member");
return mapping.findForward("logoutSuccess");
}
public ActionForward register (ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
String name = (String)((DynaActionForm)form).get("name");
String password = (String)((DynaActionForm)form).get("password");
String sex = (String)((DynaActionForm)form).get("sex");
String mail = (String)((DynaActionForm)form).get("mail");
List members = membersDAO.findByMembersName(name);
if (members != null && members.size() >0) {
return null;
} else {
Members member = new Members();
member.setName(name);
member.setPassword(password);
member.setSex(sex);
member.setMail(mail);
membersDAO.save(member);
return mapping.findForward("registerSuccess");
}
}
}
注意到,这里使用了dispatchaction。
五,三个jsp部分内容
index.jsp
<body>
<logic:notPresent name="member" scope="session">
Welcome,you have not <html:link href="login.jsp">login</html:link>. _fcksavedurl=""login.jsp">login</html:link>." <br>
</logic:notPresent>
<logic:present name="member" scope="session">
Welcome,<bean:write name="member" scope="session"/>.<html:link href="members.do?action=logout">Logout</html:link>
</logic:present>
</body>
login.jsp
<body>
If you haven't registered the system,please <html:link href="register.jsp">register</html:link>
<html:form action="/members.do?action=login" method="post" focus="name">
<table border="0">
<tr>
<td><bean:message key="members.form.name.label"/>:</td>
<td><html:text property="name" /></td>
</tr>
<tr>
<td><bean:message key="members.form.password.label"/>:</td>
<td><html:password property="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit><bean:message key="members.form.login.label"/></html:submit></td>
</tr>
</table>
</html:form>
</body>
register.jsp
<body>
Welcome to register the books online. <br>
<html:form action="/members.do?action=register" method="POST">
<bean:message key="members.form.name.label"/>:<html:text property="name"/><br>
<bean:message key="members.form.password.label"/>:<html:password property="password"/><br>
<bean:message key="members.form.sex.label"/>:
<html:select property="sex">
<html:option key="members.form.sex.male" value="male" />
<html:option key="members.form.sex.female" value="female" />
</html:select><br>
<bean:message key="members.form.mail.label"/>:<html:text property="mail"/><br>
<html:submit><bean:message key="members.form.register.label"/></html:submit>
</html:form>
</body>
注意:在开发过程中,本想加上输入验证的,因为前面己经有了这方面的例子,为了不重复,这里就有意去掉了这部分,但要运行这个例子,还是你自己加上validation.xml、validator-rules.xml两个文件,不然会出错。
转载于:https://www.cnblogs.com/newthing/archive/2007/01/17/2157932.html