开发者

Creating objects from request

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 upda开发者_运维知识库ting 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