spring整合struts的三种方式(不错)

 方式一:使用 Spring 的 ActionSupport或DispachActionSupport 类整合 Structs

Action

package com.yz.actions.action;

import java.lang.reflect.InvocationTargetException;
import javax.servlet.http.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.*;
import org.springframework.web.struts.DispatchActionSupport;
import com.yz.services.*;
import com.yz.actions.form.*;
import com.yz.vo.UserVo;
//spring的action管理请求
public class UserAction extends DispatchActionSupport {
    //针对接口编程
    IUserServices ius;
    
    public IUserServices getIus() {
        return ius;
    }

    public void setIus(IUserServices ius) {
        this.ius = ius;
    }

    public ActionForward test(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        UserVo uv = new UserVo();
        try {
            BeanUtils.copyProperties(uv, userForm);
        } catch (Exception e) {
                e.printStackTrace();
        }
        /**//*IUserServices ius = new IUserServicesImpl();*/
        //通过父类的方法获取spring容器 并得到其中的bean对象
        ius =(IUserServices)super.getWebApplicationContext().getBean("ius");
        boolean add = ius.addUsers(uv);
        System.out.println(uv.getUserName());
        String url = "/error.jsp";
        if(add){
            url = "/ok.jsp";
        }
        System.out.println(url);
        return new ActionForward(url) ;
    }
}

自己写的请求处理器,处理中文乱码
package com.yz.myReq;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.RequestProcessor;

public class myReq extends RequestProcessor {


    @Override
    protected boolean processPreprocess(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return super.processPreprocess(request, response);
    }
}

struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="userForm" type="com.yz.actions.form.UserForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="userForm"
      name="userForm"
      path="/user"
      scope="request"
      type="com.yz.actions.action.UserAction" 
      parameter="actions"
   />
  </action-mappings>
  <controller processorClass="com.yz.myReq.myReq"></controller>
  <message-resources parameter="com.yz.actions.ApplicationResources" />
 <!-- 添加一个插件,用来在启动struts框架的时候,
      同时读取spring配置文件,启动spring容器 -->
  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
          <set-property property="contextConfigLocation" 
          value="/WEB-INF/applicationContext.xml"/>
 </plug-in>
</struts-config>


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:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    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.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    
    <bean id="userDaoImpl" class="com.yz.dao.impl.IuserDaoImpl"></bean>
<!-- action里面有一个ius(service的接口引用),
    他来自  com.yz.services.impl.IUserServicesImpl(指向接口的实现类)
    IUserServicesImpl里面有一个iud(IuserDao接口引用)
    他 ref id为 userDaoImpl(指向接口的实现类)   
    -->
    <bean id="ius" class="com.yz.services.impl.IUserServicesImpl">
        <property name="iud">
            <ref bean="userDaoImpl"/>
        </property>
    </bean>
</beans>

<!--
整合思路:
   1、通过从 Spring 的 ActionSupport或者DispachActionSuport 类而不是 Struts 的 Action 类进行扩展,创建了一个新的 Action,
   2、使用 getWebApplicationContext() 方法获得一个 ApplicationContext。为了获得spring容器上下文对象,从而查找一个 Spring bean。

优缺点:
      1、这种技术很简单并且易于理解。
      2、它将 Struts 动作与 Spring 框架耦合在一起。如果您想替换掉 Spring,那么您必须重写代码。并且,由于 Struts 动作不在 Spring 的控制之下,所以它不能获得 Spring AOP 的优势。当使用多重独立的 Spring 环境时,这种技术可能有用,但是在大多数情况下,这种方法不如另外两种方法合适。

-->

方式二:使用 Spring 的 DelegatingRequestProcessor 覆盖 Struts 的 RequestProcessor
Action
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.yz.actions.action;

import java.lang.reflect.InvocationTargetException;
import javax.servlet.http.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
import org.springframework.web.struts.DispatchActionSupport;

import com.yz.actions.form.UserForm;
import com.yz.services.IUserServices;
import com.yz.services.impl.IUserServicesImpl;
import com.yz.vo.UserVo;
//spring的action管理请求
public class UserAction extends DispatchAction {
    //针对接口编程
    IUserServices ius;
    
