Struts1 Spring2 iBatis2 框架的集成
这个是属于比较老的框架了,奈何现在公司用的产品就是如此,闲来就搭一个集成框架吧
依赖jar包
antlr-2.7..jar
aspectj-1.8..jar
aspectjrt.jar
aspectjweaver-1.6..jar
bsf-2.3..jar
cglib-nodep-.1_3.jar
commons-beanutils-1.8..jar
commons-dbcp-1.4.jar
commons-digester-2.0.jar
commons-fileupload-1.3..jar
commons-logging-1.2.jar
commons-pool.jar
commons-validator-1.3..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..jar
log4j-api-2.2.jar
log4j-core-2.2.jar
mysql-connector-java-5.1.-bin.jar
oro-2.0..jar
spring-web-2.5.jar
spring-webmvc-2.5.jar
spring-webmvc-struts.jar
spring.jar
standard-1.1..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 框架的集成的更多相关文章
- S2SH框架的集成
S2SH框架的集成 20131130 代码下载 : 链接: http://pan.baidu.com/s/1sz6cQ 密码: 513t 这一个星期的时间里,学习SSH框架技术,首先因为之前的项目用到 ...
- 细说shiro之五:在spring框架中集成shiro
官网:https://shiro.apache.org/ 1. 下载在Maven项目中的依赖配置如下: <!-- shiro配置 --> <dependency> <gr ...
- 在spring+springMvc+mabatis框架下集成swagger
我是在ssm框架下集成swagger的,具体的ssm搭建可以看这篇博文: Intellij Idea下搭建基于Spring+SpringMvc+MyBatis的WebApi接口架构 本项目的GitHu ...
- 浅谈IDEA搭建SSM框架的集成
前言 学习完MyBatis,Spring,SpringMVC之后,我们需要做的就是将这三者联系起来,Spring实现业务对象管理,Spring MVC负责请求的转发和视图管理, MyBatis作为数据 ...
- springboot框架中集成thymeleaf引擎,使用form表单提交数据,debug结果后台获取不到数据
springboot框架中集成thymeleaf引擎,使用form表单提交数据,debug结果后台获取不到数据 表单html: <form class="form-horizontal ...
- 九:SpringBoot-整合Mybatis框架,集成分页助手插件
九:SpringBoot-整合Mybatis框架,集成分页助手插件 1.Mybatis框架 1.1 mybatis特点 1.2 适用场景 2.SpringBoot整合MyBatis 2.1 核心依赖 ...
- spring 2.5 基础知识和与其他框架的集成
spring环境搭建: 一:导入spring2.5所需的包,在classpath目录下建一个名为"beans.xml"模板文件: <?xml version="1. ...
- 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程
本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...
- php的laravel框架快速集成微信登录
最终的解决方案是:https://github.com/liuyunzhuge/php_weixin_provider,详细的介绍请往下阅读. 本文面向的是php语言laravel框架的用户,介绍的是 ...
随机推荐
- AMD、CMD和CommonJS规范(转)
CommonJS规范 CommonJS是在浏览器环境之外构建JavaScript生态系统为目标产生的项目,比如服务器和桌面环境中.CommonJS规范是为了解决JavaScript的作用域问题而定义 ...
- DFS练习一---HDU 1342
参考文章来源:http://blog.csdn.net/pengwill97/article/details/54850852 题目在这里:HDU.1342 最近在练习DFS,就找了一些题来做,力求自 ...
- input属性总结
<input type="text" readonly="readonly" /> 这个是不能输入的 readonly="readonly ...
- exa命令详解
exa 是 ls 文件列表命令现代化替代品. 官网:https://the.exa.website/ GitHub:https://github.com/ogham/exa 后续整理中……
- java 基础面试
1. &和&&的区别 答: &是位运算符,表示按位与运算,&&是逻辑运算符,表示逻辑与(and) 2.int 和 Integer 有什么区别 答: Ja ...
- dts--tests(二)
rxtx_callbacks.py """ DPDK Test suite. Test Rxtx_Callbacks. """ import ...
- ajax状态值和状态码
AJAX状态值是指,运行AJAX所经历过的几种状态,无论访问是否成功都将响应的步骤,可以理解成为AJAX运行步骤.如:正在发送,正在响应等,由AJAX对象与服务器交互时所得:使用“ajax.ready ...
- SQLSERVER 数据库恢复挂起的解决办法
如果你的数据库还处于挂起状态,请把我下面代码的test改为你的库名,然后执行完,刷新就正常了: USE masterGOALTER DATABASE test SET SINGLE_USERGOALT ...
- Java8 新API读取文件内容
import java.io.IOException;import java.nio.charset.Charset;import java.nio.file.Files;import java.ni ...
- __builtin_popcount() 函数
详解 该函数的主要作用是计算一个数字的二进制中有多少个1,返回值就是其中1的个数. 它使用一张基于表的方法来进行位搜索,因此这个操作的执行效率很高 此处举一题 P1582 倒水 #include &l ...