Struts2使用笔记
配置文件的加载顺序
struts.xml -> struts.properties -> web.xml
这三个文件都是可以修改
struts2常量的值,但是后面的重复的值会覆盖前面的值在上面三个文件中都是可以配置常量值的
通常在struts.xml中配置常量或者其他的Action,项目比较大时,难免臃肿,此时可以使用include标签来引入其他的xml配置文件,其格式遵循struts.xml文件的格式
在struts.xml中配置action的三种方式:
指定method
通过通配符”*”匹配
动态方法访问,注意:struts2.5以后默认关闭,需要配置打开,同时在package中配置
1
<global-allowed-methods>regex:.*</global-allowed-methods>
结果页面配置
局部结果页面配置
1
2
3
4
5
6
7
8<action name="user_*" class="com.lee.struts2test.UserController" method="{1}">
<result name="login_success">
/index.jsp
</result>
<result name="regist_success">
/login.jsp
</result>
</action>是在action中配置
全局结果页面配置
全局结果页面展示必须放在局部的action标签之前
result标签中的type属性- dispatcher:转发,默认
- redirect:重定向
Action中常用的两个类
- ActionContext
- ServletActionContext
ServletRequestAware接口,在方法中获取HttpServletRequest对象
表单数据的封装
- 原始方法,得到request中的参数
- 属性封装
- 提供Entity中的属性和get/set方法,Action会自动调用给属性赋值(获取表单数据到成员变量里面,不能把数据直接封装到实体类里面)
- 表达式封装,在页面通过使用user.userName分方式来设置表单的name属性(在Action中必须提供get方法,返回user为属性名的一个实体)
- 模型驱动封装
- 可以直接把表单数据封装到实体类里面,一个Action类中只能有一个实体类对象
使用表达式封装,可以将数据封装到List或者Map中
1.配置的时候,Intellij自动生成了全局过滤器
1 | <filter> |
其中
1 | org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter |
爆红,原来如果jar包确认没问题的话,检查你的Struts2版本,如果是2.5版本以上的话,将.ng去掉,我的是2.5.14.1,修改成
1 | <filter> |
2.使用通配符”*”配置struts.xml中的action访问路径的时候,运行时出现异常,action映射的方法没有找到,解决办法:**
1 | <action name="customer_*" class="com.lee.crm.customer.action.CustomerAction" method="{1}"> |
加上<allowed-methods>add,list,update</allowed-methods>
3.使用模型驱动封装表单数据,在需要对表单对应的实体进行更新的时候**
1 | public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { |
发现从ValueStack中获取的值依然是更新之前的值.这是由于action中的customer的确是更新了,但是valuestack中的值依然是旧值,而在页面中通过<s:property value='custId' />获取的也是旧值
解决办法有多种,这里介绍两种常用的方法:
第一种:
ActionContext.getContext().getValueStack().push(this.customer);将新的值压入栈顶,页面获取的就是新的对象的值了
第二种:
在相应的action标签中加入
1
2
3
4
5
6
7
8<action name="customer_*" class="com.lee.crm.customer.action.CustomerAction" method="{1}">
<interceptor-ref name="defaultStack">
<!-- 渲染页面前刷新model在ValueStack的root的引用 -->
<!--这样在valuestack中会自动压入一个新的值,跟手动调用push方法是一样的-->
<param name="modelDriven.refreshModelBeforeResult">true</param>
</interceptor-ref>
</action>同时在action中给对象赋上新的值
1
this.customer = customer;
4.ValueStack压入的对象是以对象的属性名作为key,属性值作为value存贮在map中的,所以在页面中取值的时候直接通过Property Name取值,具体可以多用用<s:debug><s:debug>标签看看Value Stack Contents中值的存放形式
在使用struts.xml文件时,经常因为格式导致不必要的错误。
例:1
2
3
4
5<package name="default" extends="struts-default" namespace="/namespace1">
<action name="initFStree" class="InitFStree">
<result name="success">pages/initFStree.jsp</result>
</action>
</package>
5.struts2中% 、# 的使用方法:
1 | %和$符号在OGNL表达式中经常出现. |