首页 > 代码库 > 【Struts2】如何实现Struts2与Spring的整合 外加 MyBatis 框架

【Struts2】如何实现Struts2与Spring的整合 外加 MyBatis 框架

1,简介

一般没有人会用Spring+Struts2+MyBatis这样的框架了,可不能简称为SSM。因为SSM是Spring+SpringMVC+Mybatis的简称。SSH是Spring+Struts2+Hibernate,不过现在SSH用的人也不多了。这里笔者把Sping+Struts2+Mybatis放在一起就是纯粹的实现一下功能。主要讨论的还是Struts2和Spring。

如果不使用Spring框架,Struts2框架内部还是有机制可以利用反射创建对象,之所以要把Spring+Struts2结合起来,除了体现和依赖Spring中IOC(控制反转),还有就是他的AOP(面向切面编程),这两点都是非常强大的。也就是说,使用了Spring+Struts2之后,之前由Struts2创建对象的功能交给了Spring容器来实现了。而Struts2替换了Spring中的mvc部分。因此在Spring容器进行配置的时候,就不应该再进行配置Spring-webmvc部分了。

2,实现部署Spring+Struts2+Mybatis框架

看一下项目的结构:

技术分享

首先就是导入jar包,struts2的jar包,Spring容器的jar包,Mybatis的jar包,以及struts2和Spring的整合包,Spring和Mybatis的整合包,这里笔者使用的数据库是MySQL,因此还有MySQL的驱动包和连接池包。

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <display-name>springStruts2Mybatis</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>  </welcome-file-list>  <filter>    <filter-name>struts</filter-name>    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>struts</filter-name>    <url-pattern>*</url-pattern>  </filter-mapping>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <listener>    <listener-class>      org.springframework.web.context.ContextLoaderListener      </listener-class>  </listener></web-app>
web.xml 文件

其中下面这段代码:

  <filter>    <filter-name>struts</filter-name>    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>struts</filter-name>    <url-pattern>*</url-pattern>  </filter-mapping>

就是将Struts2框架配置到web容器中。然后下面这一段:

  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <listener>    <listener-class>      org.springframework.web.context.ContextLoaderListener      </listener-class>  </listener>

就是把Spring配置到容器中去。这样的话,当随着容器启动,struts2和spring的xml文档对象就创建好了。

struts.xml文件

技术分享
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"    "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts>      <!--Struts默认只会通过.action和无后缀的请求,我们可以通过指定extension来使得Struts只通过.do的URL的请求。-->      <constant name="struts.action.extension" value="do"/>          <!-- 必须继承struts-default,才能使用Result组件 -->    <package name="user" extends="struts-default">        <!--这里的class就是Spring容器中的bean的id-->        <action name="userlogin" class="userAction">            <!-- name对应action返回值;type指定Result 类型 -->            <result name="result" type="dispatcher">loginResult.jsp</result>        </action>    </package></struts>
struts.xml

其中action节点的class值应该是spring容器中bean对象的id值。

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"     xmlns:jdbc="http://www.springframework.org/schema/jdbc"      xmlns:jee="http://www.springframework.org/schema/jee"     xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:util="http://www.springframework.org/schema/util"    xmlns:jpa="http://www.springframework.org/schema/data/jpa"    xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">        <!--             开启注解扫描         -->            <context:component-scan base-package="cn"></context:component-scan>          <bean id="config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    <property name="locations">      <list>        <value>classpath:db-config.properties</value>      </list>  </property>  </bean>   <!-- 获取数据源 -->  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">    <property name="url">      <value>${db.url}</value>    </property>    <property name="username">      <value>${db.username}</value>    </property>    <property name="password">      <value>${db.password}</value>    </property>     <property name="driverClassName">      <value>${db.dirverClass}</value>    </property>  </bean>    <!--把服务层配置到容器中-->        <bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="configLocation" value="classpath:sqlmap-config.xml"></property>        <property name="dataSource" ref="dataSource"></property>    </bean>           <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="sqlSessionFactoryBeanName" value="ssf"></property>        <property name="basePackage" value="cn.shop.dao"></property>   </bean>         </beans>
applicationContext.xml

在个是文档是spring的,由于struts2充当了spring webmvc的角色,因此在本文档不应该配置任何有关mvc的部分。

db-config.properties文件

