• Java

struts2 + spring + mybatis 框架整合

在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=0
 maxActive=20
 maxIdle=20
 minIdle=1
 maxWait=60000

在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;
 
     private Integer active; 32     
     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


最新