Pass and get attributes from one form but more than one entity for - spring

Most of the article's talk about how to work with the forms like <form:form> Spring tags just with one bean(entity), but in my web app I have more then one bean(actually 3 of them, wich is mirror to my data model in DB(MySql)). What I want is to put values for all of the properties in my entities classes from one form(it may be a jsp or xhtml or html, whatever).
So, I'm kinda new in Spring MVC and as far as I know it has backing object which comes with <commandName> tag in <form:form> tag and I suppose to think that it may be just one commandName backing object for each form??
Q: - Could you please tell me how to easily(or direct me to any example's) to fulfil my pleasant headache.
Q: - It also may have something to get attributes in one controller class but by different methods. Do I have to store them in session or request? I'm thinking to have ModelAndView class for store multiple attributes in map and after store them in ModelAndView (in model). What you suggest?

hope you are having a wonderful day!
I'd suggest you investigate the technique detailed here:
http://forum.springsource.org/showthread.php?58993-Need-to-Populate-Form-data-into-multiple-java-beans
Also, I'm wondering if there could be a terminology issue here. Do you mean you actually want to have just one form on your UI, with a lot of inputs, or do you really mean you want it all on one SCREEN or page? I say that as its also possible to have multiple forms on one UI screen and go that route... which in fact might be easier, as you could then break up your processing into multiple controllers.
Another consideration on the above relates to screen design... if you are going to be populating the data for several beans from one screen, potentially that could be a LOT of data and your screen could get very cluttered and hard to read. So from that standpoint it might also be better to consider breaking your input controls up into multiple (related) screens. There is a little more about that at the bottom of the article I linked above.

You can refer: https://stackoverflow.com/a/4986410/1882833
One approach would be to have a seperate class which encapsules the required objects. And then use it as a command to set and get the data.

Related

View and ViewModel best practice

I have doubts whether every view should have its own ViewModel or should I pass the plain model where there is no need for ViewModel? (What concerns me is that if I start to mix these two concepts, then I will end up with jungle later on)
I tried to google it but no one talks about that, every post I run into just explains the purpose of ViewModel and I know that the main purpose of ViewModel is so you can pass multiple models to view.
It depends.
In many use cases the main purpose is not to expose fields to being bound on form submission that the user shouldn't be able to update. I wouldn't slavishly create them when not needed but it depends on the developers and their level of understanding on when and why you use viewmodels vs domain/ef models. Also application code base size makes a difference.
Maybe you need select lists, maybe you want to convert some properties to different types. Lots of reasons to use them. However it is more code and mapping code even if you use a tool like AutoMapper. So they cost time to implement but maybe they fix problems and save other time? Maybe they fix a security problem? Maybe doing them all the as view models helps juniors understand? Maybe you would rather do the setup of a viewmodel at start than convert code later when it is really needed?
Consistency can help but doing a bunch of extra work may not be worthwhile. Best practice for me isn't best practice for you.
Consider the costs and benefits for your project and team . E.g. maybe your project is internal and no one is going to try to hack via adding data to submission
There are couple of reason to choose ViewModel over DomainModel.
1) First thing first is the security. Imagin you have a view for changing the password. If you pass the domain model to the view. probably you are exposing a lot of properties which is not necessary and it may cause a security problem. There is no reason to expose properties like LastLoginDate, IsActive, IsEnabled, NumberOfFailedLogin and so on for just changing the password.
2) The second reason is reducing logic from the view. If you pass a Domain class to the view, Possibly you need to add some extra logic for hiding extra properties or shape it as you like or adding logic based on the route and etc.
3) Because of the architecture. Exposing domain model to the view cause tightly coupling between your presentation layer and domain model which is not good at all.

Problems with Spring Forms and Validation

