Struts2,Hibernate,Spring 框架学习总结

阅读 1492
收藏 104
2017-05-31
原文链接:blog.csdn.net

Struts2,Hibernate,Spring框架学习总结

最近项目比较松,所以又重头温故了下java WEB的知识,而SSH算是比较典型的框架了,值得我们一学,后续继续学习SSM,也就是SpringMVC,Spring,MyBits框架知识;
学习过程是枯燥的,中途好几次想放弃,但还是坚持了下来,没办法,谁让我们选择了这个苦逼的行业;
好了,废话不说了;

image.png

Struts2介绍:

先来一个简短而又清晰的描述:Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互。
用我的话来说它就是处理用户发送过来的请求的,然后根据请求跳转不同的界面和执行不同的业务逻辑,不知道这样理解对还是不对哇。当然它的功能远远不止这些,它还可以做到,请求参数的自动封装,文件的上传下载,数据校验,国际化,ognl等等等….
我印象比较深刻的一点就是,它是线程安全的,也就是用户每次访问,它都会实例化一个对象。而传统的servlet是线程不安全的,就是说不管多少用户访问,它的实例永远是一个。这不就帮我们解决了线程安全问题了吗!!!
再此,请允许我复制粘贴一份它的原理图…..

image.png

具体的大家自行百度,不用谢;

Hibernate介绍:

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
对我们安卓开发者来说ORM并不是很陌生,当然操作对象比操作原生的sql语句心情舒畅的多,不是吗?
这个框架总体上来说还是比较好理解的,这里说下学习它的重点
  • 对象关系映射(一对一,一对多和多对一,多对多)
  • 一级缓存和二级缓存
  • 事务的处理

Spring介绍:

重点,重点,重点!
Spring致力于J2EE应用的各层的解决方案,而不是仅仅专注于某一层的方案。可以说Spring是企业应用开发的“一站式”选择,并贯穿表现层、业务层及持久层。然而,Spring并不想取代那些已有的框架,而是与它们无缝地整合。
全体起立,请重复这句话:Spring并不想取代那些已有的框架,而是与它们无缝地整合;

image.png

Spring框架是这三个中最难理解最难学的一个了,至少我是这么认为的,它很强大,很强大…..
不过总结嘛,还是大概的总结下,最后再表演下它是如何整合其他框架的;
Spring的6大核心功能:
  • IOC容器, 解决对象创建及依赖关系;
  • Spring Web,Spring对web模块的支持,可以与struts整合,让struts的action创建交给spring,spring mvc模式;
  • Spring DAO,Spring 对jdbc操作的支持,JdbcTemplate模板工具类
  • SpringORM,spring对orm的支持,既可以与hibernate整合,也可以使用spring的对hibernate操作的封装
  • Spring AOP,切面编程
  • SpringEE,spring 对javaEE其他模块的支持

SSH框架整合:

目标:
  • 熟悉Struts2,Hibernate,Spring框架整合
  • 简单的增删改查

jdfw.gif

开发工具Eclipse,新建项目SSH,项目目录结构如下:

image.png

引入Struts2 jar包,Struts2版本为2.3
  • commons-fileupload-1.3.2.jar Struts核心包
  • commons-io-2.2.jar Struts核心包
  • commons-lang3-3.2.jar Struts核心包
  • commons-logging-1.1.3.jar Struts核心包
  • freemarker-2.3.22.jar Struts核心包
  • javassist-3.11.0.GA.jar Struts核心包
  • ognl-3.0.19.jar Struts核心包
  • struts2-core-2.3.32.jar Struts核心包
  • xwork-core-2.3.32.jar Struts核心包

image.png

将Struts2的配置文件copy到src跟目录下,然后在WebContent/WEB-INF/web.xml 配置Struts2的过滤器
struts.xml文件模版如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
      "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
     <!-- 引入外部的一个配置文件 -->
      <include file="com/itkimi/group/action/user_action.xml"></include>

</struts>
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>ssh</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- config struts -->
  <filter>
    <filter-name>struts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>struts</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
</web-app>
user_action.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

   <package name="user_modle" extends="struts-default" namespace="/user">

        <action name="user_*" class="com.itkimi.group.action.UserAction" method="{1}">
            <result name="{1}">/list.jsp</result>
        </action>

   </package>

