zootropo
zootropo

Reputation: 2491

Inject JSF request parameter in a bean managed by Spring using annotations

Right now I use the f:viewParam tag to inject the request parameter into a field of my bean

<f:viewParam name="id" value="#{surveyController.id}" />

But I would much rather prefer to use annotations for this. I know about the @Value annotation, and I guess I could do something like this

@Component
@Scope("view")
public class SurveyControlador {
    @Value("#{new Long.parseLong('${param.id}')}")
    private Long id;

    ....
}

But this is just plain ugly.

Is there a better way, where I don't need to convert the value explicitly, and maybe even omit the "param"? I'm even willing to install third party libraries

Upvotes: 0

Views: 663

Answers (1)

mabi
mabi

Reputation: 5306

I've used omnifaces' @Param successfully, like so:

@Named @ViewScoped
public class SurveyController {
    @Inject @Param(name = "id")
    private ParamValue<Long> idParam;

    public void doStuff() {
        if (idParam.getValue().equals(1)) {
            throw new IllegalAccessException("you don't dare");
        }
    }
}

Pro: You additionally get access to the raw submitted value and omnifaces optionally applies validations/conversions (check the docs).

Con: Wrapper around your real parameter. And you still need to specify <f:viewParam> (you don't need to bind it to a backing bean, tho) if you want to keep the parameter for navigation.

Note that this leverages CDI, which may or may not fit the way you do things.

Upvotes: 1

Related Questions