When to use Spring WebMVC's Views and/or MessageConverters? - spring

I am writing an inhouse app with Spring 3.1.3 with UI for humans utilizing the VelocityView and with a REST API which serializes response entities as JSON or XML.
Now, besides the view and messageconverter thing. When would one use one of theses? I presumed that views are for humans as a general rule and messageconverters for M2M communication. Why do Views like JsonView, XmlView, etc. exist? Those outputs aren't for humans anyway.

You are essentially right - View is to convert the internal model into a "viewable" format - be it html, json, xml etc, so MappingJackJsonView, newer Marshalling View etc, if used as a view take in all the elements set in the model and transform them to xml.
MessageConverters on the other hand do things a little differently, it doesn't work on the model attributes, it works instead on the response body - transforming the response body to the appropriate format based on the ACCEPT header of the request.

Related

Responsibility of Controller or Service?

I have a question about responsibility of Controller and service about a piece of my code. I have a HTML form to save an article which can submit three image(thumbnail, summary and body) with their text. The body text can contains some images in Base64 format. I get them by a post Action which accept a DTO object to support all inputs.
The Tasks I want to do are:
Get DTO from client
Fetch images from body
Check Summary and body text rules
Check Fetched images rules
Check Thumbnail, summary and body image rules
Save them
I have a service layer here which has some class about checking article texts and images logics.
My question is that how should I act here. Which steps are for Controller and which ones for Service.
Step 2 is most confusing step to me. Should I do it in controller or just pass all DTO to Service to separate things itself?
Or about checking text, should I check for example summary text length in controller or it should be check by Service layer?
Can any one explain these to me?
Possible duplicate.
The responsibility of the controller, is to accept a request, invoke the processing, and respond according to the result of the processing.
Try to look at the SOLID principles and always try to apply them.
So first of all, DTO, it depends on your architectural design, but I would say that the DTO is the abstraction that allows you to decouple you Domain Model from the client model.
The DTO should be seen as the data representation between two layers, if the DTO crosses more than one layer, it probably isn't a DTO but a business or data entity.
) Fetch images from body
this looks like something you designed to be able to receive the desired data, but is not something your domain model cares about.
For example if your form allow you to save "Sale advert", which is made of few images and some text, probably this aggregation of data in your business layer (service), is represented by one or more domain objects, so the fact that you receive a body in whichever format, depends more on technology or transport, and should be transparent to your business layer.
A good example to help you find boundaries, is thinking about re-usability. How would you reuse your service layer if you were to use it from a WCF service for example?
Your service should always receive and expose Domain Objects.
Leave to the consumer component the responsibility to decode/encode.
3) Check Summary and body text rules (and all other checks)
seems to be a validation, but I cannot tell if this validation is only related to the domain.
Some validation is also done in the controller itself to check if the request is valid or not.
So if this check is done on the DTO structure, before you try to convert it, probably that is a controller validation, if instead, this validation is necessary to decide weather or not the input can be saved, well probably in this case it would be considered other's responsibility.
You mentioned:
for example summary text length
if this is a business rule, then I would place it in a validation object, responsible to validate the "summary text" or let's call it again "Sale advert".
The responsibility to save a domain object to a data store, is normally delegated to a Data Access Layer, which is coupled to the database structure and provides the abstraction to the business layer.
This can be done implementing a repository pattern or maybe using an ORM, I normally don't add logic to persist data in the business layer.
Another note, here you are asking about controller responsibility, but pay attention to your service "layer", I have seen often code where a huge service class, was encapsulating all the business logic and validation, that is very bad because again goes against most of the solid principles.
Look at the command query and decorator pattern, I love them because the really help you breaking down your code in smaller pieces with single responsibility.
If interest look at this example project on github (.net core).
I am still working on the documentation but should be clear enough.

Where to format non-standardized data into a standard format (View, Service, or DAO layer)?

