码迷,mamicode.com
首页 > 编程语言 > 详细

手动配置三大框架整合:Spring+Struts2+mybatis

时间:2014-12-24 13:30:55      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:

现在主流的项目框架中,数据库持久层有可能不是hibernate,而是mybatis或者ibatis,其实它们都是一样的,下面我来把环境搭建一下:

【导入相关jar包】新建web项目工程mss,Spring+Struts2+mybatis整合,除了Spring和Struts的jar包外(可以在我的资源中下载),我们还需导入mybatis的几个想jar包:

技术分享

三大框架整合后jar包:

技术分享技术分享

【配置web.xml】

<?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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- struts启动配置 -->
  <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>
  
  <!-- spring启动加载配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springConfig/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>
            org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  
  <!-- log4j相关配置 -->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
</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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<aop:aspectj-autoproxy proxy-target-class="true" />
    
    <!-- 读取配置文件 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties"/>
	</bean>
	
	<!--  数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName">
		   <value>${jdbc_driver}</value>
		</property>
		<property name="url">
			<value>${jdbc_url}</value>
		</property>
		<property name="username">
		    <value>${jdbc_user}</value>
		</property>
		<property name="password">
		    <value>${jdbc_password}</value>
		</property>
		<property name="maxActive" value="100"></property>
		<property name="maxIdle" value="30"></property>
		<property name="maxWait" value="500"></property>
		<property name="defaultAutoCommit" value="true"></property>
	</bean>

    <!-- 事务配置 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 实体映射类-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="com.mss.common.pojo" />
	</bean>

</beans>

数据库配置文件jdbc.properties:
技术分享

【struts2公共配置】

<?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>
	<!-- 将struts2交给spring管理-->
	<constant name="struts.configuration.xml.reload" value="true"/>
	<constant name="struts.action.extension" value="action,do,webwork" />
	
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
	<constant name="struts.multipart.maxSize" value="100971520"></constant>
	<constant name="struts.i18n.encoding" value="UTF-8"></constant>
	<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
	<constant name="struts.objectFactory" value="spring"></constant>
	<constant name="struts.custom.i18n.resources" value="messages"></constant>
	
	<include file="strutsConfig/struts-user.xml"></include>
</struts>

【创建数据表结构】:项目中我们使用的是mysql数据库,在里面新建了一个user表:

技术分享

【搭建项目结构】:这里我使用了三层架构:Action-->Service-->Dao(实体类)

编写user实体类:

