bulktree
欢迎走进有风的地方~
posts - 32,  comments - 75,  trackbacks - 0

Spring2.5.3+Hibernate3.2+Struts2.0.11整合

 

 

只有Struts2基础(初学Hibernate/Spring第三天就想着整合),有些地方不是很懂,看了网上大部分的例子、blog,百分百的MyEclipse插件,本人不太习惯使用MyEclipse,主要是Eclipse使用的时间比较长,使用MyEclipse6.0.1时(第一次用)比如你要输入.getHibernateTemplate()时,输入点时就有提示,但是当我输入点后面的字母出错时,只能返回到输入点之前才按点“.”可以提示,按ALT+/也不会出现,是不是我不知道快捷键,或是其它的方式,总之我在Eclipse中输入一半错误时按ALT+/可以又出来提示,虽然不是特依赖提示功能,但是用起来还是不爽,毕竟每天都在使用它,哪位要是知道的话烦请告诉一声bulktree@126.com

仅仅看了两天的官方文档就写了这个整合的新闻发布系统,感觉蛮好的,是个好的开始 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中配置Struts2Spring

<filter>

       <filter-name>Struts2</filter-name>

       <filter-class>

           org.apache.struts2.dispatcher.FilterDispatcher

       </filter-class>

    </filter>

    <filter>

       <filter-name>encodingFilter</filter-name>

       <filter-class>

           org.springframework.web.filter.CharacterEncodingFilter

       </filter-class>

       <init-param>

           <param-name>encodingFilter</param-name>

           <param-value>UTF-8</param-value>

       </init-param>

    </filter>

    <filter-mapping>

       <filter-name>Struts2</filter-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,使用C3P0数据源实现 -->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">

       <!-- 指定连接数据库的驱动 -->

       <property name="driverClass" value="com.mysql.jdbc.Driver"/>

       <!-- 指定连接数据库的URL -->

       <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>

    <!-- 管理Hibernate -->

    <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.xml</value>

              <value>org/bulktree/ssh2/news/vo/News.hbm.xml</value>

           </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"

                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<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<User> queryAll() throws Exception;

}



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<User> queryAll() throws Exception {

       // 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<User> users = this.getHibernateTemplate().find(hql, str);

       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;

       }

    }

}

最后我们新建一ActionLoginAction.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