2

I am getting null as URL parameter name in prepare method of Preparable interface, while parameter is set in URL.

URL I am trying to visit,

http://localhost:8080/basic-struts/registerInput.action?userid=1


public class Register extends ActionSupport implements Preparable {    

    private String userid;       

    public void prepare() throws Exception {
        // Call the service, load data, 
        // every time even if validation fails

        System.out.println("----------");
        System.out.println(userid); //<-------null
        System.out.println("----------");
    }

    public String getUserId() {
        return userid;
    }

    public void setUserId(String userid) {
        this.userid = userid;
    }

}

Note :- I get some error in logs as follows,

2021-07-01 09:28:53,929 ERROR [qtp1182469998-22] interceptor.ParametersInterceptor (ParametersInterceptor.java:238) - Developer Notification (set struts.devMode to false to disable this message): Unexpected Exception caught setting 'userid' on 'class org.apache.struts.register.action.Register: Error setting expression 'userid' with value ['1', ]

Roman C
  • 49,761
  • 33
  • 66
  • 176
Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19
  • If you’re using the default interceptor stack, note the order in which they’re run. See https://stackoverflow.com/q/30364532/438992. – Dave Newton Jul 02 '21 at 13:06

2 Answers2

1

Setting parameter userid to the action class variable is case sensitive. The corresponding setter method should be

public void setUserid(String userid) {
    this.userid = userid;
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • That removed the error message, but I still get null in userid. I think prepare method doesn't take url parameters in struts2 moreover url parameters only work with execute method. – Shoyeb Sheikh Jul 02 '21 at 07:32
  • @Shoyeb The `prepare()` method implements `Preparable` interface. And you have to write your own implementation. URL parameters are in the `request` object might not have been populated your action by the `params` interceptor. However due to the [documentation](https://struts.apache.org/core-developers/struts-default-xml.html) in the `default-stack` it's executed before `prepare` interceptor. – Roman C Jul 02 '21 at 19:52
  • I added an interceptor `paramsPrepareParamsStack` in my action and its working now, I got the value in variable `userid`. Thanks for your help with setter method. – Shoyeb Sheikh Jul 03 '21 at 04:04
0

@Dave Newton's suggestion helped, on the link he shared I got the clue and got it working,

I changed my struts.xml and added interceptor paramsPrepareParamsStack to my action as follows,

<action name="registerInput" class="org.apache.struts.register.action.Register" method="input" >
    <result name="input">/register.jsp</result>
    <interceptor-ref name="paramsPrepareParamsStack"/>
</action>
Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19