package com.mss.common.pojo;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String id;
	private String userName;
	private String password;
	private String email;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUsername(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

编写我们的dao层UserDao:

package com.mss.user.dao;

import java.util.List;
import com.mss.common.pojo.User;


public interface UserDao {
	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(User user);
	
	/**
	 * 列出所有用户
	 * @return
	 */
	public List<User> queryUsers();
	
	/**
	 * 删除用户
	 * @param id
	 */
	public void delUser(String id);
}

使用mybatis,我们得配置xml文件,将实体类User与表user映射,也将UserDao中的方法进行映射实现,这样我们不需要写UserDaoImpl,因为对数据库的操作也在这个xml中进行:UserDao.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.mss.user.dao.UserDao">

    <!-- User实体类、User表映射,注意实体类User和表名应该一致,字段下面可配置 -->
	<resultMap id="UserMap" type="com.mss.common.pojo.User">
		<result property="id" column="ID" />
		<result property="userName" column="USERNAME" />
		<result property="password" column="PASSWORD" />
		<result property="email" column="EMAIL" />
	</resultMap>

    <!-- 将UserDao中的方法进行配置,id=方法名称,parameterType=参数类型,resultMap返回的结果,
    	当用户使用UserDao中的方法时,mybaties自己会找相应配置文件中的对数据库的操作 -->
	<insert id="addUser" parameterType="User">
		INSERT INTO USER(
		ID,
		USERNAME,
		PASSWORD,
		EMAIL
		)
		VALUES (
		#{id},
		#{userName},
		#{password},
		#{email}
		)
	</insert>
	
	<!-- 返回一个上面的 resultMap实例,这里的resultMap要与上面的配置的resultMap中的id一致-->
	<select id="queryUsers" resultMap="UserMap" >
		SELECT * FROM USER
	</select>
	
	<!-- 删除信息 -->
	<delete id="delUser" parameterType="string">
		DELETE FROM USER WHERE ID = #{id}
	</delete>
	
</mapper>

编写我们的Service和ServiceImpl类,操作Dao层:UserService、UserServiceImpl

public interface UserService {
	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(User user);
	
	/**
	 * 列出所有的用户
	 * @return
	 */
	public List<User> queryUsers();
	
	/**
	 * 删除用户
	 * @param id
	 */
	public void delUser(String id);
}
package com.mss.user.serviceImpl;

import java.util.List;

import com.mss.common.pojo.User;
import com.mss.user.dao.UserDao;
import com.mss.user.service.UserService;

public class UserServiceImpl implements UserService{
	private UserDao userDao;
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 添加用户
	 */
	public void addUser(User user) {
		userDao.addUser(user);
	}

	/**
	 * 列出所有用户
	 */
	public List<User> queryUsers() {
		List<User> userList = userDao.queryUsers();
		return userList;
	}

	/**
	 * 删除用户
	 */
	public void delUser(String id) {
		userDao.delUser(id);
	}

	

}

编写Action,操作Service,UserAction

/**
 * 用户操作Action
 * @author dell
 *
 */
public class UserAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(UserAction.class);

	public UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private String id;
	private String userName;
	private String password;
	private String email;

	/**
	 * 添加用户信息
	 * 
	 * @return
	 */
	public String addUser() {
		User user = new User();
		try {
			String iid =new Random().nextInt(100)+"";
			user.setId(iid);
			user.setUsername(userName);
			user.setPassword(password);
			user.setEmail(email);
			userService.addUser(user);
		} catch (Exception e) {
			logger.error("exception in add user", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 从数据库中获得所有的用户信息
	 * 
	 * @return
	 */
	public String queryUsers() {
		try {
			List<User> userList = userService.queryUsers();
			for (int i = 0; i < userList.size(); i++) {
				System.out.println(userList.get(i).getId());
			}
			HttpServletRequest request = ServletActionContext.getRequest();
			request.setAttribute("list", userList);
			return "list";
		} catch (Exception e) {
			logger.error("Exception in queryUsers", e);
			return ERROR;
		}
	}

	/**
	 * 删除用户信息
	 * 
	 * @return
	 */
	public String delUser() {
		try {
			userService.delUser(id);
		} catch (Exception e) {
			logger.error("Exception in delUser", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

整体代码结构:

技术分享

其中,跟mybatis相关最大的一个就是UserDao.xml文件了,我们的所有对数据库的操作和方法都可以在里面进行相应的配置和参数设置,只要将相应的名称设置和匹配好,mybatis就能够自动调用
【配置我们自己的spring xml文件:applicationContext-user.xml】,其中mybatis和spring集成的下面属性配置很重要:<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"></bean>,下面有相应注解

<?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-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 操作User类的spring配置文件 -->
    <!-- 配置User中的Dao类,使mybaties能够配置User与数据库打交道 -->
    <!-- 能够映射User.xml文件-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.mss.user.dao" />
	</bean>
	<!-- 配置userService,注意 userDao名称要与UserServiceImpl中的UserDao属性名称一样-->
	<bean id="userService" class="com.mss.user.serviceImpl.UserServiceImpl">
		<property name="userDao" ref="userDao" />
	</bean>
	<!-- 配置Action,注意userService名称要与UserAction中的UserService属性名称一样 -->
	<bean id="userAction" class="com.mss.user.action.UserAction">
		<property name="userService" ref="userService" />
	</bean>

</beans>

【配置自己的Struts xml: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="user" extends="struts-default" namespace="/">
	  	<action name="userAction" class="userAction">
	  	    <result name="success">success.jsp</result>
	  	    <result name="error">error.jsp</result>
	  	    <result name="list">UserList.jsp</result>
	  	</action>
	</package>
</struts>

【项目中我们用到了log4j,配置log4j.properties】

技术分享

项目的基础配置基本完成,编写我们的视图层,上面Action中我们跳转到了UserList.jsp,编写我们的jsp显示页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
	<c:forEach items="${list}" var="s">
		<tr>
			<td><c:out value="${s.userName}"></c:out></td>
			<td><c:out value="${s.password}"></c:out></td>
			<td><c:out value="${s.email}"></c:out></td>
			<td><a href="userAction!delUser.do?id=${s.id}">删除记录</a></td>
		</tr><br>
	</c:forEach>
</table>
</body>
</html>

好了,基础环境基本上已经搭建完成,将项目部署到Tomcat上,启动Tom家的猫,如果没报错,说明我们项目搭建成功,输入下面地址:http://localhost:8080/MybatiesSS/userAction!queryUsers.do,如果数据库中没有数据,则加入相应数据,如果显示出相应的数据库记录,说明我们项目搭建成功!
技术分享

相比较hibernate来说:

hibernate:要编写实体类和实体类相映射数据库表的xml文件,然后操作数据库使用hibernate封装的java类接口

mybatis:编写实体类、实体类相映射数据库表的xml文件、对数据方法操作xml文件,其对数据库的操作也在xml文件中定义,基本上使用的是纯sql语句

mybatis是半自动的,hibernate是全自动的,就是说mybatis可以配置sql语句,对于sql调优来说是比较好的,hibernate会自动生成所有的sql语句,调优不方便,hibernate用起来难度要大于mybatis。mybatis的主要思想是sql Mapping,而hibernate是OR Mapping,mybatis应用到项目中会比较直观一点,能直接看到sql,而hibernate是通过操作对象操作数据,可以很灵活的运用于不同的数据库之间

要比较hibernate与mybatis的区别,大家还可以参考博客:http://blog.csdn.net/firejuly/article/details/8190229

上面只是粗略的讲解了一下mybatis与Spring和struts的项目整合,并没有对mybatis有很详细的讲解,其实它学起来也挺容易的,希望大家有时间能自己去了解一下!!

手动配置三大框架整合:Spring+Struts2+mybatis

标签:

原文地址:http://blog.csdn.net/harderxin/article/details/42121289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!