Monday, September 14, 2009

Roundtripping Form Parameters

So you have a form, and each of the fields has a name and a value. In HTML when you press a submit button or call Javascript to submit the form all the names and values get POSTed or added to the URL as GET parameters. In a JSP things are more complex. You are supposed to define a `bean' that gets attached to the JSP file so you can access the parameters that way:

<jsp:useBean id="user" class="" scope="session"/>

This creates the bean "user" and associates it with the session. When the form is reloaded after a submit, the parameters are available and can be used to set the form elements. To copy them into the bean you can say:

<jsp:setProperty name="user" property="*"/>

This copies all the passed-in parameters into the bean "user", provided the bean has correctly named get and set methods for them. Now, to set the actual elements of the form we use the JSP EL or "Expression Language":

<mytag:namedlist name="intf" value="${user.intfList}" selected="${user.intf}"/>

I should explain that the "namedlist" tag creates a <select> element and populates it from the comma-separated list supplied as the "value". The EL expression "${user.intf}" sets the selected property of the tag to the value of the intf instance variable in the AppletInfo class. Each such property needs a get and a set method for this to work: in this case the getIntf and setIntf methods.

Meanwhile, in the GenericPortlet class we define a method processAction:

    public void processAction(ActionRequest request, ActionResponse response) 
        throws PortletException,
        Enumeration names = request.getParameterNames();
        while ( names.hasMoreElements() )
            String param = names.nextElement();
            String value = request.getParameter(param);
            response.setRenderParameter( param, value );

All this does is read the passed-in parameter names and their values and copy them to the response object. We can of course change these before doing so. They then appear in the JSP and get copied into the bean thanks to the <jsp:setProperty id="user" property="*"/> statement.

Note that the portlet code knows nothing of beans. It just sees parameters.

No comments:

Post a Comment