码迷,mamicode.com
首页 > 编程语言 > 详细

Struts1 Spring2 iBatis2 框架的集成

时间:2015-07-01 00:49:10      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:

这个是属于比较老的框架了,奈何现在公司用的产品就是如此,闲来就搭一个集成框架吧

 

依赖jar包

antlr-2.7.6.jar
aspectj-1.8.2.jar
aspectjrt.jar
aspectjweaver-1.6.12.jar
bsf-2.3.0.jar
cglib-nodep-2.1_3.jar
commons-beanutils-1.8.0.jar
commons-dbcp-1.4.jar
commons-digester-2.0.jar
commons-fileupload-1.3.1.jar
commons-logging-1.2.jar
commons-pool.jar
commons-validator-1.3.1.jar
hamcrest-core-1.3.jar
ibatis-2.3.2.715.jar
jakarta-oro.jar
javax.servlet.jsp.jstl.jar
jstl-1.2.jar
jstl-impl.jar
junit-4.11.jar
log4j-1.2.17.jar
log4j-api-2.2.jar
log4j-core-2.2.jar
mysql-connector-java-5.1.7-bin.jar
oro-2.0.8.jar
spring-web-2.5.jar
spring-webmvc-2.5.jar
spring-webmvc-struts.jar
spring.jar
standard-1.1.2.jar
struts.jar

我们用一个小练习来演示框架的搭建是否成功,首先准备数据库环境

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8

自行插入测试数据


 

1、建立领域对象

package org.zln.module.domain;

import java.util.Date;

/**
 * Created by sherry on 15-6-30.
 */
public class User {
    private Integer id;
    private String name;
    private Date birthday;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", birthday=" + birthday +
                ‘}‘;
    }

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

2、Dao

package org.zln.base;

import com.ibatis.sqlmap.client.SqlMapClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Created by sherry on 000030/6/30 19:35.
 */
public class BaseDao {
    @Autowired
    @Qualifier("sqlMapClient")
    protected SqlMapClient sqlMapClient;
}
package org.zln.module.dao;

import org.zln.module.domain.User;

import java.util.List;

/**
 * Created by sherry on 15-6-30.
 */
public interface UserDao {
    /**
     * 查找用户
     */
    public abstract List<User> getUserList(User user);
}
package org.zln.module.dao.ibatis;

import org.springframework.stereotype.Repository;
import org.zln.base.BaseDao;
import org.zln.module.dao.UserDao;
import org.zln.module.domain.User;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by sherry on 15-6-30.
 */
@Repository("userDao")
public class UserDaoImpl extends BaseDao implements UserDao {

