1.导入的相关包是:
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
mybatis-3.2.2.jar
mybatis-spring-1.2.0-javadoc.jar
mybatis-spring-1.2.0-sources.jar
mybatis-spring-1.2.0.jar
ojdbc5.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
2.建立的package
com.ly.action(com/ly/action/UserAction.java struts的action操作层)
com.ly.mapper(com/ly/mapper/UserMapper.java和com/ly/mapper/UserMapper.xml mapper接口和映射文件)
com.ly.model(com/ly/model/User.java POJO类)
com.ly.service(/com/ly/service/UserService.java service接口)
com.ly.service.impl(com/ly/service/impl/UserServiceImpl.java service接口实现类 业务逻辑层)
3.myEclipse需要导入的插件有:
Struts 2 Core Libraries
Struts 2 Spring Libraries
Spring 3.0 Core Libraries
Spring 3.0 AOP Libraries
Spring 3.0 Persistence JDBC
Spring 3.0 Persistence Core
Spring 3.0 web libraries
4.在src/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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!--指定oracle.properties的位置--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:oracle.properties"></property> </bean> <!--链接oracle数据源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="url" value="${jdbc.url}"></property> <property name="driverClassName" value="${jdbc.driver}"></property> </bean> <!-spring管理sqlsessionfactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--告诉spring mapper映射文件的位置 该包下的所有xml文件--> <property name="mapperLocations" value="classpath*:com/ly/mapper/**/*.xml"></property> <!--告诉spring POJO;类--> <property name="typeAliasesPackage" value="com.ly.model"></property> </bean> <bean id="usermapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> <property name="mapperInterface" value="com.ly.mapper.UserMapper"></property> </bean> <!--需要在userservice的实现类里添加mappper对象属性--> <bean id="userserviceimpl" class="com.ly.service.impl.UserServiceImpl"> <property name="usermapper" ref="usermapper"></property> </bean> <!--该配置后,需要在UserAction.java类里添加userservice属性--> <bean id="useraction" class="com.ly.action.UserAction"> <property name="userservice" ref="userserviceimpl"></property> </bean> <!-- 配置事物 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--链接其他spring配置文件--> <import resource="aop.xml"/> </beans>
aop.xml配置:
这一步需要右键工程名/src目录new->other->Spring->Spring Bean Definition->next-(需要修改配置文件的文件名,自定义文件名这里是aop.xml)->finish
<?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:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:advice id="txadvice" transaction-manager="transactionManager"> <tx:attributes> <!--抛出异常测回滚--> <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED" timeout="-1" rollback-for="java.lang.Exception" /> <tx:method name="del*" isolation="DEFAULT" propagation="REQUIRED" timeout="-1" rollback-for="java.lang.Exception" /> <tx:method name="upd*" isolation="DEFAULT" propagation="REQUIRED" timeout="-1" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> <!--execution中execute表示包含这个包中的所有方法,不管参数和返回类型,而且是该包下的所有类--> <aop:config expose-proxy="false" proxy-target-class="false"> <aop:pointcut expression="execution(* com.ly.service..*.*(..))" id="txcut" /> <aop:advisor advice-ref="txadvice" pointcut-ref="txcut" /> </aop:config> </beans>
strutrs.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="default" extends="struts-default"> <!-- class中的useraction是spring的ID为useraction的id名 --> <action name="useraction*" class="useraction" method="{1}"> <result>/index.jsp</result> </action> </package> </struts>
oracle.properties配置信息:
jdbc.username=数据库账号 jdbc.password=数据库密码 jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl jdbc.driver=oracle.jdbc.driver.OracleDriver
5.User.java源码:(POJO类)
package com.ly.model; public class User { private String username; private String password; private Integer age; //生成相应的set get 方法 }
6.UserMapper.java接口 和xml映射文件关联 代码
package com.ly.mapper; import java.util.List; import com.ly.model.User; public interface UserMapper { List<User> selectUser(User user); }
mapper映射文件代码:
<?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.ly.mapper.UserMapper"> <!-- id就是UserMapper接口中的方法名,parameterTYpe就是传入的参数类型,resultType为输出类型 --> <select id="selectUser" parameterType="User" resultType="User"> select * from user where username=#{username} </select> </mapper> <!-- select 语句属性配置细节: 属性 描述 取值 默认 id 在这个模式下唯一的标识符,可被其它语句引用 parameterType 传给此语句的参数的完整类名或别名 resultType 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用) resultMap 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用) flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true|false false useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 true|false false timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置 fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定 statementType statement,preparedstatement,callablestatement。 预准备语句、可调用语句 STATEMENT PREPARED CALLABLE PREPARED resultSetType forward_only,scroll_sensitive,scroll_insensitive 只转发,滚动敏感,不区分大小写的滚动 FORWARD_ONLY SCROLL_SENSITIVE SCROLL_INSENSITIVE 驱动器决定 -->
然后在 UserService接口中定义一个方法:
List<User> selectUser(User user);
用来查询sql操作,并返回结果集,然后在impl实现类中实现该方法。
UsererviceImpl.java类:
package com.ly.service.impl; import java.util.List; import com.ly.mapper.UserMapper; import com.ly.model.User; import com.ly.service.UserService; public class UserServiceImpl implements UserService{ private UserMapper usermapper; //生成set get 方法 @Override public List<User> selectUser(User user) { return usermapper.selectUser(user); }}
实现了selectUser方法后,并返回结果集,然后应在action类中接收该返回集合
UserAction.java :
package com.ly.action; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.ly.model.User; import com.ly.service.UserService; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport implements SessionAware { private Map<String, Object> session; private UserService userservice; private User user; private List<User> list; //.......相应的set get 方法 @Override public String execute() throws Exception { list=userservice.selectUser(user);//struts会自动存入request作用域 return SUCCESS; }}
index.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf8"%> <% 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 'index.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"> <script type="text/javascript"> function look(){ var val=prompt("请输入用户名:",""); if(val!=null && val!=""){ var f=document.getElementById("f"); f.action="useraction.action?user.username="+val;//默认调用execute()方法,user.username struts会自动得到 f.submit(); } } </script> </head> <body> <center> <form id="f" method="post"> <input type="button" value="点击查询用户" onclick="look()"/> </form> </center> </body> </html>
show.jsp 为显示结果的页面,代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'show.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"> </head> <body> <center> <table> <tr> <th>用户名</th> <th>年龄</th> </tr> <!-- list中存在的泛型为User --> <c:forEach items="${list}" var="i"> <tr> <td>$i.username}</td> <td>${i.age}</td> </tr> </c:forEach> </table> </center> </body> </html> <!-- 查询出来的结果 显示在这JSP上 -->