分类: Java
2008-05-07 14:27:04
只有Struts2基础(初学Hibernate/Spring第三天就想着整合),有些地方不是很懂,看了网上大部分的例子、blog,百分百的MyEclipse插件
仅仅看了两天的官方文档就写了这个整合的新闻发布系统,感觉蛮好的,是个好的开始 come on!
以下是一个新闻发布系统的登录模块:(两天看文档,一夜写成的,不是很完善,仅仅实现基本的增删查改功能,主要是整合练习)
首先配置三个框架,有人说要是使用MyEclipse自动生成会有顺序Spring->Hibernate->Struts,太依赖工具不是本人的习惯,这些是后话。
开发工具Eclipse J2EE Developer Tomcat6.0.13 Mysql 6.0
新建Dynamic Web Project
拷贝工程所需的jar包到WEB-INF/lib下
数据库创建脚本
DROPTABLE context; CREATETABLE context ( id VARCHAR(32) NOTNULLPRIMARYKEY, title VARCHAR(100), times DATETIME, content VARCHAR(500), author VARCHAR(50), click INT, typeVARCHAR(50) ); DROPTABLEuser; CREATETABLEuser ( uid VARCHAR(50) NOTNULLPRIMARYKEY, uname VARCHAR(50), password VARCHAR(50) NOTNULL ); |
在web.xml中配置Struts2和Spring
<filter> <filter-name>Struts2filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher filter-class> filter> <filter> <filter-name>encodingFilterfilter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter filter-class> <init-param> <param-name>encodingFilterparam-name> <param-value>UTF-8param-value> init-param> filter> <filter-mapping> <filter-name>Struts2filter-name> <url-pattern>/*url-pattern> filter-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener listener-class> listener> |
项目中我使用的是Tomcat数据源配置如下,如果你不使用Tomcat数据源也可以在下面的配置文件中配置:
<Context docBase="news-SSH2" path="/news-SSH2" reloadable="true" source="org.eclipse.jst.jee.server:news-SSH2"> <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/news" password="1234" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/news?autoReconnect=true" username="root"/> Context> |
也在在配置applicationContext.xml文件中配置数据源
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/news"/>
<property name="user" value="root"/>
<property name="password" value="1234"/>
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="1"/>
<property name="initialPoolSize" value="1"/>
<property name="maxIdleTime" value="20"/> bean> |
在applicationContext.xml中配置sessionFactory
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/news">property> bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource">property> <property name="mappingResources"> <list> <value>org/bulktree/ssh2/news/vo/User.hbm.xmlvalue> <value>org/bulktree/ssh2/news/vo/News.hbm.xmlvalue> list> property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect value> property> bean> |
3. 开始编码:
我们必须明确Spring框架的体系结构,新建以下几个包
User.java
package org.bulktree.ssh2.news.vo; publicclass User { private String uid; private String uname; private String password; public String getUid() { returnuid; } Getter/setter’’’’’’’’’’’ publicvoid setPassword(String password) { this.password = password; } } |
在User类同包下即org.bulktree.ssh2.news.vo新建User.hbm.xml文件
xml version="1.0"?> DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" ""> <hibernate-mapping package="org.bulktree.ssh2.news.vo"> <class name="User" table="user"> <id column="uid" name="uid" type="string"> <generator class="assigned"/> id> <property column="uname" name="uname" type="string"/> <property column="password" name="password" type="string"/> class> hibernate-mapping> |
新建UserDao.java接口
package org.bulktree.ssh2.news.dao; import java.util.List; import org.bulktree.ssh2.news.vo.User; publicinterface UserDao { /** *增加一个用户 *@throwsException */ publicvoid addUser(User user) throws Exception; /** *根据uid/password查询User *@paramuid *@parampassword *@return *@throwsException */ public User queryByUidAndPassword(String uid, String password) throws Exception; /** *删除用户 *@paramuid *@throwsException */ publicvoid delete(String uid) throws Exception; /** *查询全部用户 *@returnList *@throwsException */ public List } |
UserDaoImpl.java接口实现类
package org.bulktree.ssh2.news.dao.impl; import java.util.List; import org.bulktree.ssh2.news.dao.UserDao; import org.bulktree.ssh2.news.vo.User; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * 继承HibernateDaoSuppor类实现getHibernateTemplate() * * @author bulktree * */ public class UserDaoImpl extends HibernateDaoSupport implements UserDao { @Override public void addUser(User user) throws Exception { this.getHibernateTemplate().save(user); } @Override public void delete(String uid) throws Exception { // TODO Auto-generated method stub } @Override public List // TODO Auto-generated method stub return null; } @Override public User queryByUidAndPassword(String uid, String password) throws Exception { String hql = "FROM User as u WHERE u.uid=? and u.password=?"; String[] str = new String[] { uid, password }; List if (users != null && users.size() >= 1) { return users.get(0); } else { return null; } } } |
Service层,新建一UserService.java接口
package org.bulktree.ssh2.news.service; publicinterface UserService { /** *添加一个用户 *@paramuid *@paramuname *@parampassword *@return新增用户的uid *@throwsException */ public String addUser(String uid, String uname, String password) throws Exception; /** *验证登录 *@paramuid *@parampassword *@returnuid *@throwsException */ public String isLogin(String uid, String password) throws Exception; } |
接口实现类
package org.bulktree.ssh2.news.service.impl; import org.bulktree.ssh2.news.dao.UserDao; import org.bulktree.ssh2.news.service.UserService; import org.bulktree.ssh2.news.vo.User; /** * UserService实现类 * * @author bulktree * */ public class UserServiceImpl implements UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public String addUser(String uid, String uname, String password) throws Exception { User user = new User(); user.setUid(uid); user.setUname(uname); user.setPassword(password); userDao.addUser(user); return user.getUid(); } @Override public String isLogin(String uid, String password) throws Exception { User user = userDao.queryByUidAndPassword(uid, password); if(user != null) { return user.getUname(); } else { return null; } } } |
最后我们新建一Action,LoginAction.java
package org.bulktree.ssh2.news.action; import java.util.Map; import org.bulktree.ssh2.news.service.UserService; import org.bulktree.ssh2.news.vo.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; /** * 登录Action * @author bulktree * */ public class LoginAction extends ActionSupport { private User user; private UserService userService; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } @Override public String execute() throws Exception { if (isInvalid(user.getUid())) { this.addFieldError("uid", "登录ID不能为空"); return INPUT; } if (isInvalid(user.getPassword())) { this.addFieldError("password", "密码项不能为空"); return INPUT; }
String uname = userService.isLogin(user.getUid(), user.getPassword()); if (uname != null) { Map session = ActionContext.getContext().getSession(); session.put("uname", uname); session.put("uid", user.getUid()); return SUCCESS; } else { this.addFieldError("idorpassword", "登录ID或密码错误"); return INPUT; } } private boolean isInvalid(String value) { return (value == null || value.length() == 0); } } |
下来就是login.jsp页面文件了
<center> <div style="color: red"><s:fielderror /><s:actionmessage />div> <s:form action="login" method="post"> <s:textfield name="user.uid" label="UID" tooltip="ENTER YOUR UID" /> <s:password name="user.password" label="PASSWORD" tooltip="ENTER YOUR PASSWORD" /> <s:submit>s:submit>
s:form> <s:a href="regist.jsp">REGIST NEW COUNTs:a>center> |
下来就是applicationContext.xml文件的配置
<bean id="userdao" class="org.bulktree.ssh2.news.dao.impl.UserDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> property> bean>
<bean id="newsdao" class="org.bulktree.ssh2.news.dao.impl.NewsDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> property> bean> <bean id="loginAction" class="org.bulktree.ssh2.news.action.LoginAction"> <property name="userService"> <ref bean="userservice"/> property> bean>
bean> |
·bean的id属性就是对应类class的实例
·property元素的name属性为bean的class属性对应类的属性名,
·ref为引用bean,引用的是bean的id
Struts.xml文件完整配置
xml version="1.0" encoding="UTF-8" ?> DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" ""> <struts> <constant name="struts.i18n.encoding" value="UTF-8" /> <package name="SSH2" extends="struts-default"> <action name="login" class="loginAction"> <result>/addNews.jspresult> <result name="input">/login.jspresult> action>
<action name="regist" class="registAction"> <result>/login.jspresult> <result name="input">/regist.jspresult> action>
<action name="listall" class="listallAction"> <result>/newsList.jspresult> <result name="input">/addNews.jspresult> action>
<action name="notice" class="noticeAction"> <result type="redirect-action">listallresult> <result name="input">/addNews.jspresult> action> package>
struts> |
·form表单的action对应struts.xml文件中的action的name属性,由于Strust由Spring管理,struts.xml文件中的action元素class属性对应的是applicationContext.xml文件中bean元素id属性
最后贴上完整的applicationContext.xml文件
xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xsi:schemaLocation=" /spring-beans-2.0.xsd">
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/news">property> bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource">property> <property name="mappingResources"> <list> <value>org/bulktree/ssh2/news/vo/User.hbm.xmlvalue> <value>org/bulktree/ssh2/news/vo/News.hbm.xmlvalue> list> property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect value> property> bean>
<bean id="userdao" class="org.bulktree.ssh2.news.dao.impl.UserDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> property> bean>
<bean id="newsdao" class="org.bulktree.ssh2.news.dao.impl.NewsDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> property> bean> <bean id="userservice" class="org.bulktree.ssh2.news.service.impl.UserServiceImpl"> <property name="userDao"> <ref bean="userdao"/> property> bean>
<bean id="newservice" class="org.bulktree.ssh2.news.service.impl.NewsServiceImpl"> <property name="newsDao"> <ref bean="newsdao"/> property> bean>
<bean id="loginAction" class="org.bulktree.ssh2.news.action.LoginAction"> <property name="userService"> <ref bean="userservice"/> property> bean>
<bean id="registAction" class="org.bulktree.ssh2.news.action.RegistAction"> <property name="userService"> <ref bean="userservice"/> property> bean> <bean id="noticeAction" class="org.bulktree.ssh2.news.action.NoticeNewsAction"> <property name="newsService"> <ref bean="newservice"/> property> bean>
<bean id="listallAction" class="org.bulktree.ssh2.news.action.QueryAllNews"> <property name="newsDao"> <ref bean="newsdao"/> property> bean> beans> |
·applicationContext.xml文件默认加载路径classpath下,也就是WEB-INF下
·整个工程没有用到hibernate.cfg.xml文件,Spring管理了hibernate,这个文件不起什么作用了,但是最好还是加上
xml version="1.0" encoding="UTF-8"?> DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" ""> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty> <mapping class="com.bulktree.ssh2.vo.User" package="com.bulktree.ssh2.vo" resource="com/bulktree/ssh2/vo/User.hbm.xml"/> session-factory> hibernate-configuration> |