本文主要介绍Struts2+Spring3+Mybatis3开发环境搭建
Struts和Spring不过多介绍。
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plan Old Java Objects,普通的 Java 对象)映射成数据库中的记录。
环境:
Struts-2.3.14
Spring-3.2.1
MyBatis-3.2.2
在apache-tomcat-7.0.39下测试通过
Project目录结构
lib文件夹下的依赖包:
入口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>test_ssm</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring资源 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/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>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,/config/struts.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Spring配置文件
applicationContext-common.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: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-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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 启用spring注解支持 -->
<context:annotation-config />
<!-- 配置DataSource数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!--创建sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:config/mabatis-config.xml" />
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/jialin/mapper/**/*.xml" />
</bean>
<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务的传播特性 -->
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="edit*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">readOnly</prop>
</props>
</property>
</bean>
</beans>
applicationContext-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:aop="http://www.springframework.org/schema/aop"
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-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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="userInfoDao" class="org.mybatis.spring.mapper.MapperFactoryBean"
scope="prototype">
<property name="mapperInterface" value="com.jialin.dao.UserInfoDao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userInfoService" class="com.jialin.service.UserInfoService"
scope="prototype">
<property name="userInfoDao" ref="userInfoDao" />
</bean>
<!-- 为IRegisterService接口配置事务拦截器,baseTransactionProxy是事务拦截器,在Controller中获取这个对象 -->
<bean id="IUserInfoService" parent="baseTransactionProxy">
<!-- 实现类 -->
<property name="target" ref="userInfoService" />
</bean>
<bean id="userManageAction" class="com.jialin.action.UserManageAction"
scope="prototype">
<property name="userInfoService" ref="IUserInfoService" />
</bean>
</beans>
Struts配置文件
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 将Action的创建交给spring来管理 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 更改struts2请求Action的后缀名,默认为action。若想去掉后缀,设为","即可 -->
<constant name="struts.action.extension" value=","></constant>
<package name="abstract_struts" abstract="true" extends="struts-default"
namespace="/">
<!-- 公共东西可以放到这个抽象包下 -->
</package>
<!-- 包含的配置文件 -->
<include file="/config/struts-user.xml"></include>
</struts>
struts-user.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="MyActions" extends="struts-default">
<action name="*_*" class="userManageAction" method="{1}">
<result name="success" type="redirect">/{2}.jsp</result>
</action>
</package>
</struts>
Mybatis配置文件
mabatis-config.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>
<typeAlias alias="userinfo" type="com.jialin.entity.UserInfo"/>
</typeAliases>
<!-- 因为已经在applicationContext-common中指定了映射文件的位置,这里就省略了 -->
<!-- <mappers>
<mapper resource="com/jialin/dao/registerMapper.xml"/>
</mappers> -->
</configuration>
UserManageAction.java
package com.jialin.action;
import com.jialin.entity.UserInfo;
import com.jialin.service.IUserInfoService;
public class UserManageAction {
private IUserInfoService userInfoService;
public IUserInfoService getUserInfoService() {
return userInfoService;
}
public void setUserInfoService(IUserInfoService userInfoService) {
this.userInfoService = userInfoService;
}
private UserInfo userInfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public String insertUser() {
userInfoService.insertUser(userInfo);
return "success";
}
public String editUser() {
userInfoService.edit(userInfo);
return "success";
}
public String removeUser() {
userInfoService.remove(userInfo);
return "success";
}
public String getUserById() {
userInfoService.get(userInfo);
return "success";
}
public String getListByName() {
userInfoService.getList(userInfo);
return "success";
}
public String getAllUser() {
userInfoService.getAllUser();
return "success";
}
}
IUserInfoService.java
package com.jialin.service;
import java.util.List;
import com.jialin.entity.UserInfo;
public interface IUserInfoService {
public void insertUser(UserInfo user);
public void edit(UserInfo user);
public void remove(UserInfo user);
public UserInfo get(UserInfo user);
public List getList(UserInfo user);
public List getAllUser();
}
UserInfoService.java
package com.jialin.service;
import java.util.List;
import java.util.Iterator;
import com.jialin.dao.UserInfoDao;
import com.jialin.entity.UserInfo;
public class UserInfoService implements IUserInfoService {
private UserInfoDao userInfoDao;
public UserInfoDao getUserInfoDao() {
return userInfoDao;
}
public void setUserInfoDao(UserInfoDao userInfoDao) {
this.userInfoDao = userInfoDao;
}
@Override
public void insertUser(UserInfo user)
{
userInfoDao.insertUser(user);
}
@Override
public void edit(UserInfo user) {
userInfoDao.edit(user);
}
@Override
public void remove(UserInfo user) {
userInfoDao.remove(user);
}
@Override
public UserInfo get(UserInfo user) {
UserInfo user1=userInfoDao.get(user);
System.out.println(user1.getUsername());
return user1;
}
@Override
public List getList(UserInfo user) {
List list=userInfoDao.getList(user);
for(Iterator iter=list.iterator();iter.hasNext();)
{
UserInfo user1=(UserInfo)iter.next();
System.out.println(user1.getUsername()+",");
}
return list;
}
@Override
public List getAllUser() {
List list= userInfoDao.getAllUser();
for(Iterator iter=list.iterator();iter.hasNext();)
{
UserInfo user=(UserInfo)iter.next();
System.out.println(user.getUsername()+",");
}
return list;
}
}
UserInfoDao.java
package com.jialin.dao;
import java.util.List;
import com.jialin.entity.UserInfo;
public interface UserInfoDao {
public void insertUser(UserInfo user);
public void edit(UserInfo user);
public void remove(UserInfo user);
public UserInfo get(UserInfo user);
public List getList(UserInfo user);
public List getAllUser();
}
UserInfo.java
package com.jialin.entity;
public class UserInfo {
private int id;
private String username;
private String password;
private String ismanager;
public void setIsmanager(String ismanager) {
this.ismanager = ismanager;
}
public String getIsmanager() {
return ismanager;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
Mybaitis映射文件
userinfo-mapper.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.jialin.dao.UserInfoDao">
<!-- 自动生成id策略 -->
<insert id="insertUser" parameterType="userinfo" useGeneratedKeys="true" keyProperty="id">
insert into userinfo(username,password,ismanager) values (#{username},#{password},#{ismanager})
</insert>
<!-- userInfoResultMap是userinfo-resultmap.xml中定义的resultmap -->
<select id="getList" parameterType="userinfo" resultType="list" resultMap="userInfoResultMap">
select * from userinfo where username like '%' #{username} '%'
</select>
<select id="getAllUser" resultType="list" resultMap="userInfoResultMap">
select * from userinfo
</select>
<select id="get" parameterType="userinfo" resultType="com.jialin.entity.UserInfo" resultMap="userInfoResultMap">
<![CDATA[
select * from userinfo where id = #{id}
]]>
</select>
<update id="edit" parameterType="userinfo">
update userinfo set
username = #{username},
password = #{password}
where id = #{id}
</update>
<delete id="remove" parameterType="userinfo">
delete from userinfo where id = #{id}
</delete>
</mapper>
userinfo-resultMap.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.jialin.dao.UserInfoDao">
<resultMap type="com.jialin.entity.UserInfo" id="userInfoResultMap">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="ismanager" column="ismanager"/>
</resultMap>
</mapper>
测试jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title></title>
<script type="text/javascript">
function insertUser()
{
var myform=document.forms[0];
myform.action="insertUser_success";
myform.method="post";
myform.submit();
}
function getUserByName()
{
var myform=document.forms[0];
myform.action="getListByName_success";
myform.method="post";
myform.submit();
}
function getAllUser()
{
var myform=document.forms[0];
myform.action="getAllUser_success";
myform.method="post";
myform.submit();
}
function editUser()
{
var myform=document.forms[0];
myform.action="editUser_success";
myform.method="post";
myform.submit();
}
function getUserById()
{
var myform=document.forms[0];
myform.action="getUserById_success";
myform.method="post";
myform.submit();
}
function removeUser()
{
var myform=document.forms[0];
myform.action="removeUser_success";
myform.method="post";
myform.submit();
}
</script>
</head>
<body>
<h1>用户管理</h1>
<hr>
<form name="myform" >
id:<input type="text" name="userInfo.id"> <br>
用户名:<input type="text" name="userInfo.username"> <br>
密码:<input type="text" name="userInfo.password"> <br>
是否为管理员:<input type="text" name="userInfo.ismanager"><br>
<input type="button" name="btninsert" onclick="insertUser()" value="增加" />
<input type="button" name="btnedit" onclick="editUser()" value="修改" />
<input type="button" name="btnremove" onclick="removeUser()" value="删除" /><br>
<input type="button" name="btnget" onclick="getUserById()" value="按id查询" />
<input type="button" name="btngetlist" onclick="getUserByName()" value="按名称查询" />
<input type="button" name="btngetall" onclick="getAllUser()" value="查询全部" />
</form>
</body>
</html>
贴代码也是个体力活,多余的话没有,核心的几个配置文件的说明都已写到注释里。
下面会出一篇文章探讨一个Hibernate和Mybatis的区别,还会出一些对这些框架讨论的文章,欢迎大家关注!