</struts>
UserAction类内容如下:
package com.itkimi.group.action;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{


    public String register(){

        return "register";
    }
}
逻辑很简单,就是请求http://localhost:8080/ssh/user/user_register.action的时候转发到到list.jsp页面,配置无误后,启动tomcat,然后在浏览器运行

image.png

引入Hibernate框架,版本号为3.6.10:
  • hibernate3.jar 核心包
  • hibernate-jpa-2.0-api-1.0.1.Final.jar 核心包
  • antlr-2.7.6.jar 核心包
  • commons-collections-3.1.jar 核心包
  • dom4j-1.6.1.jar 核心包
  • javassist-3.12.0.GA.jar 核心包
  • jta-1.1.jar 核心包
  • slf4j-api-1.6.1.jar 核心包

image.png

引入技巧,就是图中圈中的文件夹下所有的jar,当然还有hibernate3.jar文件,以及mysql驱动包.jar 和 c3p0数据库连接池.jar
在src根目录下引入hibernate的配置文件:hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- c3p0 config -->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <property name="hibernate.c3p0.max_size">10</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">3</property>
        <property name="hibernate.c3p0.validate">false</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>


    </session-factory>

</hibernate-configuration>
简单映射一个用户表:
User.java
package com.itkimi.group.bean;

public class User {

    private int id;
    private String name;
    private String address;
    private int age;
    private String email;
    private String phone;

    public User() {
        super();
    }
    public User(String name, String address, int age, String email, String phone) {
        super();
        this.name = name;
        this.address = address;
        this.age = age;
        this.email = email;
        this.phone = phone;
    }

    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 String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}
User.hbm.xml
<?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">
<!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 -->
<hibernate-mapping package="com.itkimi.group.bean">

    <class name="User" table="user">

        <id name="id" column="id" type="java.lang.Integer">
            <generator class="native" />
        </id>

        <property name="name" column="name" type="java.lang.String"></property>
        <property name="address" column="address" type="java.lang.String"></property>
        <property name="email" column="email" type="java.lang.String"></property>
        <property name="phone" column="phone" type="java.lang.String"></property>
        <property name="age" column="age" type="java.lang.Integer"></property>

    </class>
</hibernate-mapping>
进行测试:
import com.itkimi.group.bean.User;

public class AppTest {

    private static SessionFactory buildSessionFactory;

    static {
        buildSessionFactory = new Configuration()
                .configure()
                .addClass(User.class)
                .buildSessionFactory();
    }

    @Test
    public void testAdd(){
        Session session = buildSessionFactory.openSession();
        session.beginTransaction();

        //test add user
        User user = new User("itkimi", "上海市", 25, "24750@163.com", "13211111111");
        session.save(user);

        session.getTransaction().commit();
        session.close();
    }
}

image.png

image.png

Spring框架的引入和整合:

Spring

  • spring-beans-3.2.5.RELEASE.jar 核心包
  • spring-context-3.2.5.RELEASE.jar 核心包
  • spring-core-3.2.5.RELEASE.jar 核心包
  • spring-expression-3.2.5.RELEASE.jar 核心包
  • spring-web-3.2.5.RELEASE.jar 整合struts需要
  • spring-aop-3.2.5.RELEASE.jar 核心包
  • spring-jdbc-3.2.5.RELEASE.jar 整合hibernate需要
  • spring-orm-3.2.5.RELEASE.jar 整合hibernate需要
  • spring-tx-3.2.5.RELEASE.jar 核心包

以及aop相关jar包

  • aopalliance.jar
  • aspectjrt.jar
  • aspectjweaver.jar

Struts需要引用的包

  • struts2-spring-plugin-2.3.32.jar
Spring的jar包有些多,但是总体上来说分为六大功能,需要用到什么引入什么就可以了,接下来,在web.xml中增加spring的配置
<?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>ssh</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- config spring -->
    <filter>
        <filter-name>OpenSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenSessionInView</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:bean.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- config struts -->
    <filter>
        <filter-name>sturts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sturts</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

