CoolBeans
CoolBeans

Reputation: 20800

setting url parameter in an action method in struts

I want to add a URL parameter before forwarding to another action from an action method. Although HttpServletRequest has a getParameter() method, it has no setParameter() method. I know setAttribute() is there but I need the it to be part of the URL (like ?something=something&some2=some2). I know I can do it using filters but that's an overkill for this task.

Basically we have an externally managed filter which will change something on a page when that parameter is set. Let's say the color of the page will be passed as part of the URL parameter. When that parameter is present a servlet filter picks it up and changes the color of that page. I know it's a very odd way of doing but that's how they have it set up here.

I know how to make it work using java script based form submit by adding the URL parameter to the action url (ie. "/someAction.do?color=red"). But for some of the actions it actually does a action.forward("action_name") in the code. For those I was wondering what to do.

Does anyone know how to do that in struts 1.2?

Upvotes: 2

Views: 14472

Answers (2)

davibq
davibq

Reputation: 1099

I know this is an old and accepted post, but If you can't upgrade your struts (like me) then this might be useful http://www.coderanch.com/t/45890/Struts/Adding-parameters-struts-action

import org.apache.struts.action.ActionForward;
public class ParameterizedForward extends ActionForward
{
    public ParameterizedForward(ActionForward forward)
    {
        super(forward.getPath(), forward.getRedirect());
    }
    public void addParameter(String key, String value)
    {
        StringBuffer sb = new StringBuffer(getPath());
        if (key == null || key.length() < 1)
            return;
        if (getPath().indexOf('?') == -1)
            sb.append('?');
        else
            sb.append('&');
        sb.append(key + "=" + value);
        setPath(sb.toString());
    }
}

ParameterizedForward fwd = new ParameterizedForward(mapping.findForward("success"));
fwd.addParameter("name","jason");
fwd.addParameter("userLevel", "god");
return fwd;

Upvotes: 3

laz
laz

Reputation: 28638

The short answer is that it isn't possible. Request parameters are supposed to be from the HTTP request. You can fake adding them using a combination of a ServletFilter and an HttpServletRequestWrapper but that is outside of Struts. Depending upon what you are trying to accomplish there may be a better solution. Want to describe that a bit more?

Update

With the additional detail you've added, I think you can try this to see if it meets your needs:

import org.apache.struts.action.ActionRedirect;
...
ActionForward forward = action.forward("action_name");
ActionRedirect redirect = new ActionRedirect(forward);
redirect.addParameter("color", "red");
return redirect;

Upvotes: 7

Related Questions