Spring4.3.8学习之 与 Struts2 整合[四]

2017-06-19  本文已影响90人  小椰子表姐

如果转载文章请注明出处, 谢谢 !
本系列文章是学习完 Spring4.3.8 后的详细整理, 如果有错误请向我指明, 我会及时更正~😝

Spring4.3.8

Spring4.3.8学习[一]
Spring4.3.8学习[二]
Spring4.3.8学习[三]

5. Spring 与 Struts2 整合

先写一个经典的三层架构

public interface UserDao {
    public void add();
}

--------------

public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("添加成功~");
    }
}

---------------

public interface UserService {
    public void register();
}

---------------
public class UserServiceImpl implements UserService {
    private UserDao dao;     
    public void setDao(UserDao dao) { 
        this.dao = dao;
    }

    @Override
    public void register() {
        dao.add();
    }
}

applicationContext.xml:

<bean name="userDao" class="com.lanou.dao.impl.UserDaoImpl"/>

<bean name="userService" class="com.lanou.service.impl.UserServiceImpl">
    <property name="dao" ref="userDao"/>
</bean>

在应用启动时默认加载 spring 的 applicationContext 配置文件, 所以在 web.xml 中进行注册监听器

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

这个 listener 在 spring-web jar 包中,如果没有需要导入 jar 包

5.1 方式一

动作类还是 Struts2 负责管理, 只向 spring 容器要service 实例

public class UserAction extends ActionSupport {
    // 需要和 spring 中的 bean 名字保持一致!
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String register() {
        userService.register();
        return SUCCESS;
    }
}

struts.xml:

<package name="p1" extends="struts-default">
    <action name="register" class="com.lanou.web.action.UserAction" method="register">
        <result name="success">/success.jsp</result>
    </action>
</package>

但是这时候访问 register , 会出现空指针, 因为 userService 不存在, 它是由 spring 的 BeanFactory 管理的,而 userAction 是由 ObjectFactory 管理的, ObjectFactory目前不能够从 Spring 容器获取userService.

解决办法:
添加 struts2和spring 的插件, 在 struts2的包中: struts2/lib/struts2-spring-plugin.jar

在struts.xml 配置文件中替换类

<!-- 替换默认的产生动作实例的工厂为 spring —>
<constant name="struts.objectFactory" value="spring"/> 

**但是不需要做. 拷贝的 jar 包中有 struts-plugin.xml, 里面有这项配置 **

5.2 方式二

动作类也交给Spring 管理, 这时不需要 struts2-spring-plugin.jar

applicationContext.xml:

<!— 实例化动作类 — > 
<bean name="registAction" class="com.lanou.web.action.UserRegistAction" scope="prototype"> 
    <property name="userService" ref="userService"/> 
</bean>

struts.xml:
将class修改成applicationContext.xml中配置 bean 的name

<package name="p1" extends="struts-default">
    <action name="register" class="registerAction" method="register">
        <result name="success">/success.jsp</result>
    </action>
</package>

Spring4.3.8学习之与Hibernate4 整合[五]
Spring4.3.8学习之S2SH 整合[六]

上一篇 下一篇

猜你喜欢

热点阅读