Getting NULL for empty values in ModelDriven

896 Views Asked by At

ModelDriven returns NULL for the params which have empty values.

Bean:

public class MyBean
{
    private String userName;
    public void setUserName(String userName)
    {
        this.userName = userName;
    }
    public String getUserName()
    {
        return userName;
    }
}

Class:

public class MyAction extends ActionSupport implements ModelDriven<MyBean>
{
    MyBean myBean = new MyBean();
    public String execute()
    {
        System.out.println(myBean.getUserName());//getting null here
        return "SUCCESS";
    }
}

Request:

/home/MyAction.do?userName=&pass=

Hear I am passing empty value for userName param but in action I getting the null value.

How to get exact value in ModelDriven?

3

There are 3 best solutions below

0
On

Although, HttpServletRequest#getParameter() handles the two cases differently; for most practical purposes, it shouldn't matter much. That's because using ${EL} expressions or Struts display tags, the null values would get rendered as blanks only.

If, however, you have some code that depends on it (like ?chrome telling the browser type) you're better off changing it (to something like ?browser=ff) because making your Actions ServletRequestAware is not worth it.

If you would still like to go for it, here's how to do it:

public class MyAction extends ActionSupport implements ModelDriven<MyBean>,
                                                       ServletRequestAware
{
    HttpServletRequest request;
    MyBean myBean = new MyBean();

    public String execute()
    {
        if (myBean.getUserName() == null) {
            myBean.setUserName(getRequest().getParameter("userName"));
        }

        System.out.println(myBean.getUserName());
        return "SUCCESS";
    }

    public void setServletRequest(HttpServletRequest request)
    {
        this.request = request;
    }
}
0
On

When your bean property contains a null value it keeps the value in the OGNL expressions and value tag. You can always use OGNL expression to evaluate null value. For example

<s:if test="userName == null">
  <s:property value="username"/>
</s:if>

If you want to pass null value as a parameter then you should use null string.

/home/MyAction.do?userName="null"&pass="null"
0
On

I think you are getting null values beacuse of

You are implementing ModelDriven<MyBean> interface.

and this interface there must override getModel() method, check what getModel() method is returning.whether it is returning null or your bean(myBean)variable ..

public MyBean getModel() {
return null; // This must be the reason, you will get null always when you call getProperties of bean
}

Try like this

public MyBean getModel() {
    return myBean ; // This will return your bean in modelDriven Interface(return your bean variable here )
    }

Hope it helps.