从JSP页面中的Java Bean中检索值数组

时间:2013-02-24 13:12:35

标签: arrays jsp model-view-controller javabeans

无法在JSP页面中调用Bean中的getNames()...成功能够设置名称,但是当我调用getNames时它返回Null

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  try {
    List<String> name=new ArrayList<String>();
    name.add("Pushkar");
    name.add("Raj");
    ArrayBean bean=new ArrayBean();
    bean.setNames(name.toArray(new String[name.size()]));       

    // request.getRequestDispatcher("DDL.jsp").forward(request, response);
    response.sendRedirect("DDL.jsp");

  } finally {            
    out.close();
  }

public class ArrayBean {
  public String[] names;

  public String[] getNames() {
    return names;
  }

  public void setNames(String[] names) {
    this.names = names;
  }
}

2 个答案:

答案 0 :(得分:0)

将您的try catch更改为

try {
name=new ArrayList<String>();
name.add("Pushkar");
name.add("Raj");
ArrayBean bean=new ArrayBean();
bean.names=new String[name.size()];
        bean.names=name.toArray(bean.names);      

// request.getRequestDispatcher("DDL.jsp").forward(request, response);
response.sendRedirect("DDL.jsp");} finally {            
out.close();  }

希望它能奏效。

答案 1 :(得分:0)

这件事,我在Bean中添加了一个LoadData()方法,它设置了值&amp;然后我从JSP调用getNames(),它工作正常,从Servlet中删除所有代码,甚至现在不需要Servlet

public class ArrayBean {
public List<String> names;

public List<String> getNames() {
    if(names==null){loadNames();
    }return names;
}   


private void loadNames()
{
     names=new ArrayList<String>();
        names.add("Pushkar");
        names.add("Raj");        

}

}