45、Spring整合Struts2

学习目标:

1、掌握Spring整合Struts2

学习过程:

整合完成jdbc后,下面我们就整合一下struts2这个mvc框架,虽然spring本身也提供了一个spring MVC框架,不过使用struts2的人还是很多的,所以spring也对struts2进行了支持,你会体验到spring确实是一个很轻量级的框架,它不会对struts2有很大的影响,甚至你感觉不到spring的存在,只需要把struts2的Action交给spring容器管理就可以了。

一、搭建好struts2的环境

这里我们以前搭建没有什么不同,也是先导入struts2的包,建立一个struts.xml的中配置文件,修改web.xml文件就可以了,这里我就不详细说明,大家可以自己实现,最后新建一个HumanAction类,该类实现对部门的增删改查等操作,不过这里就实现列表展示而已。Action代码如下:

public class HumanAction extends ActionSupport{

    private HumanBiz humanBiz;
    private List<Department> departments;
    public String listDepartment(){
        departments=humanBiz.queryDepartments();
        return SUCCESS;
    }

    public void setHumanBiz(HumanBiz humanBiz) {
        this.humanBiz = humanBiz;
    }

    public List<Department> getDepartments() {
        return departments;
    }

    public void setDepartments(List<Department> departments) {
        this.departments = departments;
    }
}

二、由spring接管action对象

1、导入struts2的插件包struts2-spring-plugin-2.X.X.jar

struts2从spring容器获得action对象即可,这里需要导入struts2对spring支持的插件包,你可以到struts2的目录下找到这个jar包

2、在spring配置文件中配置Action组件,注意改成一般需要改变作用域为prototype,这个步骤要记住,如果不是这样那么这个Action就是单例的,所有的用户将会共享Action的属性。

   <!-- struts 2 action 如何纳入spring的管理    非单例  scope="prototype" -->
    <bean id="humanAction" class="com.action.HumanAction" scope="prototype">
      <property name="humanBiz" ref="humanBiz"></property>
    </bean>

3、修改Struts2的配置文件。class属性直接从spring容器中获得对象,所以只需要写上bean的id就可以了,不需要写上完成的类名称了。

   <!-- spring容器中找Action  class执行的bean的action的id -->
<action name="listDepartment" class="humanAction" method="listDepartment">
         <result>/deplist.jsp</result>
</action>

就是这么简单就搞定了。

三、spring的web应用

现在我们碰到了一个问题,就是struts2可不是在后台使用main方法调用的,而是一个web应用,那么spring的容器应该在web启动的时候就构造出所有的控件,这方便spring也早就考虑了,所有我们需要修改web.xml添加一个监听器,在web启动的时候就自动加载spring容器,代码如下:

<!-- web启动的时候加载spring容器 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:springContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

所有我们发现现在启动web服务器的速度比以前慢了,但是大家千万不要以为应用程序也会变慢,因为web启动的时候需要初始化所有的组件,所以速度慢而已,但是启动完毕后组件就可以直接从spring容器中取得,所有运行速度比以前还要快。

现在你可以启动这个web项目,是否能从数据库中查询得到数据了

猜你喜欢

转载自blog.csdn.net/liubao616311/article/details/85223158
今日推荐