    public IUserServices getIus() {
        return ius;
    }

    public void setIus(IUserServices ius) {
        this.ius = ius;
    }

    public ActionForward test(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        UserVo uv = new UserVo();
        try {
            BeanUtils.copyProperties(uv, userForm);
        } catch (Exception e) {
                e.printStackTrace();
        }
       boolean add = ius.addUsers(uv);
        System.out.println(uv.getUserName());
        String url = "/error.jsp";
        if(add){
            url = "/ok.jsp";
        }
        System.out.println(url);
        return new ActionForward(url) ;
    }
}

继承自spring的请求处理器替换带哦struts的请求处理器,顺便处理编码问题。
package com.yz.myReq;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.struts.DelegatingRequestProcessor;
//spring的请求处理器

public class mySpringRequestProccessor extends DelegatingRequestProcessor {

    @Override
    protected boolean processPreprocess(HttpServletRequest req,
            HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        resp.setCharacterEncoding("utf-8");
        return super.processPreprocess(req, resp);
    }
}

struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="userForm" type="com.yz.actions.form.UserForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="userForm"
      name="userForm"
      path="/user"
      scope="request"
      type="com.yz.actions.action.UserAction" 
      parameter="actions"
   />
  </action-mappings>
  <!-- spring的请求处理器 自己写的类继承他,加了中文乱码处理 
  这样在actionservlet得到action的时候,就是从spring容器中去
      获取name和path匹配的对象 -->
  <controller processorClass="com.yz.myReq.mySpringRequestProccessor"></controller>
  <message-resources parameter="com.yz.actions.ApplicationResources" />
 <!-- 添加一个插件,用来在启动struts框架的时候,
      同时读取spring配置文件,启动spring容器 -->
  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
          <set-property property="contextConfigLocation" 
          value="/WEB-INF/applicationContext.xml"/>
 </plug-in>
</struts-config>

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:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    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.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    
    <bean id="userDaoImpl" class="com.yz.dao.impl.IuserDaoImpl"></bean>
<!-- action里面有一个ius(service的接口引用),
    他来自  com.yz.services.impl.IUserServicesImpl(指向接口的实现类)
    IUserServicesImpl里面有一个iud(IuserDao接口引用)
    他 ref id为 userDaoImpl(指向接口的实现类)  /user 
    -->
    <bean id="intfUs" class="com.yz.services.impl.IUserServicesImpl">
        <property name="iud">
            <ref bean="userDaoImpl"/>
        </property>
    </bean>
    
    <!-- name必须和action的path一致 -->
    <bean name="/user" class="com.yz.actions.action.UserAction">
        <property name="ius" ref="intfUs"></property>
    </bean>
</beans>

<!--
    整合思路:
       DelegatingRequestProcessor替换struts的请求处理器,根据struts配置的action中path属性与applicationContext.xml中配置的bean的name属性找到相应的action。
     优缺点:
        1、这种设计使 Struts 动作并不知道它正被 Spring 管理,并且使您能够利用 Sping 的动作管理框架的所有优点。由于您的 Struts 动作注意不到 Spring 的存在,所以您不需要重写您的 Struts 代码就可以使用其他控制反转容器来替换掉 Spring。
        2、DelegatingRequestProcessor 方法的确比第一种方法好,但是仍然存在一些问题。如果您使用一个不同的 RequestProcessor,则需要手动整合 Spring 的 DelegatingRequestProcessor。添加的代码会造成维护的麻烦并且将来会降低您的应用程序的灵活性。此外,还有过一些使用一系列命令来代替 Struts RequestProcessor 的传闻。 这种改变将会对这种解决方法的使用寿命造成负面的影响。


-->

方式三:将 Struts Action 管理委托给 Spring 框架,使用代理
Action

package com.yz.actions.action;

import java.lang.reflect.InvocationTargetException;
import javax.servlet.http.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
import org.springframework.web.struts.DispatchActionSupport;