I am newer to Spring, previously I've worked in PHP and Python. I am having some issues understanding how Spring forms work and are validated. My understanding thus far is that when you are using the your form is backed by a bean, meaning you must provide a bean to the JSP. You can also use the stand HTML forms but then you have to manually retrieve the request parameters in the controller.
Here is the issue I am having. I have a User bean that is using Hibernate Validator, and I have add, edit pages for users. The issue is I don't want the password field to appear on the Edit page, the password is going to be garbage anyway because its using BCrypt. However when the form is submitted validation fails because it expects the password to be present. There doesn't seem to be anyway to do partial bean implementation using Spring Form.
I would like to use Spring Form if possible because it reduces repetitive validation code, and its always nice to work with objects. My thoughts now are do I create an intermediate object and then translate the data from that to my bean. Seems tedious and can lead to the creation of way to many objects. My other thought is to just using plain old HTML forms and pull the params myself and set the values in the object.
I'm not sure what is the best approach or if I'm even thinking on the right track. Spring Forms and the validation is offers seems great, but seems like it isn't particularly flexible. Like I said I'm new to Spring so I may just be missing something or not understanding.
Another issue I have been wrestling with is having multiple objects needed on a form. Lets say I have a User bean, which has the following Properties.
private Role role;
private Country country;
So I need to pass User, List, and List to my JSP. I can get them to display fine, however if the form validation fails when it returns to that page, I lose my role and country objects, unless I re-add them to the model before returning the view name. Am I missing something here or is that the norm. It's a request object so I guess that makes sense but seems tedious to have to re-add them every time.
My understanding thus far is that when you are using the your form is
backed by a bean, meaning you must provide a bean to the JSP.
I'd say mostly true. The form is backed by a bean, but the Spring JSTL tags know how to get to the bean based on the set modelAttribute. The bean is living in what you would consider "page" scope, unless you add set your model attribute to be in session. Either way, if you are using the Spring JSTL tags, they are going to one or the other place to get it.
You can also use the stand HTML forms but then you have to manually
retrieve the request parameters in the controller.
Not true. You can "simulate" the same thing that the Spring JSTL tags are doing. Understand that JSTL tags are very much like macros. They are simply copying in some pre-determined block of code into the output with some very rudimentary conditional statements. The key bit that Spring MVC needs to wire the Model Attribute on the Controller side is the name and value, which are easy to decipher how those get generated/wired together.
However when the form is submitted validation fails because it expects
the password to be present.
You could create a "DTO" or "Data Transmission Object", which is basically a go-between to take the values from the UI and are converted in the Controller/Service layer to the real Model objects on the backend. Or, if you are lazy like me, put the User in session scope, in which case you don't have to post the value as Spring will take the one out of session and just updated the one or two fields you did post. Don't post the password, Spring wont set the password.
My thoughts now are do I create an intermediate object and then
translate the data from that to my bean.
Yes, this is the DTO I referred to. You only need to do it where you need to.
I'm not sure what is the best approach or if I'm even thinking on the
right track.
There are probably thousands of ways to do anything in coding, some more right or wrong than others. I know some developers who are design-Nazi's and would say you should always do it one way or another, but I am not one of those people. I think as long as you are consistent, and you are not doing something completely boneheaded you are on the right track. My #1 concern with all the code I write is maintainability. I
Don't want to spend 20hrs trying to re-learn what I did 6mo ago, so I tend to choose the simpler option
Hate repeating code, so I tend to choose more module designs
Hate having to spend 20hrs trying to re-learn what I did 6mo ago, so tend to make heavy use of JavaDoc and comments where I find the code is tricky (lots of loops, doing something weird, etc)
Another issue I have been wrestling with is having multiple objects
needed on a form.
There are several ways to deal with this too. I have never used it, but you CAN actually have more than one Model Attribute associated with the same form and Controller handler. I think you use a <spring:bind> tag or something. I have seen samples around, so Google it if you think you need that.
My approach is usually to either put something in session or build a DTO to hold all the things I need. The first I use more for things like lists to drive building the view, for instance if I have a drop down of States coming from a table. I would have a List of the States put into session and just use them from there, that way I only go after them once and done.
I use the DTO approach (some might call it a Form Bean) when I have a complex gaggle of things I need to change all at once, but the things are not necessarily connected directly. Just to point out: You can have nested objects in your model attributes and use them in your Spring JSTL tags. You can also have Collections (List, Set, Map) in your Model Attribute and get to those as well, although Spring doesn't handle nested Collections very well.
Hope that helps.

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

MVC - Who formats the model?

