SSH2整合案例

第一次整合SSH2,参考了很多资料,辛苦颇多,遂记下来与大家分享一个菜鸟的成长。

开发环境:eclipse (我个人很喜欢)

SSH2版本:struts-2.3.4.1,hibernate-distribution-3.6.0.Final,spring-framework-2.5.6

服务器:apache-tomcat-7.0.29

参考步骤:

1.新建测试数据库(我采用的是mysql)

1 create database demo;
2 use demo;
3 create table user (
4 id int primary key auto_increment,
5 username nvarchar(20),
6 password nvarchar(20),
7 email nvarchar(50)
8 );

2.新建动态网站工程

在eclipse里新建工程,看截图

这是整个目录结构,截图分为三个部分,有重复的地方,自己对好!

这里最难的就是那些个jar包,困扰了我无数次。看好需要哪些,还有版本问题!

3.代码

SaveUserAction.java

 

 1 package com.demo.lihua.action;
 2 
 3 import com.demo.lihua.model.User;
 4 import com.demo.lihua.service.UserService;
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 public class SaveUserAction extends ActionSupport{
 8     
 9     private User user;
10     private UserService userService;//通过Spring创建业务层对象  使用set方法依赖注入
11  
12     public UserService getUserService() {
13         return userService;
14     }
15 
16     public void setUserService(UserService userService) {
17         this.userService = userService;
18     }
19 
20     public User getUser() {
21         return user;
22     }
23 
24     public void setUser(User user) {
25         this.user = user;
26     }
27 
28     @Override
29 
30     public String execute() throws Exception {
31         System.out.println("username=" + user.getUsername());
32         this.userService.save(user);
33         return SUCCESS;
34     }
35 }

 

 ListUserAction.java

1 package com.demo.lihua.action;
2 
3 public class ListUserAction {
4 
5 }    

 这是一个空实现,我还没写,大家有兴趣可以自己写,我就实现了save。

UserDAO.java

 1 package com.demo.lihua.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.demo.lihua.model.User;
 6 
 7 public interface UserDAO {
 8     
 9     /**
10      * 保存用户
11      * @param user
12      */
13     public void saveUser(User user);
14 
15     /**
16      * 删除用户
17      * @param id
18      */
19     public void deleteUser(int id);
20 
21     /**
22      * 根据id找到某个用户
23      * @param id
24      */
25     public User findUserById(int id);
26 
27     /**
28      * 查询所有的用户
29      * @param user
30      * return List<User>
31      */
32     public List<User> findAllUsers();
33 
34     /**
35      * 更新用户
36      * @param user
37      */
38     public void updateUser(User user);
39 
40     
41 }

 数据访问层的接口,实现层在下面

UserDAOImpl.java

 

 1 package com.demo.lihua.daoImpl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 6 
 7 
 8 import com.demo.lihua.dao.UserDAO;
 9 import com.demo.lihua.model.User;
10 
11 public class UserDAOImpl extends HibernateDaoSupport implements UserDAO{
12     
13     private UserDAO userDao;
14     
15     public UserDAO getUserDao() {
16         return userDao;
17     }
18 
19     public void setUserDao(UserDAO userDao) {
20         this.userDao = userDao;
21     }
22 
23     @Override
24     public void saveUser(User user) {
25         this.getHibernateTemplate().save(user);
26         
27     }
28 
29     @Override
30     public void deleteUser(int id) {
31         User user = findUserById(id);
32         if(user != null){
33            this.getHibernateTemplate().delete(user);
34         }
35         
36     }
37 
38     @Override
39     public User findUserById(int id) {
40         return (User)this.getHibernateTemplate().get(User.class, id);
41     }
42 
43     @SuppressWarnings("unchecked")
44     @Override
45     public List<User> findAllUsers() {
46         String hql = "from User";
47         return (List<User>)this.getHibernateTemplate().find(hql);
48     }
49 
50     @Override
51     public void updateUser(User user) {
52         this.getHibernateTemplate().update(user);
53         
54     }
55     
56      
57 }

