Bean Jsp String数组连接

时间:2014-03-20 05:50:00

标签: jsp javabeans

我的java bean中有一个String类型的数组,我想在我的Java Server Page中获取它。但是当我在我的页面上使用get属性时,它会给我null。任何人都可以为此提出解决方案吗?

1 个答案:

答案 0 :(得分:1)

我认为你试图访问bean属性而不通过setter方法设置它的值。访问bean及其属性的更好方法是使用jsp表达式语言,如下例所示。

JSP代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Names are : ${namesBean.names[0]} ${namesBean.names[1]}
</body>
</html>

如果我直接从http://localhost:8080/sof/main.jsp url访问此jsp页面,则此时不会初始化namesBean,并且

  

名称是:

如果我使用http://12.0.0.1:8080/sof/SampleServlet通过servlet将请求转发到这个jsp页面,那么它初始化为namesBean,那么它的值将显示在页面上。

Bean代码:

package sample;

public class SampleBean {

    public String[] names;

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

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

Servlet代码:

package sample;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SampleBean sampleBean = new SampleBean();
        sampleBean.setNames(new String[]{"Aamir", "Latif"});
        request.setAttribute("namesBean", sampleBean);
        RequestDispatcher rd = request.getRequestDispatcher("main.jsp");
        rd.forward(request, response);
    }
}

Servlet映射:

  <servlet>
    <description></description>
    <display-name>SampleServlet</display-name>
    <servlet-name>SampleServlet</servlet-name>
    <servlet-class>sample.SampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SampleServlet</servlet-name>
    <url-pattern>/SampleServlet</url-pattern>
  </servlet-mapping>

然后输出

  

名字是:Aamir Latif

更好的方法是使用JSTL