在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. 【Linux】虚拟机安装Archlinux

    参考:https://wiki.archlinux.org/index.php/Installation_guide_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87) 安装 ...

  2. window 和 linux 环境下杀死tomcat进程——也可以解决其他端口被占用的问题

    1.应用场景 在Windows或者linux操作系统中,我们在启动一个tomcat服务器时,经常会发现8080端口已经被占用的错误,而我们又不知道如何停止这个tomcat服务器. 2.window环境 ...

  3. TCP中的RST复位信号

    TCP中的RST复位信号 在TCP协议中RST表示复位,用来关闭异常的连接,在TCP的设计中它是不可或缺的. 发送RST包关闭连接时,不必等缓冲区的包都发出去,直接就丢弃缓存区的包发送RST包.而接收 ...

  4. CDN系统对网站的性能有极大的提升

    CDN系统对网站的性能有极大的提升 打开一个网站 我们只是请求了一个页面.单个页面,实际上所有文件都是一个新的请求.以新浪为例一共发起了35个请求. 这35个请求中.只有一个动态内容.其它均为静态.这 ...

  5. qt5.4

    rm -f libQt5Qml.so.5.4.0 libQt5Qml.so libQt5Qml.so.5 libQt5Qml.so.5.4g++ -Wl,-O1,--sort-common,--as- ...

  6. fork详解

    [本文链接] http://www.cnblogs.com/hellogiser/p/fork.html [代码] 下面的代码输出多少个-?  C++ Code  123456789101112131 ...

  7. Print all nodes at distance k from a given node

    Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes t ...

  8. call(),apply(),bind()与回调

    1.call(),apply(),bind()方法 JavaScript 中通过call或者apply用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定 ...

  9. jdbc无法连接数据解析

    1.网络原因 2.账户权限问题 账户是否赋予以下的权限: grant connect, resource to ADM_BI; grant read, write on directory BACKU ...

  10. php 5.6.14手动安装 php -v 显示没有安装

    奇怪了,今天利用源码手动php,安装成功后,利用php -v提示没有安装,which php也是有问题,php文件也没有办法执行 搞了半天,发现是没有添加环境变量,╮(╯▽╰)╭ 方法: 修改/etc ...