User.java

 

 1 package com.demo.lihua.model;
 2 
 3 public class User {
 4     int id;
 5     String username;
 6     String password;
 7     String email;
 8     public int getId() {
 9         return id;
10     }
11     public void setId(int id) {
12         this.id = id;
13     }
14     public String getUsername() {
15         return username;
16     }
17     public void setUsername(String username) {
18         this.username = username;
19     }
20     public String getPassword() {
21         return password;
22     }
23     public void setPassword(String password) {
24         this.password = password;
25     }
26     public String getEmail() {
27         return email;
28     }
29     public void setEmail(String email) {
30         this.email = email;
31     }
32     
33     
34     @Override
35     public boolean equals(Object arg0) {
36         // TODO Auto-generated method stub
37         return super.equals(arg0);
38     }
39     
40     @Override
41     public int hashCode() {
42         // TODO Auto-generated method stub
43         return super.hashCode();
44     }
45 }

 

 数据库映射类

User.hbm.xml

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping package="com.demo.lihua.model">
 6 
 7      <class name="User" table="user">
 8         <id name="id">
 9             <generator class="native"></generator>
10         </id>
11         <property name="username"/>
12         <property name="password"/>
13         <property name="email"/>
14     </class>
15 
16 </hibernate-mapping>

hibernate映射文件

UserService.java

 

1 package com.demo.lihua.service;
2 
3 import com.demo.lihua.model.User;
4 
5 public interface UserService {
6 
7     public void save(User user);
8 
9 }

业务逻辑的接口类

UserServiceImpl.java

 1 package com.demo.lihua.serviceImpl;
 2 
 3 import com.demo.lihua.dao.UserDAO;
 4 import com.demo.lihua.model.User;
 5 import com.demo.lihua.service.UserService;
 6 
 7 public class UserServiceImpl implements UserService{
 8     
 9     private UserDAO userDao;
10 
11     public UserDAO getUserDao() {
12         return userDao;
13     }
14 
15     public void setUserDao(UserDAO userDao) {
16         this.userDao = userDao;
17     }
18 
19     @Override
20     public void save(User user) {
21         userDao.saveUser(user);
22         
23     }   
24 }

 

 业务逻辑的实现类

log4j.properties

 1 # For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
 2 # For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
 3 log4j.rootLogger=INFO, stdout, logfile
 4 
 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 6 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 7 log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
 8 
 9 log4j.appender.logfile=org.apache.log4j.RollingFileAppender
10 log4j.appender.logfile.File=${petstore.root}/WEB-INF/petstore.log
11 log4j.appender.logfile.MaxFileSize=512KB
12 # Keep three backup files.
13 log4j.appender.logfile.MaxBackupIndex=3
14 # Pattern to output: date priority [category] - message
15 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
16 log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

 

 日志文件配置

struts.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6 
 7     <package name="default" extends="struts-default">
 8     
 9         <action name="saveUser" class="saveUserAction" >
10             <result name="success" >/success.jsp</result>
11              <result name="input">/save.jsp</result>
12         </action>
13          
14         <!-- 显示所有用户的Action -->
15         <action name="listUser" class="listUserAction">
16           <result name="success">/listUser.jsp</result>
17     </action>
18     
19     </package>
20 
21 </struts>

 

 struts配置

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

<!-- 配置一个数据源  org.gjt.mm.mysql.Driver  com.mysql.jdbc.Driver-->
<bean id="dataSource"
      class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
    <property name="driverClassName">
        <value>org.gjt.mm.mysql.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql://localhost:3306/demo</value>
    </property>
    <property name="username">
        <value>root</value>
    </property>
    <property name="password">
        <value>123456</value>
    </property>
</bean>

