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

非 Y 不嫁゛ 提交于 2019-12-06 10:47:44

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)

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?

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!