struts2与spring 结合时一些问题

来源:互联网 发布:java调用linux命令 编辑:程序博客网 时间:2024/06/05 02:26

1,spring自动生成action 的实例,前提要在web.xml中配置spring的监听器以及加入struts2-spring-plugin.jar包

       

  1. <listener>  
  2.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  3.     </listener> 
  4. <context-param>
  5.    <param-name>contextConfigLocation</param-name>
  6.    <param-value>classpath:beans.xml</param-value>
  7. </context-param> 
  将struts.xml配置的action命名为和Action类名字相同@Component("action命名");@Scope("prototype")不要忘记,每一个产生的action对象都是新的;
  其实在action名字相同的情况下上边两个注解可以都不写,默认的scope就是prototype;

2,默认情况下action中的属性再不用注解的情况下都会自动注入,前提是属性名称与类名的@Component("命名")相同,属性名称首字母小写,名称不相同的情况下需要用注解@Resource(name=""),一般常用在setter方法上;


3,异常:could not initialize proxy - no Session...
在web.xml中struts之前配置:
<filter>
   <filter-name>opensession</filter-name>
   <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>opensession</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>
这样session一旦打开就会等到我们访问完之后才会关闭,把session打开的时间一直延续到View层。
使用load时需要需要上述操作,使用get时不需要


4,总结spring容器中装的bean是service和dao;action的产生完全由struts2-spring-plugin产生,action类中不需要写注解,属性名称要与类名的@Component("命名")相同;

5,如果在bean.xml中没有配置事务,如果在web.xml配置了OpenSessionInView,则认为事务是只读的(readOnly),则不允许做增删改的操作;
所以正常情况下两者都应该配置;

6,spring中一个解决编码问题的过滤器也很好用,在web.xml中配置
  1. <filter>     
  2.   <filter-name>EncodingFilter</filter-name>     
  3.   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>     
  4.   <init-param>     
  5.     <param-name>encoding</param-name>     
  6.     <param-value>gbk</param-value>  //大小写不所谓   
  7.   </init-param>     
  8. </filter>     
  9.  <filter-mapping>     
  10.     <filter-name>EncodingFilter</filter-name>     
  11.     <url-pattern>/*</url-pattern>     
  12.  </filter-mapping>   

7,关于spring管理action的官方文档解释:在action类上边配置@Component('"action")@Scope("prototype");在struts.xml配置文件中action一行的class="action"  ;这样action就像其他普通类一样被spring管理。当然action的属性都需要@Resource()注解。

原创粉丝点击