SSH组合之Spring3整合Struts2

1、Add Spring Capabilities

2、Add struts2 Capabilities+对应版本的struts2-spring-plugin-2.2.1.jar,最好是对应版本

3、struts.xml

(1) 配置为Spring

(2) 配置Action;

 <action name="*_cat" method="{1}" class="catAction">

这里class 的”catAction“需要在applicationContext.xml配置才能找到真正的class;

action类不需要继承ActionSupport,只需要有对应每个Action名称的方法;

可以在action类有相关的变量,需要get-set函数;

如果action类需要使用Dao层,则dao变量需要声明

    <!-- struts2的Action -->
    <!-- scope默认为singleston,这里一定要设置 成prototype。这样浏览器每次请求一次,spring都会生成一个新的Action对象-->
    <bean id="catAction" scope="prototype" class="com.cat.action.CatAction">
    <property name="catService" ref="catService"></property>
    </bean>
        <!-- 配置Dao -->
    <bean id="catService" class="com.cat.service.catDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

 

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.objectFactory" value="spring" /><!-- 配置为Spring,表该Action由Spring产生 -->
    <constant name="struts.devMode" value="true" /> <!-- 是否开发模式 -->

    <package name="cat" extends="struts-default">
        <!--<global-results>
            <result name="exception">/exception.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping result="exception" exception="java.lang.Exception"></exception-mapping>
        </global-exception-mappings>-->

        <action name="*_cat" method="{1}" class="catAction">
            <param name="action">{1}</param>
            <result>/list.jsp</result>
            <result name="list">list.jsp</result>
        </action>
    </package>
</struts>    

 

4、CatAction.java

package com.cat.action;

import java.util.ArrayList;
import java.util.List;

import com.cat.bean.Cat;
import com.cat.service.ICatService;

public class CatAction {

    private ICatService catService;
    private Cat cat;
    private List<Cat> catList=new ArrayList<Cat>();
    
    public String add(){
        catService.createCat(cat);
        return list();
    }
    public String list(){
        catList=catService.listCats();
        return "list";
    }
    public ICatService getCatService() {
        return catService;
    }
    public void setCatService(ICatService catService) {
        this.catService = catService;
    }
    public Cat getCat() {
        return cat;
    }
    public void setCat(Cat cat) {
        this.cat = cat;
    }
    public List<Cat> getCatList() {
        return catList;
    }
    public void setCatList(List<Cat> catList) {
        this.catList = catList;
    }
    
    
}

 

Done!

SSH组合之Spring3整合Struts2,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。