日期:2014-05-20  浏览次数:20787 次

帮忙讲一下这个关于struts2的参数传递问题
QueryAction.java

package com.jeedroid.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.jeedroid.dao.BookDao;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class QueryAction extends ActionSupport {
private String name;
private Map<String,Integer> result;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Integer> getResult() {
return result;
}
public void setResult(Map<String, Integer> result) {
this.result = result;
}
public String execute()
{
try
{
BookDao book=new BookDao();
Map<String,Integer> books=book.getBooks(name);
setResult(books);
return "succ";
}
catch(Exception e)
{
return "error";
}
}
}


BookDao.java


package com.jeedroid.dao;

import java.util.LinkedHashMap;
import java.util.Map;

public class BookDao {

private static Map<String,Integer> books=new LinkedHashMap<String,Integer>();
static
{
books.put("j2ee整合开发", 56);
books.put("php从入门到精通", 20);
books.put("java web开发详解", 22);
}
public Map<String,Integer> getBooks(String name)
{
Map<String,Integer> books=new LinkedHashMap<String,Integer>();
for(Map.Entry<String, Integer> entry:BookDao.books.entrySet())
{
if(entry.getKey().toLowerCase().contains(name.toLowerCase()))
{
books.put(entry.getKey(), entry.getValue());
}
}
return books;
}
}

struts2.xml :
<package name="default" extends="struts-default">
  <action name="query" class="com.jeedroid.action.QueryAction">
  <result name="succ">
  /result.jsp
  </result>
  <result name="error">/error.jsp</result>
  </action>
  </package>

result.jsp
<body>
<table border="1">
<tr><td>书名</td><td>价格</td></tr>
<%
Map<String,Integer> result=(Map<String,Integer>)request.getAttribute("result");
for(Map.Entry<String,Integer> entry:result.entrySet())
{
%>
<tr>
<td><%=entry.getKey() %></td>
<td><%=entry.getValue() %></td>
</tr>
<%
}
%>
</table>
</body>
在result.jsp里面有一个request.getAttribute("result");请问这个"result"是怎么传过来的,什么时候有这个东西的,在Action里面她只是一个对象啊,而且没有setAttribute("result",books);这里怎么回事啊?

------解决方案--------------------
这是OGNL,提交action时,会经过一系列拦截器,会将值自动封装到ValueStack中,只需提供set,get方法,页面用el或request等等就能得到值