<!-- 配置sessionFactory -->
<bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <!-- 数据库方言 -->
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <!-- 显示sql语句 -->
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
    <!-- 映射文件 -->
    <property name="mappingLocations">
        <list>
            <value>classpath:com/demo/lihua/model/*.hbm.xml</value>
        </list>
    </property>
</bean>

<!-- 创建持久层Dao对象  依赖注入sessionFactory-->
<bean id="userDao" class="com.demo.lihua.daoImpl.UserDAOImpl" scope="singleton">
  <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<!-- 创建业务逻辑层Service对象   依赖注入其持久层对象属性-->
<bean id="userService" class="com.demo.lihua.serviceImpl.UserServiceImpl">
  <property name="userDao" ref="userDao" />
</bean>

<!-- 创建控制层SaveUserAction的对象 依赖注入其业务层对象属性  -->
<bean id="saveUserAction" class="com.demo.lihua.action.SaveUserAction"     scope="prototype">
      <property name="userService" ref="userService" />
</bean>

<!-- 创建ListUserAction的对象  依赖注入其业务逻辑层对象属性-->
<bean id="listUserAction" class="com.demo.lihua.action.ListUserAction"     scope="prototype">
      <property name="userService" ref="userService" />
</bean>
</beans>

 

 save.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib uri="/struts-tags"  prefix="s"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11 <h1><font color="red">保存用户</font></h1>
12 
13     <s:form action="saveUser" method="post">
14         <!-- 注意name = 对象名.属性名  -->
15         <s:textfield name="user.username" label="用户名"></s:textfield>
16         <s:textfield name="user.password" label="密码"></s:textfield>
17         <s:textfield name="user.email" label="邮箱"></s:textfield>
18       <s:submit value="提交"></s:submit>
19 
20     </s:form>
21 </body>
22 </html>

 

 UserDAOImplTest.java

package com.demo.lihua.daoImpl;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.demo.lihua.dao.UserDAO;
import com.demo.lihua.model.User;

public class UserDAOImplTest {
    public static UserDAO userDAO;
    
    @BeforeClass
    public static void setUp() {
        userDAO = new UserDAOImpl();
        ApplicationContext ctx = new FileSystemXmlApplicationContext("WebContent/WEB-INF/applicationContext.xml");
        userDAO = (UserDAO) ctx.getBean("userDao");
    }
    
    
    @Test
    public void testSaveUser() {
        User u = new User();
        u.setUsername("k");
        u.setPassword("k");
        u.setEmail("k@qq.com");
        userDAO.saveUser(u);

    }

    @Test
    public void testDeleteUser() {
        fail("Not yet implemented");
    }

    @Test
    public void testFindUserById() {
        fail("Not yet implemented");
    }

    @Test
    public void testFindAllUsers() {
        fail("Not yet implemented");
    }

    @Test
    public void testUpdateUser() {
        fail("Not yet implemented");
    }

}

 

这是一个junit的单元测试,无关乎主题,只是一个测试UserDAOImpl.java这个类的save方法,有兴趣的可以研究一下。

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 3   <display-name>SpringTest_06</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.jsp</welcome-file>
 6   </welcome-file-list>
 7   <servlet>
 8     <servlet-name>Dispatcher</servlet-name>
 9     <servlet-class>
10           org.springframework.web.servlet.DispatcherServlet
11       </servlet-class>
12     <init-param>
13       <param-name>contextConfigLocation</param-name>
14       <param-value>/WEB-INF/applicationContext.xml</param-value>
15     </init-param>
16     <load-on-startup>1</load-on-startup>
17   </servlet>
18   <servlet-mapping>
19     <servlet-name>Dispatcher</servlet-name>
20     <url-pattern>*.do</url-pattern>
21   </servlet-mapping>
22   <listener>
23     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
24   </listener>
25   <jsp-config>
26     <taglib>
27       <taglib-uri>/spring-form</taglib-uri>
28       <taglib-location>/WEB-INF/spring-form.tld</taglib-location>
29     </taglib>
30     <taglib>
31       <taglib-uri>/spring</taglib-uri>
32       <taglib-location>/WEB-INF/spring.tld</taglib-location>
33     </taglib>
34   </jsp-config>
35   <filter>
36     <filter-name>struts2</filter-name>
37     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
38   </filter>
39   <filter-mapping>
40     <filter-name>struts2</filter-name>
41     <url-pattern>/*</url-pattern>
42   </filter-mapping>
43 </web-app>

 

  这是web.xml的配置

4.效果演示

添加数据

执行成功

数据库结果

 

至此完成!

 

主要参考了这个网址

修改和补充了一些东西。

 

多的不解释,就像我自己去找资料一样就是求一个详细完整的代码而已!看看思路!

欢迎交流!

posted @ 2012-09-14 00:22  lihuabest  阅读(1718)  评论(0编辑  收藏  举报