下面是 servlet 类,它通过在bean类的对象上调用方法来设置名称,然后转发到 jsp 页面。
package BeanTesters;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class Controller extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
Bean bean = new Bean();
bean.setName("Suhail Gupta");
//request.setAttribute("name", bean);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
这是 bean 类:
package BeanTesters;
public class Bean {
private String name = null;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
以下是尝试显示 servlet 设置的名称的 jsp 片段:
<jsp:useBean id="namebean" class="BeanTesters.Bean" scope="request" />
Person created by the Servlet : <jsp:getProperty name="namebean" property="name" />
我得到的结果是:Servlet 创建的人:null为什么我得到一个空值?