4

I am using Servlet and JSP without a framework to study for my SCWCD. I have a simple form that I want the parameters to bind to a bean automatically. Is this possible without writing binding code or using a framework?

Thanks

3 Answers 3

11

Well, without a "framework" you can't do this. But you can use the Jakarta BeanUtils (http://commons.apache.org/beanutils/), more precisely the static method BeanUtils.populate in your servlet. Ex.:

BeanUtils.populate (myBean, request.getParameterMap());

Remember: the input properties names must match with bean attributes, ok?

0
9

You can do this with <jsp:useBean>.

<jsp:useBean id="form" class="com.example.Form" scope="request" />
<jsp:setProperty name="form" property="*" />
<jsp:include page="servletUrl" />

All bean properties whose names match the request parameter names -if any- will be set and the bean will be available as request attribute in the servlet matching the url-pattern of /servletUrl.

However, you'd like to use a servlet and/or MVC framework for this since it abstracts it all away and gives a better control over actions and response handling. This is essentially abuse of JSP (as being a view technology) as controller (which should be (in)directly done by a Servlet).

2

No, it isn't. You should use some framework, which I guess would be an overkill.

So what you can do, is iterate request.getParameterMap() keys and set the values to object with the corresponding field names (via reflection)

1
  • Fulvius answer provides an alternative without directly using reflection. Nov 15, 2013 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.