使用Struts2中应该注意的地方

一、标签库的使用

 

1、set标签

     set中要想得到不同访问域application、request、session里的值,可以这么写:

    

 

     set中的value不支持表达式,只支持object和string。

 

二、后台Action

1. 获得Servlet中的request、response和session,可以这么写

 

ActionContext ctx = ActionContext.getContext();

//访问ServletContext,即Application
ctx.getApplication().get("name");
ctx.getApplication().put("name",name);

//访问HttpServletRequest
ctx.get("name");
ctx.put("name",name);

//访问HttpSession
ctx.getSession().get("name");
ctx.getSession().put("name",name);

 

    或者

 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import org.apache.struts2.ServletActionContext;


HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();        
HttpSession session = request.getSession();

 

 

三、配置文件

1.Struts2允许在Struts.xml文件中管理Struts2属性,在Struts2.xml文件中通过配置constant元素,一样可以配置这些属性。


    
    ...

 上述配置用来声明国际化文件。

 

2.Struts2应用配置文件加载顺序如下

   (1)struts-default.xml(包含在Struts2-core.xml文件中)

   (2)struts-plugin.xml(包含在各插件JAR文件中)

   (3)struts.xml(应用相关的配置文件)

    从上面的加载顺序可以看出,应用相关的配置文件总是最后才加载的。因为应用可以依赖于插件,每个插件都可依赖于Struts2的核心,但插件之间不可相互依赖。

 

3.通配符匹配Action

   如果URL中的action名能跟struts.xml中带通配符的某个Action的name完全匹配,则一定匹配这个,否则按照action在struts.xml中的顺序,依次匹配。

 

4.struts.xml中配置声明式异常

   全局异常:


   



    /exception.jsp



    
    /exception.jsp

    

 

四、与其它框架的联合使用

 

1. 与Spring的结合

    (1)拷贝如下jar包到WEB-INF\lib下

            spring-core-xxx.jar

            spring-context-xxx.jar

            spring-beans---xxx.jar

            spring-web-xxx.jar

            struts2-spring-plugin-xxx.jar

            commons-logging-xxx.jar

    (2)修改web.xml

            如果web项目是Servlet2.3之后的,可以这样

           


    org.springframework.web.context.ContextLoaderListener

 

             如果是Servlet2.3之前的,必须这样


     context
     org.springframework.web.context.ContextLoaderServlet
      1 

 

      (3)在WEB-INF/下创建applicationContext.xml,作为spring的配置文件

你可能感兴趣的:(struts)