Before rendering into a view model should be formatted:
multilingual data localized;
date, time values formatted;
numbers formatted.
Who performs all this formatting - Controller or View?
Am I right that all the formatting is performed by the Controller which creates so called ViewModel containing only formatted values and sends this ViewModel to the View?
Thanks in advance!
Eric Petroelje is right, but I would build helper a class(es) to get localised content/dates etc, because localisation isn't always in the views, e.g. sending emails with localised content. I would have something like LocalisationHelper.GetString("MyKey"), or LocalisationHelper.GetDate(Date.Now), where the LocalisationHelper knows the users current locale (maybe from Session).
Then use this directly in the views where possible:
<%= Html.Encode(LocalisationHelper.GetDate(Date.Now)) %>
Design Patterns 101.
Model is for storing data (usually database-backed).
View is for presenting the data (not manipulating it).
Controller is for manipulating the model and passing that to the view (choosing the right locale for instance would go here).
MVC doesn't necessarily mean you have 3 distinct classes, but rather 3 components or layers. These are abstract and don't necessarily have to be tied to one physical class. Inside your Controller layer, that can consist of any number of helper classes or whatever.
I agree with part of what cartoonfox is saying, everything is intertwined. For instance, if you develop a view for a shopping cart, but the model is containing birthday information, then it isn't going to work. It is simply a design pattern to help remove duplication of effort. When you have fewer variables and less noise, it is much easier to focus on what needs to be done and understand it very well.
I had a discussion with our team about using annotations to render forms on a web page. These annotations were placed in the model or entity class. You will often work directly with entity classes, so it eliminates quite a bit of overhead and duplication of effort if you put your annotations here. Because your annotations are placed directly on the model class, you cannot end up with a view for birthday information, it just isn't possible. In addition, by following patterns, you strip out the junk that doesn't add value to the end result. You simply write the business logic and close to nothing else.
Although the annotations were in the same class as the model layer, the presentation or view layer consisted of the annotations and the helper classes. It doesn't need to necessarily be distinct classes or boundaries.
Another example would be. I've worked on some PHP web "applications" in the past. I use applications because they were a monolithic block of code, more or less a single main method with all the logic in there (which is hardly a functional application).
If you don't abstract code into functions and simply use a single method, you will end up with a lot of duplication of effort. If you tried to understand that monolithic code block, you would be in for a heap of trouble (as was I, it was hard to learn what was going on, then I would find a similar block of code somewhere else and be dumbfounded why a few things were tweaked the way they were).
It can be done any way you want, but design patterns such as MVC help you simplify what you write in order to get it to work as well as more easily wrap your head around the solution. Another popular design pattern or approach is divide and conquer.
To answer your original questions:
In Java, localized data would be done transparently by the application. For instance, if you wanted US English locale support, you would create a properties file:
messages_en-US.properties
and then place all your US English content in there. Depending on how much content this may be, you might want to use a different approach.
For my application I have whole pages in a different language so what I do is this. My controller determines the client's locale or a best match. Then it chooses which view to display and passes the model (data) to the view.
If you need dynamic formatting for your date/times, then your controller is responsible for determining which one will be used. Then, your view is responsible for using that converter to format the value.
I'm using JBoss Seam so the MVC design pattern is still used, but more abstractly. I don't have actual 'controllers', but an interceptor which is responsible for handling a specific piece of functionality (determining the client's locale, then another for their date/time preference). My controllers that would be the equivalent of a Spring Controller are action components responsible for handling page actions.
Walter
The view is responsible for this not the controller.
To explain I need to elaborate a bit about what the "view" is:
In both web-based and traditional GUI MVC patterns, the View is responsible for the external representation of whatever parts of the model that are shown. If that means "formatting" data from the model then so be it.
The controller shouldn't format the data - because the controller is responsible for doing things to the model based on events/commands coming in from the outside world. The controller doesn't have anything to do with rendering the output.
Example:
I want to display a shopping cart with several order lines:
Adding things to the cart causes the controller to change what's in the cart model.
Changing my locale causes the controller to change a setting in the user model to indicate preferred locale.
Whenever the cart is displayed, the view has to ask the model for the order lines and decide how to display that - maybe doing locale-sensitive work.
The same customer could ask to see the shopping cart in multiple different currencies. That just means changing what it looks like in the view. It's still the same shopping cart for the same customer with the same things in it.
If this is a web-app made from web template pages, you might embed code to pull in localized messages e.g. <%= message_renderer.text(:insufficient_funds) %>. In this case the "message_renderer" and the template file are both part of the view.
Views aren't necessarily just web-based templates. In some Java-based frameworks for example, we put "view objects" into a velocity template. Those view objects are linked back to objects in the model, but they also perform on-demand rendering and formatting behaviour. Those are part of the view although they're not just a template.
It's a bit confusing with frameworks like ruby on rails and groovy on grails where they call the template the "view" - when a view is really more than just a template. Traditionally (in Smalltalk MVC and in Java's Swing) views are just code that can perform formatting, rendering and any other display-related behaviour.
All that stuff seems like presentation layer logic, so personally I think it should go in the view.
ETA:
I wouldn't advocate for having the view call service layer objects in the general sense, but for localization I think it makes sense.
For example, lets say you have lots of static text on your pages that you have tokenized and stored in a database in various localized forms. I don't think it would make sense for the controller to have to lookup and put all those text tokens in the model. Even though a text token lookup is technically a "service layer" operation, I still think it makes sense for the view to call that service directly via some utility class rather than having the controller do it.

