Getting a null value for where i expect a string s

2019-08-20 20:00发布

问题:

Following is the servlet class that sets the name by invoking a method on the object of a bean class and then forwards to a jsp page .

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);
  }
}

And this is the bean class :

package BeanTesters;

 public class Bean {

  private String name = null;

  public void setName(String n) {
    name = n;
  }

  public String getName() {
    return name;        
  }
 }

following is a jsp snippet that tries to display the name set by the servlet:

<jsp:useBean id="namebean" class="BeanTesters.Bean" scope="request" />
    Person created by the Servlet : <jsp:getProperty name="namebean" property="name" />

The result i get is : Person created by the Servlet : null Why do i get a null value ?

回答1:

Because the jsp:useBean tag tries to get a bean in the attribute "namebean" of the request, and since you didn't store anything under this attribute name, it creates one. The bean instance used by the JSP is thus a different instance than the one created in the servlet.

Put the following code in your servlet, and you'll get the desired behavior:

request.setAttribute("namebean", bean);

Note that the jsp:xxx tags are completely obsolete, and should not be used anymore. You should instead use the JSP expression language (EL), and the JSTL:

Person created by the Servlet : ${namebean.name}

Or even better, to make sure the potential HTML characters present in the name are properly escaped:

Person created by the Servlet : <c:out value="${namebean.name}"/>