struts2 spring mybatis 整合(test)

這幾天搭了個spring+struts2+mybatis的架子,練練手,順便熟悉熟悉struts2.html

環境:myEclipse10+tomcat7+jdk1.6(1.8的jre報錯,因此換成了1.6).java

框架:spring+struts2+mybatis。mysql

 

前言:git

1.spring+mybatis的配置同    spring  MVC ;github

2.惟一要注意的是strtus2和spring的整合(spring中的bean注入到action中,網上各類講解,但都相對於各自的項目,因此,新入手struts2的時候仍是要本身耐心體驗);web

3.因爲struts2自己存在bug,且相比較spring MVC沒有什麼優點,因此,年輕的項目基本不會選擇strtus2,我使用他純屬偶然,若看客是以較功利的目的學習框架的話,不建議學習看本章博客。spring

 

如下,爲框架:sql

一.   首先是jar包,這個比較煩人(相對於我的而言,企業都有整套的jar包),數據庫

如下爲本人使用的jar包(因爲公司不使用struts2,因此雖然我借鑑了前人的博客,但仍是被jar包衝突狠狠的折磨了一番):apache

 

其中,commons-fileupload,commons.io,commons.lang3,freemarker,javassist,ognl,spring-strtus,struts2-core,struts2-spring-plugin,xwork-core爲與struts2相關的jar包,注意,aopalliance,aspectjrt要增長。

至於每一個jar包的做用請自行百度(請原諒我和部分jar包不熟的不負責任的態度)。

二.  層級

傳統的企業級的項目,因爲考慮到擴展性,會將service分拆爲service接口,和serviceImple實現類,

我屬於玩票性質,因此直接忽略了service層(圖片裏的service並無使用,可忽略),直接將在action中使用mapper(框架是死的,活學活用最重要(請原諒我給本身的懶惰找藉口))。

 

新人這裏要注意src/Resources這個文件夾,這是資源文件夾,能夠隨意設置,

右擊項目,選擇Build Path  選擇Configure  Build Path自行設置(不懂請百度)。

 

接着是web.xml,application-common.xml,mybatis.xml,struts.xml,log4j.xml,以下:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name>    
        <!-- 對Spring容器進行實例化 -->
    

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-common.xml</param-value>
    </context-param>

        <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <!-- 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>
   
   
   
   
   
   
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

application-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:context="http://www.springframework.org/schema/context"
    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-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
<!-- 數據庫鏈接 屬性   博客:http://blog.itpub.net/7971010/viewspace-1114524 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"/>
        <!--  <property name="password" value="${jdbc.mysql.password}"/> -->
        <property name="connectionProperties" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db_database24"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="5"/>
        <property name="maxWait" value="60000"/>
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <property name="validationQuery" value="SELECT 'x'"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="stat"/>
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property  name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath*:main/java/com/zq/mapper/*.xml"/>
    </bean>
    
    <bean   class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="main.java.com.zq.dao"/>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- proxy-target-class  意思  博客:http://blog.csdn.net/z69183787/article/details/17161297 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="100" />

    <context:component-scan base-package="main.java.com.zq"/>
    <context:annotation-config />
    


    
    <!--  面向切面編程使用 :博客:http://kld208.iteye.com/blog/1632935 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />
</beans>

 

 

mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties>
        <property name="dialect" value=""/>

    </properties>
    
        <typeAliases>  
        <typeAlias alias="user" type="main.java.com.zq.model.User"/>  
    </typeAliases>  
     


</configuration>

 

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>


<!-- 指定以name的方式組合action和service的關係          
        <constant name="struts.objectFactory.spring.autoWire" value="name"></constant>  
-->  
        <package name="shop.admin" namespace="/admin" extends="struts-default">

        <action name="loginAction" class="loginAction" method="Login">
            <result name="SUCCESS">/WEB-INF/login.jsp</result>
        </action>
    </package>
</struts>

 

log4j.xml:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=debug, stdout

log4j.logger.java.sql.PreparedStatement=debug

 

文件夾struts請忽略,這裏是爲了分寫struts接口時使用的,但我只寫了一個接口,因此,就只能呵呵了····

如下問代碼部分:

LoginAction.java

package main.java.com.zq.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import main.java.com.zq.dao.LoginMapper;
import main.java.com.zq.model.User;
import main.java.com.zq.service.LoginService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Scope("prototype")
@Controller("loginAction")
public class LoginAction extends ActionSupport implements ModelDriven<User> {
    Logger logger=Logger.getLogger(LoginAction.class);

    
    @Autowired
    private LoginMapper loginMapper;
    
    private static final long serialVersionUID = 1L;
    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    private User user=new User();
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user=user;
    }

    public void setLoginMapper(LoginMapper loginMapper) {
        this.loginMapper = loginMapper;
    }
    public String Login(){
        Map<Object, Object> map=new HashMap<Object, Object>();
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());
        System.out.println(map.toString());
        logger.debug(map.toString());
        Map<?, ?> resultMap=loginMapper.login(map);
        if(resultMap.get("password").equals(user.getPassword())){
            return "SUCCESS";
        }else {
            return SUCCESS;
        }
    }

}

 

LoginMapper.java:

package main.java.com.zq.dao;

import java.util.Map;

import org.springframework.stereotype.Repository;


public interface LoginMapper {
    Map login(Map map);
    

}

 

 

LoginMapper.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="main.java.com.zq.dao.LoginMapper">
<select id="login" parameterType="map" resultType="map">
    SELECT * from tb_user where username=#{username} limit 1
</select>
        
        
        
        
        
</mapper>

 

User.java:

package main.java.com.zq.model;

import java.io.Serializable;

/**
 * 
 * @author Sean
 *
 */
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    
    private String username;

    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;
    }

    private String password;
    
}

 

Test.java(這是我測試用的,建議堅持使用測試類,不管你偷懶直接建Test類仍是使用junit,Test能在你不知道哪裏出錯的時候一步一步調試,讓你有跡可循):

package main.java.com.zq.utils;

import java.util.HashMap;
import java.util.Map;

import main.java.com.zq.action.LoginAction;
import main.java.com.zq.dao.LoginMapper;
import main.java.com.zq.model.User;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String [] args){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-common.xml");
        
        System.out.println(context.getBean("dataSource").toString());
        
     LoginMapper loginMapper=
        (LoginMapper) context.getBean("loginMapper");
     
     Map map=new HashMap();
     map.put("username", "admin");
     System.out.println(loginMapper.login(map));
     
     
     LoginAction loginAction=(LoginAction) context.getBean("loginAction");
     User user=new User();
     user.setPassword("adine");
     user.setUsername("admin");
     loginAction.setUser(user);
     
     System.out.println(loginAction.Login().toString());

        

    }

}

 

 

 

 jsp部分只有一個表單,其餘什麼都沒有,不喜歡jsp,html萬歲!

github:https://github.com/zhouqia/spring-mybatis-struts2.git

 能夠直接克隆,裏面的代碼不能夠直接用,但都有,那些想直接拉下來跑的,我就呵呵了,多動手少年。

 

 

以上。

爲所有代碼。

若是能夠輕鬆搭建,建議能夠看綠考慮    strtus2的過濾器和mybatis的插件的原理,你會發現都是使用動態代理實現的,

並且,你能夠考慮考慮,他們使用的動態代理究竟是環形的,仍是直線形的。

 

 

最討厭又臭又長的文章,之後寫博客,要儘可能精簡。

相關文章
相關標籤/搜索