/*
result配置各种视图转发类型
在struts1中配置的转发是重定向和内部转发:
<action path="/addUI" type="...">
<forward name="add">/index.jsp</forward>
<forward name="add" redirect="true" >/index.jsp</forward>
</action>
在struts2中提供了多种结果类型,常用的类型:
1.重定向到某个jsp
dispatcher(默认值):
redirect:请求重定向,此时不能将资源放在WEB-INF/目录下
<action name="index" class="cn.it.action.HelloAction" method="execute">
<result type="redirect">/index.jsp?username=${username}</result>
</action>
上面的意思是:/index.action请求来了之后,会找cn.it.action.HelloAction这个Action的execute方法,在execute方法中对username属性进行赋值
这样在请求重定向之后的地址会带上一个username的参数如:/struts2/index.jsp?username=chenyansong
如果传递过来的是中文,那么就要用到url编码:URLEconder.encode("中国","UTF-8");
在jsp中可以获取请求参数的值(中国):${param.username}
但是此时要进行ISO8859-1解码:在jsp中<%= new String(request.getParameter("username").getBytes("iso8859-1"),"UTF-8")%>
2.重定向到某个action
redirectAction:重定向到某个Action
<action name="action">
<result type="redirectAction">addUI</result>
</action>
addUI是要重定向的action
但是如果重定向的action不在同一个包中,那么该怎样做呢?
<package ............>
<action name="action">
<result type="redirectAction">
<param name="actionName">xxx</param><!--指定Action的名称-->
<param name="namespace">/other</param><!--指定要转发的Action所在的名称空间-->
</result>
</action>
</package>
<!--因为redirectAction对应于一个类(可以参见struts-default.xml),在这个类中有actionName、namespace属性,这里是通过参数的形式将值注入到属性上-->
<package name="other" namespace="/other" extends="struts-default">
<action name="xxx">
<result>/index.jsp</result>
</action>
</package>
4、 plainText:原样输出代码
<action name="plainText">
<result type="plainText">/WEB-INF/page/add.jsp</result>
</action>
如果原样输出的数据中有中文乱码的问题,那么怎样解决呢?
<action name="plainText">
<result type="plainText">
<param name="location">/index.jsp</param><!--定位到哪个jsp页面-->
<param name="charSet">UTF-8</param> <!--指定以UTF-8去读取文件(因为文件是以u8存的)-->
</result>
</action>
5、全局视图:
<package name="first" namespace="/test" extends="struts-default">
<global-results>
<result name="message">/index.jsp</result>
</global-results>
</package>
那么在Action中就能使用message这个视图
那么如何使用不同包下的全局视图呢?
<package name="second" namespace="/second" extends="first">
<action name="yyy" class="cn.it.action.HelloAction" method="add">
</action>
</package>
<package name="first" namespace="/test" extends="struts-default">
<global-results>
<result name="message">/index.jsp</result>
</global-results>
</package>
只需要通过继承包就行了,所以在HelloAction中的add方法就能使用message视图
public String add(){
return "message";
}
本学习笔记是根据传智播客的视频教程整理而来