Billworth Vandory
Billworth Vandory

Reputation: 5053

binding form parameters to a bean using just Servlets and JSP - possible?

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

Upvotes: 4

Views: 7381

Answers (3)

Fulvius
Fulvius

Reputation: 511

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?

Upvotes: 11

BalusC
BalusC

Reputation: 1108802

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).

Upvotes: 9

Bozho
Bozho

Reputation: 597124

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)

Upvotes: 2

Related Questions