    @Override
    public List<User> getUserList(User user) {
        List<User> users = null;
        try {
            users = sqlMapClient.queryForList("org.zln.module.domain.User.getUserList", user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }
}

3、Service

package org.zln.module.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zln.module.dao.UserDao;
import org.zln.module.dao.ibatis.UserDaoImpl;
import org.zln.module.domain.User;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by sherry on 15-6-30.
 */
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserService {
    @Autowired
    @Qualifier("userDao")
    public UserDao userDao;

    @Transactional(readOnly = true)
    public List<User> getUserList(Integer id,String name){
        User user = new User();
        user.setId(id);
        user.setName(name);
        return userDao.getUserList(user);
    }
}

4、iBatis配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
    PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-2.dtd">

<!-- 设置命名空间 -->
<sqlMap namespace="org.zln.module.domain.User">

    <!--别名-->
    <typeAlias alias="User" type="org.zln.module.domain.User"/>

    <!--参数Map-->
    <parameterMap id="User-Par-Map" class="User">
        <parameter property="id" jdbcType="INTEGER"/>
        <parameter property="name" jdbcType="VARCHAR"/>
        <parameter property="birthday" jdbcType="DATE"/>
    </parameterMap>
    <!--返回Map-->
    <resultMap id="User-Res-Map" class="User">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="birthday" column="birthday"/>
    </resultMap>
    /*查询列表*/
    <sql id="select-user-list">
        SELECT
            t1.id
            ,t1.name
            ,t1.birthday
        FROM user t1
    </sql>
    /*查询条件*/
    <sql id="where-user-parameter">
        <dynamic prepend="WHERE">
            <isNotEmpty prepend="AND" property="id">
                t1.id = #id#
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="name">
                <!--这是MySQL的写法 不同数据库拼接方式不同-->
                t1.name LIKE CONCAT(‘%‘, #name#, ‘%‘)
                <!--
                Oracle like ‘%‘ || #username# || ‘%‘
                SqlServer like ‘%‘ + #username# +  ‘%‘
                -->
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="birthday">
                t1.birtjday = #birtjday#
            </isNotEmpty>
        </dynamic>
    </sql>
    /*更新列表*/
    <sql id="update-user-list">
        <dynamic prepend="SET">
            <isNotEmpty prepend="," property="id">
                t1.id = #id#
            </isNotEmpty>
            <isNotEmpty prepend="," property="name">
                t1.name = #name#
            </isNotEmpty>
            <isNotEmpty prepend="," property="birthday">
                t1.birthday = #birthday#
            </isNotEmpty>
        </dynamic>
    </sql>
    /*查询User*/
    <select id="getUserList" parameterMap="User-Par-Map" resultMap="User-Res-Map">
        <include refid="select-user-list"/>
        <include refid="where-user-parameter"/>
    </select>
</sqlMap>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE sqlMapConfig
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <!--iBatis配置信息-->
    <settings enhancementEnabled="true"
              useStatementNamespaces="true"
              cacheModelsEnabled="true"
              lazyLoadingEnabled="true"/>

    <!-- 映射文件位置 -->
    <sqlMap resource="org/zln/module/cfg/ibatis/User.xml" />

</sqlMapConfig>



5、集成iBatis与Spring

<?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:context="http://www.springframework.org/schema/context"
       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.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:annotation-config/>
    <!--数据源配置-->
    <context:property-placeholder location="classpath:org/zln/cfg/jdbc.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--iBatis配置-->
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="configLocation" value="classpath:org/zln/cfg/ibatis/sql-map-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--JDBC数据源事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--使用注解配置事务-->
    <tx:annotation-driven transaction-manager="txManager"/>

    <!--base-->
    <context:component-scan base-package="org.zln.base"/>
    <!--module dao-->
    <context:component-scan base-package="org.zln.module.dao.ibatis"/>
    <!--module service-->
    <context:component-scan base-package="org.zln.module.service"/>
    <!---->
    <!--引入模块化配置文件-->
    <!--<import resource="classpath:org/zln/module/cfg/spring/module_dao.xml"/>-->
    <!--<import resource="classpath:org/zln/module/cfg/spring/module_service.xml"/>-->
    <import resource="classpath:org/zln/module/cfg/spring/module_action.xml"/>
</beans>

个人喜欢使用自动扫描与注解的方式进行Bean的管理与事务管理

6、测试Spring+iBatis

package org.zln.module.service;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zln.module.dao.UserDao;
import org.zln.module.domain.User;

import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by sherry on 15-6-30.
 */
public class UserServiceTest {

    private static ApplicationContext applicationContext;
    private static final String[] CONFIG_FILES = {"org/zln/cfg/spring/db_spring_cfg.xml"};
    private UserService userService;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception{
        applicationContext = new ClassPathXmlApplicationContext(CONFIG_FILES);
    }

    @Before
    public void setUpBefore() throws Exception{
        userService = (UserService) applicationContext.getBean("userService");
    }

    @Test
    public void testGetUserList() throws Exception {
        List<User> users = userService.getUserList(1,null);
        for (User u:users){
            System.out.println(u);
        }
    }
}

7、集成Struts1与Spring2

Action

package org.zln.base;

import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by sherry on 000030/6/30 20:16.
 */
public class BaseAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String parameter = mapping.getParameter();
        System.out.println("请求parameter:"+parameter);
        String forward = "error";
        if ("index".equals(parameter)){
            //进入工程测试主页面
            forward = gotoIndex(mapping,form,request,response);
        }
        return mapping.findForward(forward);
    }

    private String gotoIndex(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        return "success";
    }
}
package org.zln.module.action;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.zln.base.BaseAction;
import org.zln.module.domain.User;
import org.zln.module.form.UserForm;
import org.zln.module.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by sherry on 000030/6/30 20:55.
 */
public class UserAction extends BaseAction{

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String parameter = mapping.getParameter();
        System.out.println("请求parameter:"+parameter);
        String forward = "error";
        if ("loginUI".equals(parameter)){
            //登陆页面
            forward = loginUI(mapping, form, request, response);
        }else if ("loginDO".equals(parameter)){
            //登陆动作
            forward = loginDo(mapping, form, request, response);
        }
        return mapping.findForward(forward);
    }

    private String loginDo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        User user = new User();
        try {
            PropertyUtils.copyProperties(user,userForm);
            List<User> users = userService.getUserList(user.getId(),user.getName());
            request.setAttribute("userObj",user);
            request.setAttribute("users",users);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }

    private String loginUI(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        return "success";
    }
}
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
    "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
    <global-forwards>
        <forward name="error" path="/WEB-INF/error.jsp"/>
    </global-forwards>
    <action-mappings>
        <!--进入工程首页-->
        <action path="/index" parameter="index">
            <forward name="success" path="/WEB-INF/main.jsp"/>
        </action>
    </action-mappings>

    <!--Spring管理Action-->
    <controller>
        <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/>
    </controller>
</struts-config>
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
        "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>

    <form-beans>
        <form-bean name="userForm" type="org.zln.module.form.UserForm"/>
    </form-beans>
    <action-mappings>
        <!--登陆页面-->
        <action path="/module/loginUI" name="userForm" parameter="loginUI">
            <forward name="success" path="/WEB-INF/module/login/loginUI.jsp"/>
        </action>
        <!--登陆动作-->
        <action path="/module/loginDo" name="userForm" parameter="loginDO">
            <forward name="success" path="/WEB-INF/module/login/loginSuccess.jsp"/>
            <forward name="failure" path="/WEB-INF/module/login/loginFailure.jsp"/>
        </action>
    </action-mappings>

</struts-config>

8、Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:org/zln/cfg/spring/db_spring_cfg.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--Spring解决乱码问题-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Struts1配置-->
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <!--主配置文件-->
        <init-param>
            <param-name>config</param-name>
            <param-value>
                /WEB-INF/struts_cfg/struts-config.xml
                ,/WEB-INF/struts_cfg/struts_module.xml
            </param-value>
        </init-param>
        <!--module 模块配置文件-->
        <!--<init-param>
            <param-name>config/module</param-name>
            <param-value>/WEB-INF/struts_cfg/struts_module.xml</param-value>
        </init-param>-->
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

9、JSP

<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<%--
  Created by IntelliJ IDEA.
  User: nbcoo_000
  Date: 000030/6/30
  Time: 20:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%
    String homePage = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
    <title>登陆页面</title>
</head>
<body>
    <html:form action="/module/loginDo" method="post">
        <table>
            <caption>登陆</caption>
            <tr>
                <td>用户名</td>
                <td>
                    <html:text property="name"/>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <html:submit>登陆</html:submit>
                </td>
            </tr>
        </table>
    </html:form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="bean"    uri="http://struts.apache.org/tags-bean" %>
<%@ taglib prefix="logic"   uri="http://struts.apache.org/tags-logic" %>
<%@ taglib prefix="c"       uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="html" uri="http://jakarta.apache.org/struts/tags-html" %>
<%
    String homePage = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
    <title>登陆成功</title>
</head>
<body>
    <table>
        <tr>
            <td>ID</td>
            <td>NAME</td>
            <td>BIRTHDAY</td>
        </tr>
        <logic:iterate id="user" name="users" type="org.zln.module.domain.User">
            <tr>
                <td><html:text property="id" name="user" /></td>
                <td><html:text property="name" name="user" /></td>
                <td><html:text property="birthday" name="user" /></td>
            </tr>
        </logic:iterate>
    </table>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%
    String homePage = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
    <title>登陆失败</title>
</head>
<body>
    登陆失败
</body>
</html>

漏了个Form,大家就自行补上吧,有哪里不对与需要改进的地方,不吝赐教

 

Struts1 Spring2 iBatis2 框架的集成

标签:

原文地址:http://www.cnblogs.com/sherrykid/p/4612135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!