Using MVC, how should one handle communication between Views? Between Models?

Question number three in my quest to properly understand MVC before I implement it:
I have two cases in mind:
The primary application
window needs to launch the
preferences window. (One View
invoking another View.)
The primary Model for an application
needs to access a property
in the preferences Model. (One Model
accessing another Model.)
These questions are related in that they both involve communication across Model-View-Controller triplets, a topic that I haven't found much discussion of in my Googling.
The obvious way to fix this is to wrap everything in a top-level "application" object that handles transactions between Models and allows Controllers to invoke one another's methods. I have seen this implemented, but I'm not convinced its a good idea. I can also see possibilities involving Controllers observing more than one Model and responding to more than one View, but this seems like its going to become very cluttered and difficult to follow.
Suggestions on how best to implement this sort of cross-talk? I feel like its a very obvious question, but I've been unable to find a well-documented solution.
On a broader note, if anyone has a link that shows typical approaches to these sorts of MVC issues, I would love to see it. I haven't had much luck finding solid, non-trivial references. Examples in Python would be lovely, but I'll gladly read anything.
Edit 1:
I see some pretty interesting things being said below and in general no-one seems to have a problem with the approach I've described. It is already almost a lazy form of the FrontController design that Vincent is describing. I certainly don't foresee any problems in implementing that pattern, however, it doesn't seem that anyone has really addressed the question in regards to communication amongst Models. All the answers seem to be addressing communication among objects in a single Model. I'm more interested in maintaining separate Models for separate components of the application, so that I'm not stuffing fifty state properties into a single Model class. Should I be maintaining them as sub-Models instead?
With respect to (1), views don't invoke other views. They invoke controller actions that may result in other views being rendered. In your case, the primary application window contains a user interface element (button, link) that invokes a controller action to display the preferences window.
With respect to (3), model components certainly could be related to one another. This isn't unexpected nor to be avoided, necessarily. For instance your Customer model may have an associated set of Orders. It would be perfectly natural to access the customer's orders via a method in the Customer class.
You might want to take a look at the MVC page on wikipedia for an overview.
You may want to consider looking up the Front Controller design pattern.
The Front Controller pattern defines a single component that is responsible for processing application requests. A front controller centralizes functions such as view selection, security, and templating, and applies them consistently across all pages or views. Consequently, when the behavior of these functions need to change, only a small part of the application needs to be changed: the controller and its helper classes.
This way all requests from the view goes to the FrontController who then decides which specific action (controller) to invoke. Sometimes, it could forward straight to another view as in your first case.
There is no problem with multiple objects in the model talking to each other. In fact that will be very common. The way I see it, all the objects in the Model act like one component to represent the data and operations on the data.
This article might help. And this one.
Model does not mean a single model object. The model is the subset of the entirety of your domain model which is directly related to the controller actions and the views in question.

Resources