1、 数据库设计 user 在user.hbm.xml里table="user" 一定要加上中括弧,table="[user]" 不然提示关键字错误
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[user]
GO
CREATE TABLE [dbo].[user] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[username] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[password] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[email] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
2、myEclipse中依次添加struts、spring、hibernate插件
文件夹目录:src下,com.wzj.struts.vo // com.wzj.struts.form // com.wzj.struts.action // com.wzj.struts.service //
com.wzj.struts.dao
webRoot下,index.jsp // success.jsp // web-inf/applicationContext.xml
3、按照次序列出所有的源文件及代码
(1)User.hbm.xml (com.wzj.struts.vo目录下)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.wzj.struts.vo.User" table="[user]" schema="dbo" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="10" not-null="true" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="10" not-null="true" />
</property>
<property name="email" type="java.lang.String">
<column name="email" length="50" not-null="true" />
</property>
</class>
</hibernate-mapping>
(2)User.java (com.wzj.struts.vo目录下)
package com.wzj.struts.vo;
/**
* User generated by MyEclipse - Hibernate Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
private String email;
// Constructors
/** default constructor */
public User() {
}
/** full constructor */
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
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 getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
(3)UserService.java (com.wzj.struts.service目录下)
package com.wzj.struts.service;
import com.wzj.struts.dao.UserDAO;
import com.wzj.struts.vo.User;
public class UserService {
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public User regist(User user){
userDAO.save(user);
return user;
}
}
(4)UserForm (com.wzj.struts.form目录下)
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.wzj.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;
/**
* MyEclipse Struts
* Creation date: 08-07-2007
*
* XDoclet definition:
* @struts.form name="userForm"
*/
public class UserForm extends ValidatorForm {
/*
* Generated fields
*/
/** password property */
private String password;
/** password2 property */
private String password2;
/** username property */
private String username;
/** email property */
private String email;
/** langxin property */
private String langsin;
/*
* Generated Methods
*/
/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
/**
* Returns the password.
* @return String
*/
public String getPassword() {
return password;
}
/**
* Set the password.
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Returns the password2.
* @return String
*/
public String getPassword2() {
return password2;
}
/**
* Set the password2.
* @param password2 The password2 to set
*/
public void setPassword2(String password2) {
this.password2 = password2;
}
/**
* Returns the username.
* @return String
*/
public String getUsername() {
return username;
}
/**
* Set the username.
* @param username The username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Returns the email.
* @return String
*/
public String getEmail() {
return email;
}
/**
* Set the email.
* @param email The email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Returns the langxin.
* @return String
*/
public String getLangsin() {
return langsin;
}
/**
* Set the langxin.
* @param langxin The langxin to set
*/
public void setLangsin(String langsin) {
this.langsin = langsin;
}
}
(5) UserDAO.java (com.wzj.struts.dao目录下)
package com.wzj.struts.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.wzj.struts.vo.User;
/**
* Data access object (DAO) for domain model class User.
* @see com.wzj.struts.vo.User
* @author MyEclipse - Hibernate Tools
*/
public class UserDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UserDAO.class);
//property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
protected void initDao() {
//do nothing
}
public void save(User transientInstance) {
log.debug("saving User instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById( java.lang.String id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) getHibernateTemplate()
.get("com.wzj.struts.vo.User", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(User instance) {
log.debug("finding User instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
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 List findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from User as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByUsername(Object username) {
return findByProperty(USERNAME, username);
}
public List findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}
public List findByEmail(Object email) {
return findByProperty(EMAIL, email);
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) getHibernateTemplate()
.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
}
}
(6)UserAction (com.wzj.struts.action目录下)
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.wzj.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.wzj.struts.form.UserForm;
import com.wzj.struts.service.UserService;
import com.wzj.struts.vo.User;
/**
* MyEclipse Struts
* Creation date: 08-07-2007
*
* XDoclet definition:
* @struts.action path="/user" name="userForm" input="/index.jsp" scope="request" validate="true"
*/
public class UserAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UserForm userForm = (UserForm) form;// TODO Auto-generated method stub
User user = new User();
user.setUsername(userForm.getUsername());
user.setPassword(userForm.getPassword());
user.setEmail(userForm.getEmail());
System.out.println("user == "+ user.getUsername());
userService.regist(user);
return mapping.findForward("success");
}
}
(7) applicationContext.xml配置文件 (web-inf目录下)
<?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.microsoft.jdbc.sqlserver.SQLServerDriver</value>
</property>
<property name="url">
<value>jdbc:microsoft:sqlserver://crf-wzj:1433</value>
</property>
<property name="username">
<value>sa</value>
</property>
<property name="password">
<value>sa</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.SQLServerDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/wzj/struts/vo/User.hbm.xml</value>
</list>
</property></bean>
<bean id="userDAO" class="com.wzj.struts.dao.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean name="/user" class="com.wzj.struts.action.UserAction"
abstract="false" singleton="false" lazy-init="default"
autowire="default" dependency-check="default">
<property name="userService">
<ref local="userService" />
</property>
</bean>
<bean id="userService" class="com.wzj.struts.service.UserService"
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
<property name="userDAO">
<ref local="userDAO" />
</property>
</bean>
<bean id="UserDAO" class="com.wzj.struts.dao.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean></beans>
(8)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>
<data-sources />
<form-beans >
<form-bean name="userForm" type="com.wzj.struts.form.UserForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="userForm"
input="/index.jsp"
name="userForm"
path="/user"
scope="request"
>
<forward name="failure" path="/index.jsp" />
<forward name="success" path="/success.jsp" />
</action>
</action-mappings>
<!--controller的作用: 可以在action里不用写type属性了 -->
<controller>
<set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor" />
</controller>
<message-resources parameter="com.wzj.struts.ApplicationResources" />
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" />
</plug-in>
</struts-config>
(9)页面index.jsp
<%@ page language="java"%>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for UserForm form</title>
</head>
<body>
<html:form action="/user">
password : <html:password property="password"/><html:errors property="password"/><br/>
password2 : <html:password property="password2"/><html:errors property="password2"/><br/>
username : <html:text property="username"/><html:errors property="username"/><br/>
email : <html:text property="email"/><html:errors property="email"/><br/>
langsin : <html:text property="langsin"/><html:errors property="langsin"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
(10)success.jsp
<%@ page language="java"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for UserForm form</title>
</head>
<body>
welcome,<bean:write name="userForm" property="username"/>
</body>
</html>