</web-app>
contextConfigLocation 配置对应的xml文件,我们在看下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" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.itkimi" ></context:component-scan>


    <!-- datasource c3po数据库连接池配置-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>

    <!-- sessionFactory 整合hibernate时用到的sessionfactory-->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <!-- hibernate properties config hibernate属性配置-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- hibernate mapping file hibernate映射文件加载-->
        <property name="mappingLocations">
            <list>
                <value>classpath:com/itkimi/group/bean/*.hbm.xml</value>
            </list>
        </property>

    </bean>

    <!-- config translation 事务控制-->
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>


    <tx:advice id="tvAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" read-only="false" />
        </tx:attributes>
    </tx:advice>

    <!-- aop config -->
    <aop:config>
        <aop:pointcut expression="execution(* com.itkimi.group.service.*.*(..))"
            id="pt" />
        <aop:advisor advice-ref="tvAdvice" pointcut-ref="pt" />
    </aop:config>
</beans>
到这里,基本上三大框架整合就完毕了,接下来开始写action,service,dao了,直接上代码了
UserAction.java:
package com.itkimi.group.action;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itkimi.group.bean.User;
import com.itkimi.group.service.IUserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport{

    @Resource(name = "userServiceImp")
    private IUserService userService;
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    private User user;
    public User getUser() {
        return user;
    }

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

    //注册
    public String register(){
        userService.add(user);
        return "index";
    }

    //登陆
    public String login(){
        User u = userService.findUser(user);
        if(u != null){
            return "loginSuccess";
        }
        return "index";
    }

    //列表
    public String list(){
        List<User> userAll = userService.findAll();
        Map<String, Object> contextMap = ActionContext.getContext().getContextMap();
        contextMap.put("list", userAll);
        return "listJsp";
    }

    //删除
    public String delete(){
        User findUser = userService.findUser(user.getId());
        userService.remove(findUser);
        return "loginSuccess";
    }

    //修改
    public String update(){
        user = userService.findUser(user.getId());
        return "update";
    }

    public String updateComplete(){
        userService.update(user);
        return "loginSuccess";
    }

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

<struts>

   <package name="user_modle" extends="struts-default" namespace="/user">

        <action name="user_*" class="userAction" method="{1}">
            <result name="{1}">/{1}.jsp</result>
            <result name="index" type="redirect">/index.jsp</result>
            <result name="listJsp">/list.jsp</result>
            <result name="loginSuccess" type="redirectAction">user_list</result>
        </action>

   </package>
UserServiceImp
package com.itkimi.group.service.imp;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.itkimi.group.bean.User;
import com.itkimi.group.dao.IUserDao;
import com.itkimi.group.service.IUserService;

@Service("userServiceImp")
public class UserServiceImp implements IUserService {

    @Resource(name = "userDaoImp")
    private IUserDao userDao;
    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add(User user) {
        userDao.add(user);
    }

    @Override
    public void remove(User user) {
        userDao.remove(user);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User findUser(Serializable id) {
        return userDao.findUser(id);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findUser(User user) {
        return userDao.findUser(user);
    }

}
UserDaoImp
package com.itkimi.group.dao.imp;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Repository;

import com.itkimi.group.bean.User;
import com.itkimi.group.dao.IUserDao;

@Repository("userDaoImp")
public class UserDaoImp implements IUserDao{

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void add(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public void remove(User user) {
        sessionFactory.getCurrentSession().delete(user);
    }

    @Override
    public void update(User user) {
        sessionFactory.getCurrentSession().update(user);
    }

    @Override
    public User findUser(Serializable id) {
        return (User) sessionFactory.getCurrentSession().get(User.class, id);
    }

    @Override
    public List<User> findAll() {
        Session session = sessionFactory.getCurrentSession();
        return session.createQuery("from User").list();
    }

    @Override
    public User findUser(User user) {
        Session session = sessionFactory.getCurrentSession();
        Query createQuery = session.createQuery("from User u where u.name=? and u.password=?");
        createQuery.setString(0, user.getName());
        createQuery.setString(1, user.getPassword());
        User u = (User) createQuery.uniqueResult();
        return u;
    }

}
编写过程中遇到的问题总结,在开启Spring注解扫描的时候,启动tomcat莫名其妙的报错,百度了下也没找到答案,无意中将jdk 1.8切换为1.7此问题就解决了,可能造成的原因,某些jar包不是最新的吧;
好了,总结就到这里,相信以后回过头复习会更加深入理解。

本文对你有帮助?欢迎扫码加入后端学习小组微信群:

评论