struts2,hibernate,spring整合笔记(4)--struts与spring的整合

饭要一口一口吃,程序也要一步一步写,

很多看起来很复杂的东西最初都是很简单的

下面要整合struts和spring

spring就是我们的管家,原来我们费事费神的问题统统扔给她就好了

先写一个测试方法

package com.hibernate;
import static org.junit.Assert.*;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.beans.HelloWorldAction;
public class SpringTest {
    private ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    public void test() {
        HelloWorldAction a=(HelloWorldAction)ac.getBean("helloWorldAction");
        System.out.println(a);
    }
}

当然,现在肯定是不成立的

spring还不知道我们的helloWorldaction是什么

我们要先声明

在HelloWorldAction "public class HelloWorldAction"

上面添加

@Controller

@Scope("prototype")

现在上面的test已经可以运行了,

但也只是spring接管了HelloWorldAction类,并不代表spring与struts整合了

顶多算是一个spring的helloworld

接下来,我们需要在web.xml中加入监听器

新的web.xml如图所示

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>oa</display-name>
  
  
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  
   <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.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

然后在加入一个 struts2-spring-plugin-2.1.8.1.jar

将struts.xml中的action的class属性改为"helloWorldAction"

约定俗成,第一个字母小写,其他不变,写错了要报错

重启服务器,在浏览器中输入

localhost:8080/oa/test/helloworld.action

不报错就成功了

 

posted @ 2015-05-22 00:11  Asens  阅读(185)  评论(0编辑  收藏  举报