今天用spring+struts2+mybatis整合了一个框架,以下是各文件配置内容或代码。
一、建立一个web工程,取名zframe
二、引入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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>zframe</display-name>
<!-- 设置spring字符编码过滤器 -->
<filter>
<filter-name>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring容器加载配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 加载spring容器的配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置Struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
四、配置applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 采用注解的方式配置bean -->
<context:annotation-config />
<!-- 配置要扫描的包 -->
<context:component-scan base-package="com.frame"></context:component-scan>
<!-- 配置数据源属性文件 -->
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/db.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<!-- 队列中的最小等待数 -->
<property name="minIdle" value="${database.minIdle}"/>
<!-- 队列中的最大等待数 -->
<property name="maxIdle" value="${database.maxIdle}"/>
<!-- 最长等待时间,单位毫秒 -->
<property name="maxWait" value="${database.maxWait}"/>
<!-- 最大活跃数 -->
<property name="maxActive" value="${database.maxActive}"/>
<!-- 初始化个数 -->
<property name="initialSize" value="${database.initialSize}"/>
</bean>
<!-- 配置mybatis的SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/mybatis.xml"></property>
</bean>
<!-- 配置mybatis数据处理的方式,共四种方式,这里采用MapperScannerConfigurer方式 -->
<!--
SqlSessionTemplate 这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制
SqlSessionDaoSupport 这个只需要在实现类中继承特殊类就可以使用sqlsession
MapperFactoryBean 这个要写配置文件,把对应的所有接口在配置文件中引用即可,无需写实现类
MapperScannerConfigurer 这个要写配置文件,只要给出接口所在的包即可,会自动把包中的接口引入,无需写实现类
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.frame.dao"/>
</bean>
<!-- 事务配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- jdbc初始化数据库 -->
<jdbc:initialize-database data-source="dataSource" ignore-failures="NONE" enabled="${jdbc.initializedatabase}">
<jdbc:script encoding="utf-8" location="/WEB-INF/db-init.sql"/>
</jdbc:initialize-database>
</beans>
五、配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 指定默认编码集 ,作用于HttpServletRequest的setCharacterEncoding()和freemarker,vilocity的输出 -->
<constant name="struts.i18n.encoding" value="UTF-8"/>
<!-- 当struts配置文件修改时是否自动加载 -->
<constant name="struts.configuration.xmlreload" value="true"/>
<!-- 开发模式下打印详细的错误信息,默认为false -->
<constant name="struts.devMode" value="true"/>
<!-- 标准的UI主题,默认的UI主题为xhtml,可以为simple,xhtml或ajax -->
<constant name="struts.ui.theme" value="xhtml"/>
<package name="test" namespace="/" extends="struts-default">
<action name="hello" class="com.frame.action.HelloAction">
<result name="success">/pages/hello.jsp</result>
</action>
<action name="demo" class="demoAction">
</action>
</package>
</struts>
六、配置log4j.properties
log4j.rootLogger=info,A1
log4j.logger.com.mchange=warn,A1
log4j.additivity.com.mchange=false
log4j.logger.org.hibernate=warn,A1
log4j.additivity.org.hibernate=false
log4j.logger.com.ibatis=warn,A1
log4j.additivity.com.ibatis=false
# ConsoleAppender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss,SSS} [%c]-[%p] %m%n
# 打印sql
log4j.logger.org.apache.ibatis=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
#com.frame
log4j.logger.com.frame=debug
七、建表及序列sql文件db-init.sql内容
create table DEMO
(
ID NUMBER,
NAME VARCHAR2(50),
GENDER VARCHAR2(1),
AGE NUMBER,
CREATE_DATE DATE,
UPDATE_DATE DATE
);
create sequence DEMO_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 21
increment by 1
cache 20;
八、配置mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
</typeAliases>
<mappers>
<mapper resource="com/frame/dao/demoMapper.xml"/>
</mappers>
</configuration>
九、数据库属性文件db.properties内容
#######################datasource config################################
#for oracle
database.driver=oracle.jdbc.driver.OracleDriver
database.url=jdbc:oracle:thin:@127.0.0.1:1521:xe
database.username=test
database.password=test
#######################pool config################################
database.initialSize=2
database.maxActive=10
database.maxIdle=5
database.minIdle=3
database.maxWait=3000
#######################jdbc:initialize-database enabled config################################
jdbc.initializedatabase=false
一、建立一个类:com.frame.action.HelloAction,内容如下:
package com.frame.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport implements ServletResponseAware{
private static final long serialVersionUID = -6493858961444458651L;
private HttpServletResponse response;
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public String execute() throws Exception {
System.out.println("HelloAction.execute is executing...");
return SUCCESS;
}
public void say() throws IOException{
System.out.println("HelloAction.say is executing....");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<span style='color:red;'>啊哈,We are here!</span>");
out.close();
}
}
二、建一个响应jsp:/zframe/WebRoot/pages/hello.jsp,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'hello.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1 style="color:#aabbff;">欢迎使用struts2。。。</h1>
</body>
</html>
三、测试结果:
测试一下mybatis:
一、建立一个action类
package com.frame.action;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.frame.service.DemoService;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class DemoAction extends ActionSupport {
private static final long serialVersionUID = -3617424650852024180L;
@Autowired
private DemoService demoService;
private String name;
private String gender;
private int age;
public void insert() {
System.out.println("开始执行插入数据。。。");
Map map = new HashMap();
map.put("name", name);
map.put("gender", gender);
map.put("age", age);
this.demoService.insert(map);
System.out.println("插入数据成功:"+map);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
二,建立一个service接口并建其实现类:
a.接口
package com.frame.service;
import java.util.Map;
public interface DemoService {
public void insert(Map map);
}
b.实现类
package com.frame.service.impl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.frame.dao.DemoDao;
import com.frame.service.DemoService;
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
private DemoDao demoDao;
@Override
public void insert(Map map) {
this.demoDao.insert(map);
}
}
三、建立Dao接口和其对应的mapper文件
a.dao接口
package com.frame.dao;
import java.util.Map;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public interface DemoDao {
public void insert(Map map);
}
b.demoMapper.xml内容
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.frame.dao.DemoDao">
<insert id="insert">
insert into demo (
id,
name,
gender,
age,
create_date)
values(
demo_seq.nextval,
#{name,jdbcType=VARCHAR},
#{gender,jdbcType=VARCHAR},
#{age,jdbcType=NUMERIC},
sysdate)
</insert>
</mapper>
c.demoMapper.xml说明
demoMapper.xml的路径配置在mybatis.xml文件中。其内的sql需要一个namespace,用来指定它是哪个dao的sql。如:其内id为insert的sql对应com.frame.dao.DemoDao接口的insert方法。当然这种配置是mybatis中的一种,如需要了解更多,请查询mybatis的文档。
四、jsp表单文件/zframe/WebRoot/pages/demo.jsp内容
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'demo.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="demo!insert.action">
姓名:<input name="name"><br>
性别:<input type="radio" name="gender" value="1">男<input type="radio" name="gender" value="2">女<br>
年龄:<input name="age" οnkeyup="this.value=this.value.replace(/[^0-9]/g,'');"><br>
<input type="submit" value="确定">
</form>
</body>
</html>
五、测试结果
结束!
相对应的原代码下载地址:http://download.csdn.net/detail/yunsyz/6674559