S2SH整合

  struts-2.5.10 + hibernate-release-5.2.8.Final+ spring-framework-4.3.6.RELEASE  整合实例。

Struts2单独测试:

所需jar包

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>S2SH_struts2</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  
  
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

 

struts.xml文件

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

<struts>

    <package name="login"  extends="struts-default">
        <action name="login"  class="com.fuwh.action.Login" >
            <result name="success">/success.jsp</result>
            <result name="error">/login.jsp</result>
        </action>
    </package>
</struts>

 

Action

package com.fuwh.action;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private String password;
    private String error;
    
    public String getError() {
        return error;
    }
    public void setError(String error) {
        this.error = error;
    }
    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;
    }
    @Override
    public String execute() throws Exception {
        System.out.println("name:"+name);
        System.out.println("password:"+password);
        System.out.println("登陆验证");
        if(name.equals("fuwh")&&password.equals("123")){
            return SUCCESS;
        }else{
            error="用户名或密码错误";
            return ERROR;
        }
    }
    
}

JSP页面

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>struts-2.5.10</title>
</head>
<body>
<form action="login"  method="get">
    <label>name:</label><input type="text" name="name" value="${name }"/><br/>
    <label>pswd:</label><input type="password" name="password" value="${password }"/><br/>
    <input type="submit" value="提交"/><font color="red">${error }</font>
</form>
</body>
</html>
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>struts-2.5.10</title>
</head>
<body>
${name }登陆成功!!!
</body>
</html>

 

Hibernate包单独测试

 必须jar包

 

 实体类

 

package com.fuwh.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class Student {
    
    @Id
    @GeneratedValue(generator="_native")
    @GenericGenerator(name="_native",strategy="native")
    private int id;
    
    @Column(name="name")
    private String name;
    
    private int age;
    
    public Student() {
    }
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    
}

JUnit测试类

package com.fuwh.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.fuwh.model.Student;

public class StudentTest {

    private  SessionFactory sessionFactory;
    
    @Before
    public void setUp() throws Exception {
        final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
                .configure()
                .build();
        try {
            sessionFactory=new MetadataSources(registry)
                    .buildMetadata()
                    .buildSessionFactory();
        } catch (Exception e) {
            // TODO: handle exception
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

    @After
    public void tearDown() throws Exception {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }

    @Test
    public void test() {
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        Student student=new Student("fuwh",22);
        session.save(student);
        session.getTransaction().commit();
        session.close();
    }

}

 

配置文件

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">mysqladmin</property>
        <property name="hibernate.dialect">MySQL5</property>
        
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <property name="show_sql">true</property>
        
        <mapping class="com.fuwh.model.Student"/>
        
    </session-factory>
</hibernate-configuration>

 

Spring单独测试

必须的jar包

 

bean类

 

package com.fuwh.model;

public class Student {

    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    
    
    
}
package com.fuwh.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fuwh.model.Student;

public class StudentService {
    public static void main(String args[]){
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        Student student=(Student)ac.getBean("student");
        System.out.println(student);
    }
}

配置文件

 

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

    <bean id="student" class="com.fuwh.model.Student">
        <property name="id" value="1001"></property>
        <property name="name" value="fuwh"></property>
        <property name="age" value="10"></property>
    </bean>

</beans>

 

 

  测试完三个框架各自的必须包无问题后,那么现在就开始用Spring来整合Struts2和Hibernate。

 

  Spring在整合Strut2的时候,需要加入Struts提供的一个struts2-spring-plugin-2.5.10.jar开发包。

  然后在web.xml文件中,加入Spring的监听器,默认会让Spring来创建所有的Struts2对象,但是如果Spring创建不成功。

  则struts2会自己创建。

  Spring在整合Hibernate的时候,则需要加入一些数据库访问的包,本例中还使用了dbcp的连接池。

  spring-orm-4.3.6.RELEASE.jar

  spring-jdbc-4.3.6.RELEASE.jar

  commons-dbcp2-2.1.1.jar

  commons-pool2-2.4.2.jar

  如果还要使用切面,事务等其他功能则另外添加jar包。

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>S2SH</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 添加spring监听器 和配置Spring默认读取的配置文件路径 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:bean.xml</param-value>
  </context-param>  
  
  
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

实体类

package com.fuwh.model;

public class User {

    private int id;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    public User(){}
    
    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    public User(int id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }
    
    
}

hbm配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- 这是实体类和表的映射关系的配置文件 -->
<hibernate-mapping package="com.fuwh.model">
    <class name="User" table="t_user">
        <id name="id" type="int">
            <generator class="native"></generator>
        </id>
        <property name="username" column="username"/>
        <property name="password"></property>        
    </class>

</hibernate-mapping>

处理画面参数的action

package com.fuwh.action;

import com.fuwh.dao.UserDao;
import com.fuwh.model.User;
import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport{


    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String username;
    private String password;
    private String error;
    private UserDao userDao;
    
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getError() {
        return error;
    }
    public void setError(String error) {
        this.error = error;
    }
    @Override
    public String execute() throws Exception {
        System.out.println("登陆验证:(username:"+username+",password:"+password+")");
        User user=userDao.getUser(new User(username,password));
        if(user!=null){
            return SUCCESS;
        }else{
            error="用户名或密码错误";
            return ERROR;
        }
    }
}

dao

package com.fuwh.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import com.fuwh.model.User;


public class UserDao {
    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    private Session getSession(){
        return this.sessionFactory.openSession();
    }
    public User getUser(User user) throws Exception{
        Query query=this.getSession().createQuery("from User u where u.username=:username and u.password=:password");
        query.setParameter("username", user.getUsername());
        query.setParameter("password", user.getPassword());
//        query.setString(0, user.getUsername());
//        query.setString(1, user.getPassword());
        User newUser=(User)query.uniqueResult();
        return newUser;
    }
}

Spring的bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- 配置action login 交给Spring管理 -->
    <bean id="login" class="com.fuwh.action.Login">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <!-- 配置dao,也交给Spring管理 -->
    <bean id="userDao" class="com.fuwh.dao.UserDao">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
    <!-- 配置数据源 -->
     <bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
        <property name="username" value="root"/>
        <property name="password" value="mysqladmin"/>
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
        <property name="mappingResources">
            <list>
                <value>/com/fuwh/model/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
            </value>
        </property>
        
    </bean>
    
    
    
</beans>

struts.xml配置文件

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

<struts>
    <!-- class 属性指定的是Spring中配置的类的id -->
    <package name="login"  extends="struts-default">
        <action name="login"  class="login" >
            <result name="success">/success.jsp</result>
            <result name="error">/login.jsp</result>
        </action>
    </package>
</struts>

Hibernate配置文件,大部分配置都交给Spring管理了。

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
    <!-- 
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">mysqladmin</property>
        <property name="hibernate.dialect">MySQL5Dialect</property>
        <mapping class="com.fuwh.model.Student"/>
     -->    
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 把session绑定到当前线程中 -->
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>

    </session-factory>
</hibernate-configuration>

登陆页面

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>struts-2.5.10</title>
</head>
<body>
<form action="login"  method="get">
    <label>name:</label><input type="text" name="username" value="${username }"/><br/>
    <label>pswd:</label><input type="password" name="password" value="${password }"/><br/>
    <input type="submit" value="提交"/><font color="red">${error }</font>
</form>
</body>
</html>

 

这样就基本上整合好了。

 

当然数据源并不是必须的,也可以将Spring的配置文件中的数据源删掉,然后在hibernate中配置数据库连接属性。

 

posted @ 2017-02-19 16:31  Ouka傅  阅读(245)  评论(0编辑  收藏  举报