Struts2+Spring3.2+ibatis2.3整合
Struts2+Spring3.2+ibatis2.3整合
转自:http://blog.163.com/ppy2790@126/blog/static/1032422412013330105358161/
一、代码目录结构:
![](https://images0.cnblogs.com/blog2015/663332/201506/151104202639695.jpg)
二、web.xml配置:(集成struts、spring)
<?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">
<!-- 加载spring 配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<!-- 设置编码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>Set Character 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>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三、spring配置:(整合ibats,配置数据数据库,事务管理,配置ibatis)
--------------------------------------------华丽分隔线---------------------------------------------------
spring-jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mydb
jdbc.username=root
jdbc.password=root
--------------------------------------------华丽分隔线---------------------------------------------------
spring-transaction.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: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-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="propertyBean"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/spring-jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<aop:config proxy-target-class="true">
<aop:advisor
pointcut="execution(* cn.itair.service.*.*(..))"
advice-ref="txAdvice" />
</aop:config>
<!-- SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:config/sql-map-config.xml" />
<property name="mappingLocations"
value="classpath*:/cn/itair/ibatis/sqlmap/*.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!--
the transactional advice (what 'happens'; see the <aop:advisor/> bean
below)
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="list*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="search*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- end::transaction -->
<!-- 事务 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 抽象的Dao -->
<bean id="baseIbatisDAO" abstract="true">
<property name="sqlMapClient">
<ref local="sqlMapClient" />
</property>
</bean>
</beans>
--------------------------------------------华丽分隔线---------------------------------------------------
spring-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: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-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="udao" class="cn.itair.dao.impl.UserDaoImpl" parent="baseIbatisDAO"/>
</beans>
--------------------------------------------华丽分隔线---------------------------------------------------
spring-service.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: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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="userService"
class="cn.itair.service.impl.UserServiceImpl">
<property name="usersDao" ref="udao" />
</bean>
</beans>
--------------------------------------------华丽分隔线---------------------------------------------------
spring-action.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: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-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="userAction"
class="cn.itair.action.UsersAction"
scope="prototype">
<property name="userService" ref="userService" />
</bean>
</beans>
--------------------------------------------华丽分隔线---------------------------------------------------
struts.xml:
<?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="abc" extends="struts-default" namespace="">
<action name="userAction" class="userAction">
<result name="user">/user.jsp</result>
</action>
<action name="userList" class="userAction" method="doList">
<result name="list">/list.jsp</result>
</action>
</package>
</struts>
--------------------------------------------华丽分隔线---------------------------------------------------
log4j.properties:
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
#JDBC
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
#ibatisERROR
log4j.logger.com.ibatis=ERROR
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=ERROR
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=ERROR
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=ERROR
#struts2
log4j.logger.org.apache.struts2=ERROR
log4j.logger.org.apache=ERROR
log4j.logger.com.opensymphony=ERROR
#spring
log4j.logger.org.springframework=WARN
log4j.logger.org.springframework.aop=ERROR
log4j.logger.org.quartz=ERROR
#tomcat
log4j.logger.org.apache.catalina.core=ERROR
#c3p0
log4j.logger.com.mchange.v2=ERROR
#proxool
log4j.logger.org.logicalcobwebs.proxool=ERROR
#xfire
log4j.logger.org.codehaus.xfire=ERROR
#JSON
log4j.logger.com.googlecode.jsonplugin=DEBUG
五、分层调用:bean-->dao(spring-dao.xml)-->servcie(spring-service.xlm)-->action(spring-action.xml)-->view(jsp)
sqlmap/xxx.xml _|
ibatis的sql配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="user">
<select id="findUsers" resultClass="cn.itair.bean.Users">
SELECT
uid,uname,upass
FROM
USERS
</select>
<insert id="save">
INSERT INTO users(uname,upass) VALUES
(#uname#,#upass#)
</insert>
<select id="count" resultClass="java.lang.Integer">
select count(*) as count from
users
</select>
<select id="getAllUser" resultClass="cn.itair.bean.Users" parameterClass="java.util.Map">
<![CDATA[
SELECT uid, uname, upass FROM users limit #start# ,#end#
]]>
</select>
</sqlMap>
六、封装一个ibatis操作的基类,每个dao类从该类继承:
package cn.itair.web.code;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
private static final long serialVersionUID = -4025716041310497629L;
private Logger log4j = Logger.getLogger(BaseAction.class);
public String jsonString;
public void outJsonString(String str) {
getResponse().setContentType("text/javascript;charset=UTF-8");
outString(str);
}
public void outString(String str) {
try {
PrintWriter out = getResponse().getWriter();
out.write(str);
} catch (IOException e) {
e.printStackTrace();
log4j.error("out print failed:" + e);
}
}
public void outXMLString(String xmlStr) {
getResponse().setContentType("application/xml;charset=UTF-8");
outString(xmlStr);
}
/**
* 获得request
*
* @return
*/
public HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
/**
* 获得response
*
* @return
*/
public HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
/**
* 获得session
*
* @return
*/
public HttpSession getSession() {
return getRequest().getSession();
}
/**
* 获得servlet上下文
*
*
*
* @return
*/
public ServletContext getServletContext() {
return ServletActionContext.getServletContext();
}
public String getRealyPath(String path) {
return getServletContext().getRealPath(path);
}
}
七、分页工具类PageUtil:
public class PageUtil {
private int curPage = 0; // 当前页
private int pageSize = 0; // 每页多少行
private int endSize; // 用于not in(select top endSize id)不在多少行内
private int totalRow; // 共多少行
private int totalPage; // 共多少页
public int getStart() {
if (curPage > 1)
return (curPage - 1) * pageSize;
else
return 0;
}
public int getEnd() {
return pageSize;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
int temp = pageSize * (curPage - 1);
this.setEndSize(temp);
this.curPage = curPage;
}
public int getEndSize() {
return endSize;
}
public void setEndSize(int endSize) {
this.endSize = endSize;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRow() {
return totalRow;
}
public void setTotalRow(int totalRow) {
totalPage = totalRow / pageSize;
if (totalRow % pageSize > 0)
totalPage = totalPage + 1;
this.totalRow = totalRow;
}
public int getTotalPage() {
return this.totalPage;
}
public String getToolsMenu() {
StringBuffer str = new StringBuffer("");
int next, prev;
prev = curPage - 1;
next = curPage + 1;
if (curPage > 1) {
str
.append("<a href=\"javascript:void(0)\" onclick=\"document.forms[0].pages.value=1;document.forms[0].submit();\">首页</a> ");
} else {
str.append("<a href=\"javascript:void(0)\">首页</a> ");
}
if (curPage > 1) {
str
.append("<a href=\"javascript:void(0)\" onclick='document.forms[0].pages.value="
+ prev
+ ";document.forms[0].submit();'>上页</a> ");
} else {
str.append("<a href=\"javascript:void(0)\">上页</a> ");
}
if (curPage < totalPage) {
str
.append("<a href=\"javascript:void(0)\" onclick='document.forms[0].pages.value="
+ next
+ ";document.forms[0].submit();'>下页</a> ");
} else {
str.append("<a href=\"javascript:void(0)\" >下页</a> ");
}
if (totalPage > 1 && curPage != totalPage) {
str
.append("<a href=\"javascript:void(0)\" onclick='document.forms[0].pages.value="
+ totalPage
+ ";document.forms[0].submit();'>末页</a> ");
} else {
str.append("<a href=\"javascript:void(0)\" >末页</a> ");
}
str.append(" 共" + totalRow + "条记录");
str.append(" 第"+curPage+"页");
str
.append(" 每页<SELECT size=1 name=pagesize onchange='this.form.pages.value=1;this.form.pageSize.value=this.value;this.form.submit();'>");
if (pageSize == 3) {
str.append("<OPTION value=3 selected>3</OPTION>");
} else {
str.append("<OPTION value=3>3</OPTION>");
}
if (pageSize == 10) {
str.append("<OPTION value=10 selected>10</OPTION>");
} else {
str.append("<OPTION value=10>10</OPTION>");
}
if (pageSize == 20) {
str.append("<OPTION value=20 selected>20</OPTION>");
} else {
str.append("<OPTION value=20>20</OPTION>");
}
if (pageSize == 50) {
str.append("<OPTION value=50 selected>50</OPTION>");
} else {
str.append("<OPTION value=50>50</OPTION>");
}
if (pageSize == 100) {
str.append("<OPTION value=100 selected>100</OPTION>");
} else {
str.append("<OPTION value=100>100</OPTION>");
}
str.append("</SELECT>");
str.append("条 分" + getTotalPage() + "页显示 转到");
str
.append("<SELECT size=1 name=Pagelist onchange='this.form.pages.value=this.value;this.form.submit();'>");
for (int i = 1; i < totalPage + 1; i++) {
if (i == curPage) {
str.append("<OPTION value=" + i + " selected>" + i
+ "</OPTION>");
} else {
str.append("<OPTION value=" + i + ">" + i + "</OPTION>");
}
}
str.append("</SELECT>页");
str.append("<INPUT type=hidden value=" + curPage
+ " name=\"pages\" > ");
str.append("<INPUT type=hidden value=" + pageSize
+ " name=\"pageSize\"> ");
return str.toString();
}
}
八、action代码:
public class UsersAction extends BaseAction {
private UserService userService;
private int pages = 1;
private int pageSize = 3;
private String pageBar;
private List<Users> list;
private Users user;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
userService.add(user);
return "user";
}
public String doList() throws Exception {
PageUtil page = new PageUtil();
int count = getUserService().getCount();
page.setCurPage(pages);
page.setPageSize(pageSize);
page.setTotalRow(count);
pageBar = page.getToolsMenu();
Map<String, Integer> pageMap = new HashMap<String, Integer>();
pageMap.put("start", page.getStart());
pageMap.put("end", page.getEnd());
list = getUserService().getAllUser(pageMap);
return "list";
}
//getters and setters
}
九、页面代码:
<h4>user information list</h4>
<hr>
<s:form action="userList">
<s:iterator value="#request.list" id="us">
<s:property value="#us.uname"/>
<br/>
</s:iterator>
<hr>
<s:property value="#request.pageBar" escape="false"/>
</s:form>