技术分享
db.dirverClass=com.mysql.cj.jdbc.Driverdb.url=jdbc:mysql:///test?characterEncoding=utf8&useSSL=true&serverTimezone=GMTdb.password=517839db.username=root
db-config.properties

UserAction.java文件

技术分享
package cn.shop.action;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import cn.shop.bean.UserInfo;import cn.shop.dao.UserMapper;import cn.shop.service.UserService;@Controllerpublic class UserAction {        @Resource    private UserService userService;        private String username;//接受参数    private String password;//接受参数    private String message;//传出参数        public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }    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 execute(){        UserInfo userinfo=userService.userlogin(username, password);        if(userinfo!=null){            message="登录成功";        }else{            message="登录失败";        }                return "result";    }}
UserAction.java

UserInfo.java文件

技术分享
package cn.shop.bean;public class UserInfo {    private int userid;    private String username;    private String password;                public UserInfo() {        super();    }    public UserInfo(int userid, String username, String password) {        super();        this.userid = userid;        this.username = username;        this.password = password;    }    public int getUserid() {        return userid;    }    public void setUserid(int userid) {        this.userid = userid;    }    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;    }    }
UserInfo.java

UserMapper.java文件

技术分享
package cn.shop.dao;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import cn.shop.bean.UserInfo;public interface UserMapper {        UserInfo findUserByNameAndPass(@Param("name")String name,@Param("upass")String pass);}
UserMapper.java

UserService.java文件

技术分享
package cn.shop.service;import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.shop.bean.UserInfo;import cn.shop.dao.UserMapper;@Servicepublic class UserService {        @Resource    private UserMapper userMapper;        public UserInfo userlogin(String username,String password){        return userMapper.findUserByNameAndPass(username, password);    }}
UserService.java

UserMapper.xml文件

技术分享
<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"       "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"><mapper namespace="cn.shop.dao.UserMapper">    <!-- 查询操作-->    <select id="findUserByNameAndPass" resultType="cn.shop.bean.UserInfo">        select * from userinfo where username =#{name} and password=#{upass};    </select></mapper>
UserMapper.xml

sqlmap-config.xml文件

技术分享
<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE configuration             PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"            "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"><configuration>    <!-- 加载SQL定义文件 -->    <mappers>        <mapper resource="cn/shop/sql/UserMapper.xml" />    </mappers></configuration>
sqlmap-config.xml文件

login.jsp文件

技术分享
<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!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>用户登录</title></head><body><form action="userlogin.do" method="POST" >用户名:<input type="text" name="username"/> <br/>密码:<input type="password" name="password"/> <br/><input type="submit" value="http://www.mamicode.com/提交" /></form></body></html>
login.jsp

loginResult.jsp文件

技术分享
<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!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>用户登录</title></head><body>登录结果是:${message }</body></html>
loginResult.jsp

 

然后这里笔者说一说整体的配置思路,就是先配送Spring+Struts2部分,然后再配置Spring+Mybatis部分,最后将三者联系起来就可以了。在配置的时候需要测试的,特别是在,mybatis和spring容器部分,因此这些部分的内容应该在配置过程中进行测试。

当Mabatis单个部分配置完成后,我们可以通过如下的代码检查是否有Bug.

         SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();           Reader reader = Resources.getResourceAsReader("sqlmap-config.xml");           SqlSessionFactory factory = builder.build(reader);           SqlSession session = factory.openSession();
UserMapper usermapper
= session.getMapper(UserMapper.class); UserInfo userinfos=usermapper.findUserByNameAndPass("jame","123456"); System.out.println(userinfos.getPassword());

这里笔者就用上面的代码举例了。还有,就是关于Mybatis部分,可以参见Mybatis如何配置

如果没有问题了,我们就把和Spring容器整合。对spring进行检查,这里笔者拷贝一段测试上面Spring容器的部分代码

          ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");            SqlSessionFactory factory = ac.getBean("ssf",SqlSessionFactory.class);            SqlSession session = factory.openSession();            UserMapper usermapper= session.getMapper(UserMapper.class);            UserInfo userinfos=usermapper.findUserByNameAndPass("jame","123456");            System.out.println(userinfos.getPassword());

看完了测试的代码,在测试XML过程中都是根据XML文件创建文档对象,然后通过文档对象调用其中的方法,只不过spring和mybatis的语法不同而已。

 

【Struts2】如何实现Struts2与Spring的整合 外加 MyBatis 框架