详细源码请看:https://github.com/yxiaobai/struts-spring-mybatis
struts spring mybatis
---------------------------------------------1、pom.xml 配置依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fz</groupId> <artifactId>struts-spring-mybatis</artifactId> <packaging>war</packaging> <version>1.0</version> <name>struts-spring-mybatis</name> <url>http://maven.apache.org</url> <properties> <java-version>1.8</java-version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <struts.version>2.5.10</struts.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- log4j2 log4j-core2.7 jar log4j-api2.7 jar--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> <!-- struts2.5.10 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> <!-- struts2 实现注解需要的jar包--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.5.10</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.10</version> </dependency> <!--spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.6.RELEASE</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> <scope>provided</scope> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 导入dbcp的jar包,beans.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- web servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <sourceDirectory>src/main/java</sourceDirectory> <testSourceDirectory>src/test/java</testSourceDirectory> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java-version}</source> <target>${java-version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> <configuration> <!--将类文件打成jar包--> <archiveClasses>false</archiveClasses> <!--将资源文件打到classes目录下--> <webResources> <resource> <directory>src/main/resources</directory> <targetPath>WEB-INF/classes</targetPath> <filtering>true</filtering> </resource> </webResources> </configuration> </plugin> <!-- tomcat plugin --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/manager/text</url> <!-- tomcat管理路径 --> <server>tomcat7</server> <!-- 与settings.xml文件中Server的id相同 --> <uriEncoding>utf-8</uriEncoding> <port>8080</port><!--服务器端口号80可以省去--> <path>/</path> <!-- 应用的部署位置 --> <contextReloadable>true</contextReloadable> <systemProperties> <java.util.logging.SimpleFormatter.format>[%4$s] %1$tF %1$tT %3$s %5$s %n </java.util.logging.SimpleFormatter.format> </systemProperties> </configuration> <executions> <execution> <id>tomcat-run</id> <phase>test</phase> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
2、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"> <display-name>struts</display-name> <!-- spring framework 4.3.6 监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- strutx 2.5.10 支持 --> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3、在resources/beans.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <context:component-scan base-package="com.action,com.entity"/> <!-- 引入jdbc配置文件db.properties --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:db.properties"/> </bean> <!-- 使用spring jdbc中的类建立数据源 --> <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.user}"/> <property name="password" value="${db.pass}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${db.initialSize}"/> <!-- 连接池最大数量 --> <property name="maxActive" value="${db.maxActive}"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${db.maxIdle}"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="${db.minIdle}"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${db.maxWait}"/> </bean> <!-- SqlSessionFactory --> <bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="ds"/> <!-- com.entity.Student 可以写 sutdent --> <property name="typeAliasesPackage" value="com.entity"/> <property name="mapperLocations" value="classpath:com/entity/mapper/*Mapper.xml"/> </bean> <!-- SqlSession --> <bean id="session" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sf"/> </bean> <!--创建数据映射器,数据映射器必须为接口 --> <!-- <bean id="ssm" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.entity.mapper.StudentMapper" /> <property name="sqlSessionFactory" ref="sf" /> </bean> --> <!-- 扫描mapper包 自动在spring中生成 xxxxMapper bean --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.entity.mapper"/> <property name="sqlSessionFactoryBeanName" value="sf"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="ds"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
4、在resources/struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <constant name="struts.devMode" value="true"/> <constant name="struts.configuration.xml.reload" value="true"/> <!--国际化配置--> <constant name="struts.custom.i18n.resources" value="res"/> <constant name="struts.i18n.encoding" value="UTF-8"/> <constant name="struts.i18n.reload" value="true"/> <constant name="struts.ui.theme" value="simple"/> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.action.extension" value="action,,do"/> <constant name="struts.action.excludePattern" value="/myservlet.action,/tag.jsp"/> <package name="reg" extends="struts-default" namespace="/"> <action name="test" class="aaaa"/> <action name="show" class="aaaa" method="show"> <result>/show.jsp</result> </action> <action name="del" class="aaaa" method="delete"> <result type="redirectAction"> <param name="actionName">show</param> <param name="namespace">/</param> </result> </action> </package> </struts>
5、在resources/db.properties
#jdbc 参数 db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf8&useSSL=true db.user=root db.pass= #dbcp 数据库连接池配置参数 #定义初始连接数 db.initialSize=0 #定义最大连接数 db.maxActive=20 #定义最大空闲 db.maxIdle=20 #定义最小空闲 db.minIdle=1 #定义最长等待时间 db.maxWait=60000
<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="com.opensymphony.xwork2" level="info"/> <Logger name="org.apache.struts2" level="info"/> <Logger name="org.springframework" level="info"/> <Root level="info"> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration>
7、webapp/index.jsp
<%@ page language="java" pageEncoding="utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Struts 2.5.10 test</title> <style> input{padding:5px;margin:5px;} </style> </head> <body> <a href="show">显示学生信息</a> <h3>jstl-core</h3> <c:forEach begin="1" end="10" step="1" var="i"> <h5>jstl-foreach-${i}</h5> </c:forEach> <hr> <h3>struts-action操作</h3> <a href="test">test</a> <a href="show">show</a> <hr> <h3>struts-tag</h3> <s:iterator begin="1" end="10" step="2"> <s:property/><br> </s:iterator> </body> </html>
8、webapp/show.jsp
<s:iterator value="sts" var="s"> <s:property value="uname"/>-----<a href="del.action?id=${s.id}" οnclick="return confirm('是否要删除:${s.uname}?')">删除</a><br> </s:iterator>
9、com.entity.mapper.StudentMapper.java
package com.entity.mapper; import com.entity.Student; import org.apache.ibatis.annotations.Insert; import java.util.List; public interface StudentMapper { public List<Student> query(); public int delById(int id); @Insert("insert into student values(null,#{uname},#{address})") public int insert(Student student); }
10、com.entity.mapper.StudentMapper.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.entity.mapper.StudentMapper"> <select id="query" resultType="student"> select * from student </select> <delete id="delById" parameterType="int"> delete from student where id = #{id} </delete> </mapper>
11、com.action.Test.java
package com.action; import com.entity.mapper.StudentMapper; import lombok.Data; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @Component("aaaa") @Data public class Test { private int id; public void execute() throws IOException { HttpServletResponse resp = ServletActionContext.getResponse(); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.print("<!DOCTYPE html>"); out.print("\n<html lang=\"zh\">"); out.print("\n<head>\n<meta charset=\"utf-8\">\n<title>webrx</title>\n<body>"); out.print("\n<h1>hello-struts2.5.10-中文</h1>"); out.print("\n</body>"); out.print("\n</html>"); out.flush(); out.close(); } @Autowired //自动注入spring ioc 中的 studentMapper private StudentMapper studentMapper; public String show(){ ServletActionContext.getContext().put("sts",studentMapper.query()); return "success"; } public String delete(){ studentMapper.delById(id); return "success"; } }
详细源码请看:https://github.com/yxiaobai/struts-spring-mybatis