ssh框架中,jsp与action之间互传数据

来源:互联网 发布:eva初号机真面目 知乎 编辑:程序博客网 时间:2024/05/06 07:46

action与jsp之间传递数据的方法

一、jsp接受action中传来的数据

action调用service中业务函数产生一个数据,例如一个list,将这个list传给jsp进行显示(利用<s:iterator>标签循环显示出来)。

①首先action自动执行execute函数后跳转到某个jsp页面,需要在struts.xml中进行配置。执行完execute函数需要返回一个值,struts.xml根据这个返回值判断需要跳转到哪个jsp页面。例如下面是返回success就跳转到listCategory.jsp页面。

<action name="category" class="categoryAction"><result name="list">catagory/listCategory.jsp</result><!--<result name="input">catagory/listCategory.jsp</result>--><result name="success">catagory/listCategory.jsp</result></action>
②action中list的名字为List,那么在jsp页面中就要用到这个名字List进行获取,使用<s:iterator>标签获取List并循环输出。iterator标签中的value值是从action中取得的变量的名字。

<s:iterator value="threadList" var="thread"><tr><td width="5%">+_+</td><th style="width:35%">帖子名称</th><td style="width:15%">作者</td><th style="width:10%">回复数</th><td style="width:20%">最后回复时间</td><td style="width:15%">最后回复</td></tr><tr><td>❤</td><th><s:property value="#thread.title"/></th><th><s:property value="#thread.account"/></th><th><s:property value="#thread.replyCount"/></th><th><s:property value="#thread.dateLastReply"/></th><th><s:property value="#thread.accountLastReply"/></th></tr></s:iterator>

③如果要将iterator标签从action1中获取的List某个属性传给action2再进行操作,需要给jsp加个链接链到action,并传给action一个参数,action获取到参数后可以执行相应execute函数。链接实现是通过<a>标签和内部的<s:url action/>标签实现的,传给tread.action,参数为board,参数值为%{name}。这里取参数值用到了&{}方法,不同于iterator取参数使用#符号。

<th><a href="<s:url action="thread?board=%{name}"/>"><s:property value="#board.name"/></a></th>

④在另一个action2中取这个board参数时有三种方法。第一种setter、getter方法比较简单,亲测可用。

a、

实例:现在jsp页面传递一个名为username的参数到action中

url:   http://localhost:8080/StudentSystem/role_list.action?username=1321312

一、通过get set方法获取

在对应的action类中定义同名变量,并生成set get方法,那么参数将会自动获取值

String username;

 public String getUsername()
 {
  return username;
 }

 public void setUsername(String username)
 {
  this.username = username;
 }

System.out.println(username);//结果为1321312


b、通过ServletActionContext获取//导入import org.apache.struts2.ServletActionContext;

 HttpServletRequest reqeust= ServletActionContext.getRequest();

  String username=reqeust.getParameter("username");//字符串

//url:   http://localhost:8080/StudentSystem/role_list.action?username=1321312&username=34343

  String[] username=reqeust.getParameterValues("username");//字符串数组

  System.out.println(username);//结果为1321312

  System.out.println(username[0]);//结果为1321312

c、通过ActionContext获取//导入import com.opensymphony.xwork2.ActionContext;

  ActionContext context = ActionContext.getContext();
  Map params = context.getParameters();
  String[] username=(String[])params.get("username");

  //ActionContext获取到一个对象如object或String[]

    System.out.println(username[0]);//结果为1321312

<th><a href="<s:url action="thread?board=%{name}"/>"><s:property value="#board.name"/></a></th>
0 0