在Eclipse下基于Maven整合Struts2,Spring和Mybatis3框架。

新建Maven project,type选择webapp

工程目录如下

修改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</groupId>
     <artifactId>javaweb</artifactId>
     <packaging>war</packaging>
     <version>0.0.1-SNAPSHOT</version>
     <name>javaweb Maven Webapp</name>
     <url>http://maven.apache.org</url>

     <properties>
         <struts.version>2.3.28</struts.version>
         <spring.version>3.0.5.RELEASE</spring.version>
         <mybatis.version>3.2.6</mybatis.version>
         <log4j.version>1.2.17</log4j.version>
     </properties>

     <dependencies>

         <!-- struts包 -->
         <dependency>
             <groupId>org.apache.struts</groupId>
             <artifactId>struts2-core</artifactId>
             <version>${struts.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.struts</groupId>
             <artifactId>struts2-spring-plugin</artifactId>
             <version>${struts.version}</version>
         </dependency>

         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-jdbc</artifactId>
             <version>${spring.version}</version>
         </dependency>

         <!-- mybatis核心包 -->
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
             <version>${mybatis.version}</version>
         </dependency>

         <!-- mybatis-spring包 -->
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis-spring</artifactId>
             <version>1.2.2</version>
         </dependency>

         <!-- java ee 包 -->
         <dependency>
             <groupId>javax</groupId>
             <artifactId>javaee-api</artifactId>
             <version>7.0</version>
         </dependency>

         <!-- Mysql数据库链接jar包 -->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.30</version>
         </dependency>
         <dependency>
             <groupId>commons-dbcp</groupId>
             <artifactId>commons-dbcp</artifactId>
             <version>1.2.2</version>
         </dependency>

         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>3.8.1</version>
             <scope>test</scope>
         </dependency>
     </dependencies>

     <build>
         <finalName>javaweb</finalName>
     </build>
 </project>

在resources目录下添加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"
     xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

     <!-- 配置要扫描的包 -->
     <context:component-scan base-package="action"></context:component-scan>
     <context:component-scan base-package="service.impl"></context:component-scan>  

     <!-- 指定数据源配置文件 -->
     <context:property-placeholder location="classpath:jdbc.properties" />

     <!-- 数据源 -->
     <bean id="dataSource_dev" class="org.apache.commons.dbcp.BasicDataSource"
         destroy-method="close">
         <property name="driverClassName" value="${driver}" />
         <property name="url" value="${url}" />
         <property name="username" value="${username}" />
         <property name="password" value="${password}" />
     </bean>

     <!-- 配置sqlSessionFactory -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="dataSource_dev" />
         <property name="mapperLocations" value="classpath:mapper/*.xml" />
     </bean>

     <!-- 指定DAO层 -->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <property name="basePackage" value="dao" />
         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
     </bean>

     <!-- 使用Spring的事务管理器 -->
     <bean id="transactionManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource_dev" />
     </bean>

 </beans>

在resources目录下添加配置文件jdbc.properties:

 # JDBC Configuration
 driver=com.mysql.jdbc.Driver
 url=jdbc:mysql://localhost:3306/web
 username=root
 password=password

 # DBCP Pool settings
 initialSize=
 maxActive=
 maxIdle=
 minIdle=
 maxWait=

在resources目录下添加struts配置文件struts.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>
     <!-- 指定默认编码集 -->
     <constant name="struts.i18n.encoding" value="UTF-8" />

     <constant name="struts.multipart.maxSize" value="99000000" />
     <constant name="struts.multipart.saveDir" value="/tmp"/>

     <!-- 当struts配置文件修改时是否自动加载 -->
     <constant name="struts.configuration.xmlreload" value="true" />

     <!-- 开发模式下打印详细的错误信息 -->
     <constant name="struts.devMode" value="true" />

     <constant name="struts.ui.theme" value="xhtml" />

     <include file="User.xml"></include>

 </struts>    

在resources目录下添加mybatis配置文件mybatis-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>
     <settings>
         <setting name="cacheEnabled" value="true"/>
         <setting name="lazyLoadingEnabled" value="true"/>
         <setting name="aggressiveLazyLoading" value="true"/>
     </settings>

     <typeAliases>

     </typeAliases>

 </configuration>

在web.xml中添加如下配置:

 <!-- spring的配置文件位置 -->
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext.xml</param-value>
     </context-param>

     <!-- 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>

     <!-- 集成spring -->
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>

在工程中添加如下类:

代码如下:

 package action;

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.List;

 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletResponse;

 import org.apache.struts2.ServletActionContext;
 import org.springframework.context.annotation.Scope;
 import org.springframework.stereotype.Controller;

 import com.opensymphony.xwork2.ActionSupport;
 import beans.User;
 import service.IUserService;

 @Controller
 @Scope("prototype")
 public class UserAction extends ActionSupport {

     private static final long serialVersionUID = 1L;

     @Resource
     private IUserService userService;

     private User user;

     private List<User> userlist;

     public User getUser() {
         return user;
     }

     public void setUser(User user) {
         this.user = user;
     }

     public List<User> getUserlist() {
         return userlist;
     }

     public void setUserlist(List<User> userlist) {
         this.userlist = userlist;
     }

     public String execute() throws Exception {
         System.out.println("execute");
         return SUCCESS;
     }

     public String addUser() {
         userService.addUser(user);
         return SUCCESS;
     }

     public String deleteUser() {
         userService.deleteUser(user.getId());
         return SUCCESS;
     }

     public String queryAllUser() {
         userlist = userService.queryAllUser();
         return "list";
     }

     public void validate() {
         System.out.println("validate()会对action中的所有方法进行校验");
 //        if(this.user.getName() == null || this.user.getName().trim().equals("")) {
 //            this.addFieldError("name", "用户名不能为空!");
 //        }
     } 

     //直接返回一个字符串
     public String queryUserNameByID() throws IOException{
         HttpServletResponse response = ServletActionContext.getResponse();
         response.setContentType("text/html;charset=UTF-8");
         //response.sendError(401,"timeout");
         PrintWriter out = response.getWriter();
         out.println("luangeng123");//返回的字符串数据
         out.flush();
         out.close();
         return null;
     }

 }
 package beans;

 import java.sql.Date;

 public class User {
     private Integer id;

     private String name;

     private String pwd;

     private String sex;

     private Integer age;

     private String email;

     private String phone;

     private Date register_time;

     private Date last_update_time;

     private String remark;

     public User(String name, String pwd, String email, String phone){
         this.name = name;
         this.pwd = pwd;
         this.email = email;
         this.phone = phone;
     }

     public Integer getId() {
         return id;
     }

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

IUserDao

 package dao;

 import java.util.List;

 import org.apache.ibatis.annotations.Delete;
 import org.apache.ibatis.annotations.Select;

 import beans.User;

 public interface IUserDao {

     public void addUser(User user);

     @Delete("delete from f_user_t where id=#{id}")
     public void delUser(Integer userId);

     @Select("select * from f_user_t where id=#{id")
     public User queryUserById(Integer userId);

     @Select("select * from f_user_t")
     public List<User> queryAll();

 }

mapper中的User.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="dao.IUserDao">

    <resultMap type="beans.User" id="userResult">
        <result property="id" column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
        <result property="username" column="username" />
        <result property="password" column="password" />
    </resultMap>

    <insert id="insertUser" parameterType="beans.User">
     insert into f_user_t
    (name,pwd,sex,age,email,phone,register_time,last_update_time,remark,active)
    values
    (#{name},#{pwd},#{sex},#{age},#{email},#{phone},now(),now(),#{remark},#{active})
     </insert>

</mapper>
 package service;

 import java.util.List;
 import beans.User;

 public interface IUserService {

     public abstract void addUser(User user);

     public abstract void deleteUser(Integer userId);

     public abstract User queryUserById(Integer userId);

     public abstract List<User> queryAllUser();

 }
 package service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;

 import dao.IUserDao;
 import beans.User;
 import service.IUserService;

 @Service
 @Transactional
 public class UserService implements IUserService {

     @Autowired
     private IUserDao userDao;

     public void addUser(User user) {
         userDao.addUser(user);
     }

     public void deleteUser(Integer userId) {
         userDao.delUser(userId);
     }

     public User queryUserById(Integer userId) {
         return userDao.queryUserById(userId);
     }

     public List<User> queryAllUser() {
         return userDao.queryAll();
     }

 }

struts的User.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="user" namespace="/user" extends="struts-default">
     <action name="*" class="userAction" method="{1}">
         <result name="success" type="redirectAction">queryAllUser</result>
         <result name="error">/error.jsp</result>
         <result name="list">/list.jsp</result>
         <result name="input">/error.jsp</result>
     </action>

 </package>

 </struts>

list.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 <%@ taglib prefix="s"  uri="/struts-tags"%>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
   <head>

     <title>用户列表</title>

     <meta http-equiv="pragma" content="no-cache">
     <meta http-equiv="cache-control" content="no-cache">
     <meta http-equiv="expires" content="0">   

   </head>

   <body>
     <center>
         <h2>用户列表</h2>
         <h3><s:a action="toadd" namespace="/user">添加新用户</s:a> </h3>

         <table width="90%" border="1">
             <tr>
                 <th>用户id</th>
                 <th>用户名称</th>
                 <th>用户密码</th>
                 <th>age</th>
                 <th>email</th>
                 <th>sex</th>
                 <th>phone</th>
                 <th>remark</th>
                 <th>操作</th>
             </tr>
             <s:iterator value="userlist">
                 <tr>
                     <td><s:property value="id"/> </td>
                     <td><s:property value="name"/> </td>
                     <td><s:property value="pwd"/> </td>
                     <td><s:property value="age"/> </td>
                     <td><s:property value="email"/> </td>
                     <td><s:property value="sex"/> </td>
                     <td><s:property value="phone"/> </td>
                     <td><s:property value="remark"/> </td>
                     <td>
                     <s:a action="toupdate" namespace="/user">
                     <s:param name="user.id" value="id"/>修改
                     </s:a>
                     &nbsp;&nbsp;
                     <s:a action="delete" namespace="/user">
                     <s:param name="user.id" value="id"/>删除
                     </s:a>
                     </td>
                 </tr>
             </s:iterator>
         </table>
     </center>
   </body>
 </html>

启动mysql,创建数据库web,创建表f_user_t, 插入数据:

启动Tomcat,访问 http://localhost:8080/javaweb/user/queryAllUser

end

struts2 + spring + mybatis 框架整合的更多相关文章

  1. SSM框架-----------SpringMVC+Spring+Mybatis框架整合详细教程

    1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One  ...

  2. Struts2+Spring+Hibernate框架整合总结详细教程

    一.SSH三大框架知识总结 Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架.其全新的Struts 2的体系结构与S ...

  3. 【整理】JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系

    #[整理]JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系 ![关系图解](http://images.cnitblog.com/blog/84 ...

  4. SSH(Struts2+Spring+Hibernate)框架搭建流程&lt;注解的方式创建Bean&gt;

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  5. 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...

  6. Spring+MyBatis框架中sql语句的书写,数据集的传递以及多表关联查询

    在很多Java EE项目中,Spring+MyBatis框架经常被用到,项目搭建在这里不再赘述,现在要将的是如何在项目中书写,增删改查的语句,如何操作数据库,以及后台如何获取数据,如何进行关联查询,以 ...

  7. Struts2+Spring+Mybatis+Junit 测试

    Struts2+Spring+Mybatis+Junit 测试 博客分类: HtmlUnit Junit Spring 测试 Mybatis  package com.action.kioskmoni ...

  8. struts2 spring mybatis 整合(test)

    这几天搭了个spring+struts2+mybatis的架子,练练手,顺便熟悉熟悉struts2. 环境:myEclipse10+tomcat7+jdk1.6(1.8的jre报错,所以换成了1.6) ...

  9. 框架整合——Spring与MyBatis框架整合

    Spring整合MyBatis 1. 整合 Spring [整合目标:在spring的配置文件中配置SqlSessionFactory以及让mybatis用上spring的声明式事务] 1). 加入 ...

随机推荐

  1. CentOS 7 安装 nginx

    一.安装nginx依赖lib库: 1.yum install gcc-c++ -y 2.yum install pcre pcre-devel -y 3.yum install zlib zlib-d ...

  2. icon-font与svg

    icon font 使用与svg应用分享 icon font 字体概述 css3增加了@font-face属性,传统的浏览器是通过font-family来设置字体,如果系统里没有的话就用其它字体来代替 ...

  3. 反人类的MyEclipse之-调整JavaScript代码-花括号换行显示

    然后将除最后一项外所有的都勾选为Next Line

  4. [ASM C/C++] C makefile:2: *** missing separator. Stop. 问题

    在利用make编译代码时,makefile文件的目标代码前面要用tab而不能用空格来代替. 要不然就会提示: makefile:2: *** missing separator.  Stop. 要注意 ...

  5. nginx rewrite 指令last break区别最详细的解释

    转自:http://blog.sina.com.cn/s/blog_4f9fc6e10102ux0w.html http://blog.cafeneko.info/2010/10/nginx_rewr ...

  6. 使用ThreadSanitizer线程检查工具

    ThreadSanitizer又叫TSan,是一个检查线程Data Race的C/C++工具.它集成在新版的gcc和clang中,通过编译时加-fsanitize=thread,可以在运行时检测出Da ...

  7. Leetcode 202 Happy Number 弗洛伊德判环解循环

    今天先谈下弗洛伊德判环,弗洛伊德判环原来是在一个圈内有两人跑步,同时起跑,一人的速度是另一人的两倍,则那个人能在下一圈追上另一个人,弗洛伊德判环能解数字会循环出现的题,比如说判断一个链表是不是循环链表 ...

  8. 怎么设置task的最大线程数

    //-------------------------------------------------------------------------- // // Copyright (c) Mic ...

  9. MySQL数据很大的时候

    众所周知,mysql在数据量很大的时候查询的效率是很低的,因为假如你需要 OFFSET 100000 LIMIT 5 这样的数据,数据库就需要跳过前100000条数据,才能返回给你你需要的5条数据.由 ...

  10. python numpy sum函数用法

    numpy.sum numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)[source] Sum of array element ...