import com.yz.actions.form.UserForm;
import com.yz.services.IUserServices;
import com.yz.services.impl.IUserServicesImpl;
import com.yz.vo.UserVo;
//spring的action管理请求
public class UserAction extends DispatchAction {
    //针对接口编程
    IUserServices ius;
    
    public IUserServices getIus() {
        return ius;
    }

    public void setIus(IUserServices ius) {
        this.ius = ius;
    }

    public ActionForward test(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        UserVo uv = new UserVo();
        try {
            BeanUtils.copyProperties(uv, userForm);
        } catch (Exception e) {
                e.printStackTrace();
        }
        boolean add = ius.addUsers(uv);
        System.out.println(uv.getUserName());
        String url = "/error.jsp";
        if(add){
            url = "/ok.jsp";
        }
        System.out.println(url);
        return new ActionForward(url) ;
    }
}

代理
package com.yz.myActionProxy;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.DelegatingActionProxy;


public class mySpringActionProxy extends DelegatingActionProxy {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            ServletRequest req, ServletResponse resp) throws Exception {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        return super.execute(mapping, form, request, response);
    }
}

struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="userForm" type="com.yz.actions.form.UserForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="userForm"
      name="userForm"
      path="/user"
      scope="request"
      type="com.yz.myActionProxy.mySpringActionProxy" 
      parameter="actions"
   />
  </action-mappings>
    <controller processorClass="com.yz.myReq.myReq"></controller>
  <message-resources parameter="com.yz.actions.ApplicationResources" />
 <!-- 添加一个插件,用来在启动struts框架的时候,
      同时读取spring配置文件,启动spring容器 -->
  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
          <set-property property="contextConfigLocation" 
          value="/WEB-INF/applicationContext.xml"/>
 </plug-in>
</struts-config>


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:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    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.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    
    <bean id="userDaoImpl" class="com.yz.dao.impl.IuserDaoImpl"></bean>
<!-- action里面有一个ius(service的接口引用),
    他来自  com.yz.services.impl.IUserServicesImpl(指向接口的实现类)
    IUserServicesImpl里面有一个iud(IuserDao接口引用)
    他 ref id为 userDaoImpl(指向接口的实现类)  /user 
    -->
    <bean id="intfUs" class="com.yz.services.impl.IUserServicesImpl">
        <property name="iud">
            <ref bean="userDaoImpl"/>
        </property>
    </bean>
    
    <!-- name必须和action的path一致 -->
    <bean name="/user" class="com.yz.actions.action.UserAction">
        <property name="ius" ref="intfUs"></property>
    </bean>
</beans>

<!--
    整合思路:
      1、 将 Strut 动作管理委托给 Spring。
      2、您可以通过在 struts-config 动作映射中注册一个代理来实现。代理负责在 Spring 环境中查找 Struts 动作。由于动作在 Spring 的控制之下,所以它可以填充动作的 JavaBean 属性,并为应用诸如 Spring 的 AOP 拦截器之类的特性带来了可能。 
     优缺点: 
        1、动作委托解决方法是这三种方法中最好的。  Struts 动作不了解 Spring,不对代码作任何改变就可用于非 Spring 应用程序中。RequestProcessor 的改变不会影响它,并且它可以利用 Spring AOP 特性的优点。 
        2、动作委托的优点不止如此。一旦让 Spring 控制您的 Struts 动作,您就可以使用 Spring 给动作补充更强的活力。例如,没有 Spring 的话,所有的 Struts 动作都必须是线程安全的。如果您设置 标记的 singleton 属性为“false”,那么不管用何种方法,您的应用程序都将在每一个请求上有一个新生成的动作对象。您可能不需要这种特性,但是把它放在您的工具箱中也 很好。您也可以利用 Spring 的生命周期方法。例如,当实例化 Struts 动作时, 标记的 init-method 属性被用于运行一个方法。类似地,在从容器中删除 bean 之前,destroy-method 属性执行一个方法。这些方法是管理昂贵对象的好办法,它们以一种与 Servlet 生命周期相同的方式进行管理
-->
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章