简体   繁体   English

根据请求创建对象

[英]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. 对于该人正在注册或编辑用户的情况,他们填写表单,并在Servlet中处理请求。 At the moment, the servlet is taking all the request parameters and building a User object from them, like this: 目前,该servlet正在获取所有请求参数并根据它们构建一个User对象,如下所示:

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. 因此,这类代码可在许多不同的servlet中进行重用(注册,管理员添加用户,用户更新自我,管理员更新其他人等),而且有点丑陋,所以我想对其进行清理。 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. 我可以想到的两个选择是一个构造函数,该构造函数使用请求对象或User类中的静态方法来基于请求创建并返回新的User。

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? 如果表单发生更改,我应该继续在servlet中单独处理请求还是应该实现上述方法之一?

DON'T add a c'tor that takes a Request as an argument. 不要添加以Request为参数的变量。 You only couple your User class to the Servlet API this way. 您只能通过这种方式将User类耦合到Servlet API。

Instead use a Web Framework as @skaffman suggests. 而是使用@skaffman建议的Web框架。 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. 编辑:如果您拒绝学习新的框架,则至少可以使用某些类似框架的BeanUtils仅执行数据绑定。 I do recommend the Web Framework option though. 我确实建议使用Web Framework选项。

Instead of coding all the business logic in the servlet, why dont you use basic MVC framework. 而不是在servlet中编码所有业务逻辑,为什么不使用基本的MVC框架。 Using a framework will make your coding and testing a lot easier. 使用框架将使您的编码和测试容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM