tags:

views:

36

answers:

2

I'm working on some user related tasks for a website. For cases when the person is registering or editing a user, they fill out a form and the request is handled in a servlet. At the moment, the servlet is taking all the request parameters and building a User object from them, like this:

User toRegister = new User(request.getParameter("name"),
        request.getParameter("lastName"));

There's more parameters but you get the point.

So this sort of code is being reused in a bunch of different servlets (registering, admin adding user, user updating self, admin updating others etc) and it's kinda ugly, so I wanted to clean it up. The two alternatives I could think of were a constructor that takes the request object or a static method in the User class to create and return a new User based on the request.

It's not much of a question since I know they would both work but I couldn't find any sort of best practices for this situation. Should I keep to handling the requests individually in the servlets in case the forms change or should I implement one of the above methods?

A: 

DON'T add a c'tor that takes a Request as an argument. You only couple your User class to the Servlet API this way.

Instead use a Web Framework as @skaffman suggests. There are many of these, and it will make your life easier.

EDIT: If you refuse to learn a new framework you can at least use BeanUtils of some similar framework to do the data binding only. I do recommend the Web Framework option though.

Eran Harel
OK i'll check out some frameworks.
Daniel
If you decide to use BeanUtils, here's the class you are looking for: http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/PropertyUtilsBean.html - create a utility method that iterates the parameters of the request and sets those properties on the object.
Kevin Day
A: 

Instead of coding all the business logic in the servlet, why dont you use basic MVC framework. Using a framework will make your coding and testing a lot easier.

Swapna