Creating objects from request - java

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?

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.

Related

Details on how front end interacts with back end?

Consider this line of jsp code:
function clearCart(){
cartForm.action="cart_clear?method=clear";
cartForm.submit();
}
Clearly it's trying to call a method on the back end to clear the cart. My question is how does the service (Tomcat most likely, correct me if I'm wrong) which hosts this site that contains this snippet of code know how and where to find this method, how it "indexes" it with string values etc. In my java file, the clear method is defined as:
public String clear( )
{
this.request = ServletActionContext.getRequest();
this.session = this.request.getSession();
logger.info("Cart is clearing...");
Cart cart = ( Cart ) this.session.getAttribute(Constants.SESSION_CART );
cart.clear();
for( Long id : cart.getCartItems().keySet() )
{
Item it = cart.getCartItems().get(id);
System.out.println( it.getProduct().getName() + " " + it.getNumber()
);
}
return "cart";
}
By which module/what mechanism does Tomcat know how to locate precisely that method? By copycatting online tutorials and textbooks I know how to write these codes, but I want to get a bit closer to the bottom of it all, or at least something very basic.
Here's my educated (or not so much) guess: Since I'm basing my entire project on struts, hibernate and spring, I've inadvertently/invariably configured the build path and dependencies in such ways that when I hit the "compile" button, all the "associating" and "navigating" are done by these framework, in other words, as long as I correctly configured the project and got spring etc. "involved" (sorry I can't think of that technical jargon that's on the tip of my tongue), and as long as I inherit a class or implement an interface, when compiling, the compiler will expose these java methods to the jsp script - it's part the work done by compiler, part the work done by the people who composed spring framework. Or, using a really bad analogy, consider a C++ project whereby you use a 3rd party library which came in compiled binary form, all you have to do is to do the right inclusion (.h/.hpp file) and call the right function and you'll get the function during run time when calling those functions - note that this really is a really bad analogy.
Is that how it is done or am I overthinking it? For example it's all handled by Tomcat?
Sorry for all the verbosity. Things get lengthy when you need to express slightly more complicated and nuanced ideas. Also - please go deep and go low-level don't go too deep, by that I mean you are free to lecture on how hibernate and spring etc. work, how its code is being run on a server, but try not to touch the java virtue machine, byte code and C++ pointers etc. unless of course, it is helpful.
Thanks in advance!
Tomcat doesn't do much except obey the Servlet specification. Spring tells Tomcat that all requests to http://myserver.com/ should be directed to Spring's DispatcherServlet, which is the main entry point.
Then it's up to Spring to further direct those requests to the code that handles them. There are different strategies for mapping a specific URL to the code that handles the request, but it's not set in stone and you could easily create your own strategy that would allow you to use whatever kind of URLs you want. For a simple (and stupid) example you could have http://myserver.com/1 that would execute the first method in a single massive handler class, http://myserver.com/2 would execute the second, etc.
The example is with Spring, but it's the same general idea with other frameworks. You have a mapper that maps an URL to the handler code.
These days it's all hidden under layers of abstraction so you don't have to care about the specifics of the mapping and can develop quickly and concentrate on the business code.

Returning list using #Responsebody or return ModelAndView from spring controller which one better

First of all my language is not good and sorry for that and i am working with small organization and i am not getting coding standards or suggestions in the office .so let me know to which process uses in the well defined java projects among return List,Map and model object OR return ModelAndView from Controller in spring.Because for complex tables in the jsp's i think myself its not the better way to return json formatted List and handle them using jquery instead of that just throw a model and view and use static html components in the jsp's and populate the tables using model object.If you suggest return Collection List i need to add jackson processor jar files and having nearly 1mb size otherwise an jsp just 2kb size. Please help me to follow the correct way in what cases we generally use among one.Thanks in advance
Viswam,
The answer depends mostly on your application and the functionality you want to achieve, there is no standard solution here.
If your application is a single page application (read this wikipedia article) or you want RESTful application, I would suggest to stick with #ResponseBody, reason is simple, it supports AJAX and basically doesnt change the page from Server side.
You can easily populate any complex table using plain JavaScript or jQuery from the JSON response you receive.
Also if I were to think, I wouldn't want to waste my resources at server side for populating data in JSP and then send it over to client(browser) when it can do this by itself. But this is strictly a personal choice/preference.
And, If you need to redirect to or reload a page, I believe ModelAndView is the way to go.
Suggestion : You can check the Spring Code from various tutorials and projects on GitHub or similar platforms/blogs to learn how to keep your code clean and readable.
The best way to learn Best Practices is first code-reading and second actually Practicing them.
Also I dont think a dependency of 1 MB size should be a headache in today's world.

Rails application, but all data layer is using a json/xml based web service

