1. 程式人生 > >SSH框架的搭建和測試(Spring + Struts2 + Hibernate)

SSH框架的搭建和測試(Spring + Struts2 + Hibernate)

conf work fault 項目 -i extends struts2 scrip map

SSH框架實現了視圖、控制器、和模型的徹底分離,同時還實現了業務邏輯層與持久層的分離。

Spring實現了MVC中的 Controller的功能,Struts實現Web視圖的功能,Hibernate則實現數據模型層的功能對數據進行持久化。

搭建流程:

實現對Spring的支持
實現對hibernate的支持
  --測試Spring+hibernate

實現對struts的支持
  --導包:struts2-spring-plugin-2.3.16.3.jar
  --在web.xml配置文件裏配置監聽器,服務器一旦啟動,就加載Spring容器
  
  <!-- 監聽服務器啟動 -->
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 讀取spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</
param-value> </context-param>

1、項目結構:

技術分享圖片

2、安裝Spring

技術分享圖片

3、依賴包(其中包括Spring、Struts2和Hibernate的一些依賴包)

技術分享圖片

技術分享圖片

技術分享圖片

4、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 監聽服務器啟動 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 讀取spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml,classpath:config/applicationContext-dao.xml</param-value> </context-param> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> <init-param> <param-name>config</param-name> <param-value>struts-default.xml,struts-plugin.xml,config/struts.xml</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

5、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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <!-- <import resource="config/applicationContext-dao.xml"/> -->

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation"
            value="classpath:config/hibernate.cfg.xml">
        </property>
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"></property>
    </bean>
    
    <!-- 註入service -->
    <bean id="userService" class="com.cn.service.UserService">
        <property name="userDao" ref="userDao"></property>
    </bean>
    
    <!-- 註入dao 
    <bean id="userDao" class="com.cn.dao.UserDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>-->
    
    <!-- 註入action -->
    <bean id="registAction" class="com.cn.action.RegistAction">
        <property name="userService" ref="userService"></property>
    </bean>
    
    </beans>

也可以在外部註入;

applicationContext-dao.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    
    <!-- 註入dao -->
    <bean id="userDao" class="com.cn.dao.UserDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    
    </beans>

6、hibernate.cfg.xml

<?xml version=‘1.0‘ encoding=‘UTF-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/xtkj?characterEncoding=utf-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="myeclipse.connection.profile">CS</property>
    
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="connection.autocommit">true</property>
    
        <mapping class="com.cn.pojo.User"/>
    </session-factory>

</hibernate-configuration>

7、struts.xml(在web.xml配置文件裏配置監聽器,服務器一旦啟動,就加載Spring容器):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

    <package name="test" extends="struts-default">
        <action name="registAction_*" class="registAction" method="{1}">
            <result name="welcome">/welcome.jsp</result>
        </action>
    </package>

</struts>    

測試:

8、pojo封裝數據層:User.java

package com.cn.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="tb_user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private String password;
    private String address;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public User(String name, String password, String address) {
        super();
        this.name = name;
        this.password = password;
        this.address = address;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
}

9、dao數據持久化層:

UserDao.java:

package com.cn.dao;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cn.pojo.User;

public class UserDao extends HibernateDaoSupport implements UserDAOInterf{

    public void save(User user){
        this.getHibernateTemplate().save(user);
    }
    
}

UserDAOInterf.java:

package com.cn.dao;

import com.cn.pojo.User;

public interface UserDAOInterf {

    public void save(User user);
    
}

10、service業務邏輯層:

UserService.java:

package com.cn.service;

import org.springframework.transaction.annotation.Transactional;

import com.cn.dao.UserDAOInterf;
import com.cn.dao.UserDao;
import com.cn.pojo.User;

public class UserService implements UserServiceInterf{

    private UserDAOInterf userDao;
    
    @Transactional
    public void save(User user){
        userDao.save(user);
    }

    public UserDAOInterf getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDAOInterf userDao) {
        this.userDao = userDao;
    }

    
    
}

UserServiceInterf.java:

package com.cn.service;

import com.cn.pojo.User;

public interface UserServiceInterf {

    public void save(User user);
    
}

11、action控制器層(負責業務邏輯層與表現層的交互):RegistAction.java

package com.cn.action;

import com.cn.pojo.User;
import com.cn.service.UserService;
import com.cn.service.UserServiceInterf;

public class RegistAction {

    private User user;
    private UserServiceInterf userService;
    
    public String regist(){
        userService.save(user);
        return "welcome";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserServiceInterf getUserService() {
        return userService;
    }

    public void setUserService(UserServiceInterf userService) {
        this.userService = userService;
    }
}

12、regist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘regist.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <form action="registAction_regist">
        用戶名:<input type="text" name="user.name"/><br/>
        密碼:<input type="password" name="user.password"/><br/>
        地址:<input type="text" name="user.address"/><br/>
        <input type="submit" value="註冊"/>
    </form>
  </body>
</html>

SSH框架的搭建和測試(Spring + Struts2 + Hibernate)