获取null值,我期望mutator设置一个字符串 [英] Getting a null value for where i expect a string set by the mutator

查看:196
本文介绍了获取null值,我期望mutator设置一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是通过在 bean 类的对象上调用方法然后转发到jsp页面来设置名称的servlet类。

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

这是bean类:

package BeanTesters;

 public class Bean {

  private String name = null;

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

  public String getName() {
    return name;        
  }
 }

以下是一个试图显示名称的jsp片段由servlet设置:

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" />

我得到的结果是: Servlet创建的人:null 为什么我得到一个空值?

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

推荐答案

因为 jsp:useBean tag尝试在请求的属性namebean中获取bean,并且由于您没有在此属性名称下存储任何内容,因此它会创建一个。因此,JSP使用的bean实例与servlet中创建的实例不同。

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.

将以下代码放入servlet中,您将得到所需的行为:

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

request.setAttribute("namebean", bean);

请注意 jsp:xxx 标签是完全过时了,不应该再使用了。您应该使用JSP表达式语言(EL)和JSTL:

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}

或者甚至更好,以确保名称中存在的潜在HTML字符被正确转义:

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}"/>

这篇关于获取null值,我期望mutator设置一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