I have a web service layer that is written in Java/Jersey, and it serves JSON.
For the front-end of the application, I want to use Rails.
How should I go about building my models?
Should I do something like this?
response = api_client.get_user(123)
User user = User.new(response)
What is the best approach to mapping the JSON to the Ruby object?
What options do I have? Since this is a critical part, I want to know my options, because performance is a factor. This, along with mapping JSON to a Ruby object and going from Ruby object => JSON, is a common occurance in the application.
Would I still be able to make use of validations? Or wouldn't it make sense since I would have validation duplicated on the front-end and the service layer?
Models in Rails do not have to do database operation, they are just normal classes. Normally they are imbued with ActiveRecord magic when you subclass them from ActiveRecord::Base.
You can use a gem such as Virtus that will give you models with attributes. And for validations you can go with Vanguard. If you want something close to ActiveRecord but without the database and are running Rails 3+ you can also include ActiveModel into your model to get attributes and validations as well as have them working in forms. See Yehuda Katz's post for details on that.
In your case it will depend on the data you will consume. If all the datasources have the same basic format for example you could create your own base class to keep all the logic that you want to share across the individual classes (inheritance).
If you have a few different types of data coming in you could create modules to encapsulate behavior for the different types and include the models you need in the appropriate classes (composition).
Generally though you probably want to end up with one class per resource in the remote API that maps 1-to-1 with whatever domain logic you have. You can do this in many different ways, but following the method naming used by ActiveRecord might be a good idea, both since you learn ActiveRecord while building your class structure and it will help other Rails developers later if your API looks and works like ActiveRecords.
Think about it in terms of what you want to be able to do to an object (this is where TDD comes in). You want to be able to fetch a collection Model.all, a specific element Model.find(identifier), push a changed element to the remote service updated_model.save and so on.
What the actual logic on the inside of these methods will have to be will depend on the remote service. But you will probably want each model class to hold a url to it's resource endpoint and you will defiantly want to keep the logic in your models. So instead of:
response = api_client.get_user(123)
User user = User.new(response)
you will do
class User
...
def find id
#api_client.get_user(id)
end
...
end
User.find(123)
or more probably
class ApiClient
...
protected
def self.uri resource_uri
#uri = resource_uri
end
def get id
# basically whatever code you envisioned for api_client.get_user
end
...
end
class User < ApiClient
uri 'http://path.to.remote/resource.json'
...
def find id
get(id)
end
...
end
User.find(123)
Basic principles: Collect all the shared logic in a class (ApiClient). Subclass that on a per resource basis (User). Keep all the logic in your models, no other part of your system should have to know if it's a DB backed app or if you are using an external REST API. Best of all is if you can keep the integration logic completely in the base class. That way you have only one place to update if the external datasource changes.
As for going the other way, Rails have several good methods to convert objects to JSON. From the to_json method to using a gem such as RABL to have actual views for your JSON objects.
You can get validations by using part of the ActiveRecord modules. As of Rails 4 this is a module called ActiveModel, but you can do it in Rails 3 and there are several tutorials for it online, not least of all a RailsCast.
Performance will not be a problem except what you can incur when calling a remote service, if the network is slow you will be to. Some of that could probably be helped with caching (see another answer by me for details) but that is also dependent on the data you are using.
Hope that put you on the right track. And if you want a more thorough grounding in how to design these kind of structures you should pick up a book on the subject, for example Practical Object-Oriented Design in Ruby: An Agile Primer by Sandi Metz.

Where to validate data in a web app (using Spring)

This is a follow-on to my question Spring Web MVC - validate individual request params.
I've figured out how to invoke the Spring Validator on domain objects that have been created from my inputs and how to have that validator honor the JSR-303 annotations on my classes themselves. The part I can't figure out is where in my code to perform this validation. The obvious approach is to do it in the controller and return a different model and view if there's a validation failure.
But I also have a service layer which sometimes gets calls to create/update objects from input sources other than the web controller. So it's tempting to implement validation there, but the only obvious way I can think of to report a failure is throw an exception. I see Spring provides BindException but the Javadoc also basically says not to use it in application code.
What is the common/recommended practice here?
I think the answer is both.
Controllers are associated with views. You don't want the validation to disappear if you change view technologies.
Services should assume that no one is safe and validate all incoming parameters.
Other answers are all good, I'll just state one important rule:
Each subsystem/layer should validate its input, no matter where it comes from.
When you encapsule the validation logic inside of a ValidationService you can use it inside your controllers and services. As you want the user to interact with the input and to correct invalid information you should be able to display validation problems in your web view.
Sometimes you might have data (CommandObjects, Forms) which is not directly visible in the service layer and then the validation should be done in the controller which then passes the information into the service layer.
When you design your application you should think about the interaction between each layer. Mixinig validation logic into every layer might not be needed. Think about how data gets into your system. If controllers are your main entry point you can perfectly place it there since no data gets into your services without passing the validation.
At least you should validate inputs at the service layer, in order to guarantee correctness. Additionally you can do validations further up to get better usability, etc. if needed.

One or multiple servlets per webapp?

I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.
Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.
So, what are your experiences, what works best?
Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.
That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.
So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.
[EDIT] Re-reading your question it seems as if you are using the term site to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.
Most web frameworks use a dispatcher servlet (ex: Spring MVC) that takes care of routing requests to appropriate classes/controllers.
When you start having lots of pages, this approach works best because you have a more user friendly way (in regard to web.xml) of declaring/managing a class that handles http requests and its url. Example (spring mvc again):
#Controller
public class MyController {
#RequestMapping("/viewPosts")
public void doViewPosts(HttpRequest r, HttpResponse res) {
//...
}
}
Besides, having a dispatcher servlet keeps your code flow centralized.
It depends.
In my latest projects, I have implemented a single servlet that delegates to several servlet-like objects which are instantiated in a dependency injection fashion. For instance, I have something like this in my servlet (pseudo-code):
for(Handler handler : handlers) {
if(handler.handle(request, response)) {
return;
}
}
where Handler is an interface with a boolean handle(request, response) method. I obtain my handlers from a container (be it Spring or something even more lightweight).
The reason for this is that I really like dependency injection, and it is difficult to achieve it in Servlets; and I really don't feel much at home with most frameworks that provide web-component dependency injection- I like the simplicity of servlets.
Were not for this, I would go with multiple servlets, although there's a trade-off; either you have an enormous web xml with lots (and lots) of servlet mappings or you have a very complex servlet (unless you use something like my d-i approach).

Categories

Resources