I am using Spring MVC for my presentation layer, and am also using Spring for my Service and DAO layers. Normally I would format data in the View layer of MVC (in my case JSPs), but what if the data that is retrieved from the database is not in a standardized format?
For instance, I am pulling phone numbers from one of my company's databases, but they could potentially be in any format (111)-555-1234 or 1115551234, etc. This seems like it would be too much functionality and processing to place in the JSP/View layer. I would prefer to put all of the numbers in the same format somewhere else and then re-format on the View. Where should I format in this situation - Service layer? DAO?
This would also allow me to take advantage of libraries that I could not potentially call from a JSP (or that would not make sense to call from a JSP).
Thanks!
I would have the DAO query methods remove the formatting characters from the phone numbers, and have the presentation layer give them a consistent format (probably in JSP tags). I am not a fan of putting business logic in DAOs, but this seems extremely data-related.
(Actually if the formatting code first removes any pre-existing formatting before doing its own formatting, you might be able to get by without removing formatting characters anywhere else. I just like having things in a canonical form.)
As an alternative to putting the formatting-char-removal in the DAO, if you are using Hibernate then you can create custom user types that remove or insert formatting characters from the phone number attributes.
I generally do formatting, when I map the Model to Value object (VO or whatever you want to call them), mostly in the presentation layer (or i put a layer in between the presentation and service layer, If I have too many things to do). This brings consistency in the format across the application, if that is what you want.
When i want the name to be in camelcase, I do this
BeanUtils.copyProperties(userAccount, userAccountVO, ignoreProperties);
userAccountVO.setName(StringUtilities.convertToCamelCase(userAccountVO.getName()));

Can Content Negotiation Be Used to Control Return Types in the ASP.NET WebApi?

We're building a web api whose GET methods return DTOs. We'd like to build it so that, under certain circumstances, these DTOs are stripped of unnecessary properties in an effort to control the volume of data being sent down to the client. For example, when we return one of our email DTOs we sometimes would like the client to specify that it only needs a subject, date and ID and not the body of the email. In other scenarios, of course, the body of the email is needed.
What's the best way in the MVC WebApi to do this? I've looked into MediaTypeFormatters but they seem focused on the format of the data (JSONP, XML) rather than the content.
It sounds to me like you would like to have a custom mediatype.
This could be used in combination with a custom MediaTypeFormatter.
For instance, you could define your own mediatype (this is a bad example of a name):
application/vnd.me-shortform
And then, in your code you can omit filling in the emailbody and let the default formatter format your result.
Or you could write your own MediaTypeFormatter (subclassing an existing one) and register it for your custom mediatype.
Then, in the MediaTypeFormatter you could either through attributes on your DTO or something similar decide that the email body is not necessary and omit having it as part of the result.
Mark Seeman on Vendor Media Types should give you a good starting point.

spring - difference between request.setAttribute and model.addAttribute?

can any one tell me the difference between request.setAttribute and model.addAttribute in spring web app?
The difference is, that Model is an abstraction. You could use Spring with servlets, portlets or other frontend technologies and Model attributes will always be available in your respective views.
HttpServletRequest on the other hand is an object specific for Servlets. Spring will also make request attributes available in your views, just like model attributes, so from a user perspective there is not much difference.
Another aspect is that models are more lightweight and more convenient to work with (e.g iterating over all attributes in a model map is easier than in a request).
Request V/s Model
where request could get attributes through getAttribute("") method. normally it is used for getting information from defined attributes and used inside the method for performing the different operations. So Basically Request used for input.
Just like Request, the model provides addAttribute("","") method, Through this model, we could make the object and storing data inside model object and deploying it on result Server Page.Basically it used in storing input data which is provide by us and storing for some time.

Spring3 MappingJacksonJsonView vs. MappingJacksonHttpMessageConverter

Spring 3 includes the ContentnegotiatingViewResolver which can be used to decide on the views based on Aceept HTTP header for example.
This would be one way to render a json view, another way (which also provides mapping for incoming request bodies to objects) would be to setup the MappingJacksonHttpMessageConverter.
Which one is used best? Are there any guidelines or hints?
Thanx!
MappingJacksonHttpMessageConverter looks alike a good approach , in case you want to skip the view resolution altogether.
HttpMessageConverter would allow you to do do more like XML,etcImages,etc easily and you can also unit test them :)

Resources