When to use spring web flow over spring mvc - spring-mvc

Is it fair to say that the most important justification to use Spring Webflow over Spring MVC is this:
Using Spring MVC, the different stages of the workflow needs to be in code. i.e. If Stage 1 ends in success, in the Controller we need to forward to the jsp for stage 2 and so on. In SPring MVC, we cannot do it in xml file.
But in Spring webflow we can configure the flow in xml file without touching code.
Is this wrong or over simplification? I looked at http://forum.springsource.org/showthread.php?16393-Difference-between-Spring-MVC-Web-Framework-and-Web-Flow and was trying to make a summary of the explanation.

If your application have complex Flow pages, events which need to be defined as Finite state machin then use Webflow. It would be justified to use webflow for website where you buy Insurence, Flight Tickets.
Otherwise use normal MVC framework like Struts, learning curve for webflow can be bit hard than other MVC frameworks.
I would say below point mentioned in post is fully justified.
The main point: webflow is a powerful controller. That's it. Use it when you need its power. use plain old controllers where you don't.

Taken from http://forum.spring.io/forum/spring-projects/web/web-flow/7159-difference-between-spring-mvc-web-framework-and-web-flow
MVC is an implementation of the Model View Controller design pattern, webflow is an implementation of a "web flow" state machine.
Web flow sits on top of springs MVC and allows you to define complex navigational flows.
Quite simply; if you have lots of independent single pages, which don't do much and don't interact, use plain old MVC. If you have a set of pages that represent a workflow, use webflow to model the workflow. If you have both; mix and match

Related

Why is Razor Pages the recommended approach to create a Web UI in Asp.net Core?

Learning new things needs an investment of time, space and energy. I am currently learning Asp.Net Core MVC 2.0. This ASP.NET Core tutorials overview states:
Razor Pages is the recommended approach to create a Web UI with ASP.NET Core
This information confused me in deciding whether I have to stop learning Asp.net Core MVC and start learning Asp.net Core Razor Pages.
Why is Razor Pages the recommended approach to create a Web UI in Asp.net Core?
Any directions are welcome.
From this article in Microsoft docs:
MVC: Using controllers and views, it was common for applications to have very
large controllers that worked with many different dependencies and view models and returned many
different views. This resulted in a lot of complexity and often resulted in controllers that didn’t follow
the Single Responsibility Principle or Open/Closed Principles effectively.
Razor Pages addresses this
issue by encapsulating the server-side logic for a given logical “page” in a web application. A Razor Page that has no server-side logic can simply consist of a Razor file (eg. “Index.cshtml”). However, most non-trivial Razor Pages will have an associated page model
class, which by convention is named the same as the Razor file with a “.cs” extension (for example, “Index.cshtml.cs”). This page model class combines the responsibilities of a Controller and a ViewModel. Instead of handling requests with controller action methods, page model handlers like “OnGet()” are
executed, rendering their associated page by default.
Razor pages simplify the process of building
individual pages in an ASP.NET Core app, while still providing all the architectural features of ASP.NET Core MVC. They are a good default choice for new page-based functionality.
When to use MVC:
If you’re building web APIs, the MVC pattern makes more sense than trying to use Razor Pages.
If your project will only expose web API endpoints, you should ideally start from the Web API project
template, but otherwise it’s easy to add controllers and associated API endpoints to any ASP.NET Core
app. You should also use the view-based MVC approach if you’re migrating an existing application
from ASP.NET MVC 5 or earlier to ASP.NET Core MVC and you want to do so with the least amount of
effort. Once you’ve made the initial migration, you can evaluate whether it makes sense to adopt
Razor Pages for new features or even as a wholesale migration.
Note:
Whether you choose to build your web app using Razor Pages or MVC views, your app will have
similar performance and will include support for dependency injection, filters, model binding, validation, etc.
Update: Some more reasons i read on this github issue commented by scott sauber:
We're using Razor Pages for a [complex] Health Insurance portal... We have 60+ pages and I can say that for Server-rendered HTML, I will never go back to MVC. It's also not just for simple things. The Health Insurance domain is inherently complex and combine this with the fact that it's a multi-tenant app (we sell the product to other insurance companies), which adds more complexity as the app is highly configurable as different insurance companies do things a bit differently.
Why use it?
Razor Pages is more secure by default. Razor Pages gives you AntiForgeryToken validation by default. Plus you opt-in to what properties you want to be model bound via [BindProperty] which limits your exposure to over-posting attacks.
Razor Pages has a better folder structure by default that scales better. In MVC, the default folder structure simply does not scale. Having separate folders for Views, Controllers, and often ViewModels when all three are ultimately tightly coupled to one another is a huge PITA to work with. You end up bouncing to all 3 folders and navigating a bunch anytime you need to add or change a feature. It's horrible. This is why I advocated for Feature Folders. With Razor Pages, your PageModel (Controller + ViewModel) are in the same folder as your View. You can just hit F7 to toggle between them which is also super convenient.
Leads to more maintainable code that scales better. With MVC it was super easy to bloat a Controller with 10+ Actions. Often, these Actions weren't even related to one another in any way (except maybe a Redirect between the two). This made navigating the Controller to find code very difficult. It got worse if there were private methods in the Controller too, further adding to the method bloat. With Razor Pages, it's nearly impossible to bloat up your Page Model with unrelated methods to your page. Everything you put in your PageModel is related to your Page.
Unit Testing is easier. With a Controller, you might have 8 Actions and some of your dependencies you inject in were only related to one or two Actions. So when unit testing a single Action either you need to mock those out unnecessarily or pass a null, both of which feels gross (this can be solved a bit with the Builder pattern). With Razor Pages, the dependencies you inject in are 100% related to GET and POST actions you're working with. It just feels natural.
Routing is easier. By default in Razor Pages, routing just matches your folder structure. This makes nesting folders way easier to accomplish. For instance, all of our HR Admin pages are under the /Administrator folder and all the Employee pages are under the /Employee folder. We can authorize an entire folder and say the person must be an Administrator to get to any subfolder of /Administrator, which was way easier to do that than with multiple Controllers that make up the Administrator features.
I think that's the big stuff.
Update 2:
This is about some complexity of MVC pattern, does not directly answer the question but can be useful: An Engineering Manager at Facebook, said (here) for their “sufficiently” large codebase and large organization, “MVC got really complicated really quickly,” concluding that MVC does not scale. The complexity of the system went exponential every time they attempted to add a new feature making the code “fragile and unpredictable.” This was becoming a serious problem for developers new to a certain codebase because they were afraid to touch the code lest they might break something. The result was MVC was falling apart for Facebook.
Razor Pages are optimized for page-based workflows and can be used in these scenarios with fewer moving parts than traditional MVC models. This is because you don't need to deal with Controllers, Actions, Routes, ViewModels, and Views (as you typically would). Instead your route is convention-based, and your PageModel serves as your Controller, Action(s), and ViewModel all in one. The page, of course, replaces the View. You also don't have to have as many folders as you would in MVC, further simplifying your project.
From ASP.NET Core - Simpler ASP.NET MVC Apps with Razor Pages, a Sept. 2017 MSDN article by Steve Smith:
[Razor Pages] provide
a simpler way to organize code within ASP.NET Core applications, keeping implementation logic and view models closer to the view implementation code.
They also offer a simpler way to get started developing ASP.NET Core apps,
That article has more information on why to use Razor Pages over MVC for page-based workflows. Obviously, for APIs, you will still want to use Controllers.
3rd party edit - disadvantages of classical MVC folder organization
ASP.NET Core - Feature Slices for ASP.NET Core MVC, an older MSDN article from Sept. 2016, describes why the classical MVC convention to organize views and controller might have disadvantages for larger projects. The article gives an example of four loosely related application concepts: Ninjas, Plants, Pirates and Zombies. The article outlines a way to structure them outside of the default folder convention by organizing files into folders by feature or area of responsibility.
Microsoft is coming back to the WebForms approach to simplify the project structure trusting in the "Convention over configuration" mantra, while hiding the configuration from developer to make things faster. But it has the disavantage that everything will be mixed again. It doesn't look like a smart move for organizing. But... Hey! Something new must catch the attention of the dev towards Microsoft.
If your page uses an MVC Web API for the REStful, it's really more easy to just use Razor pages. If not, I would recommend you to use Core MVC.
In huge projects, where the model and controller are together in the same file, maintenance will be a nightmare. It works well for clases that are just 2 properties long, but it violates the Open Close Principle of OOP. You should design and use an architecture that can grow with time (Extensible) and still be stable and logic(No reestructuring the project), just extend it using the same pattern.
As a Software Architect I use design patterns automatically. What I like a lot is the Facade design pattern. You hide everything related to Home behind a HomeController and you can do the same with Repositories.
Want to know a funny thing? A tour guide explained where the name
Facade comes from. In Amsterdam you have big houses across the waters.
From the outside they look luxureous. But from the behind they can be
messy. The facade of the house hides whats behind it. Design patterns
comes from the building world. Well whats behind in my applications
also looks good but it was nice to know from the tour guide about the
explanation.
What about support for Sharing and Grouping actions in Razor pages. If you look at MVC Controllers you can see that you can Group controller actions based on functionality. You could say the Home page is such a functionality. Then you have a HomeController with About() and Contact() in it, but with Razor Pages this would be different pages. May be you have a big HomeController with lets say 5 other Views in it. They can all be grouped in the same HomeController.
A Controller has two things a Razor Pages does not have:
Sharing: You can share Controller actions between different pages, sometimes controller actions are not bound only to one page but can be shared between several pages. Remember Controller actions can also only return Data (JSON/XML/etc). Sometimes what they return can be used by different pages too.
Grouping: You can group related Controller actions together in one Controller. Ok if you are a fan of small Controller files you won't do this. I do. I group my Controllers based on functionality. That makes navigation much easier.
What is the Razor pages way of handling this: Use of directories I think:
Grouping: If we have the HomeController, then we could make a subdirectory Home with all the Home pages in it.
Question: For a simple Home that would be enough. But lets say we have an XController that uses for all actions the same Repository. You could initialize that Repository in the Initializer function of the XController. But for pages in the X subdirectory you would have to do that for all X actions again. Is that DRY?
Sharing: You could make a "Share" subdirectory and under that, directories with functionality that should be shared between pages.
Question: If you look at my fix you can see I use directories to solve the Share and Grouping problem of Razor pages.
How would you do this?
or...are Razor pages just meant to be for simple websites, could this be the conclusion for this version of Razor pages.
Blazor server has a strange architecture. It looks like a chat application by use of SignalR. My experience with applications like that is that events can get lost. I don't want to lose events, better is they are stacked and guaranteed to be processed like mail.
Developers were on forums in 2013 asking "What does Microsoft mean, Silverlight is not the recommended ...???"
Only this time, it is that MVC is going to be pronounced dead and long live MVVM.
And you can likely expect MVC to be thrown to the scrap heap, slowly, but sped up in about 18 months from now, and any and all time you spent learning MVC will go to that same scrap heap.
Also, MVVM looks easy but it takes a year to get the hang of it and really do it right.

Modernizing Struts 1.x Application

I would like to modernize my Struts 1.x application. There are quite a number of articles which advocate migration of codes, instead of rewriting the entire system.
I would like to seek the advice of someone who has successfully modernize legacy applications.
My current system is using struts 1.x and JDBC prepared statements as the data access layer.
I am looking forward to improve the legacy application with the following objectives:
Web Pages should be coded with Responsive Web Design in mind.
Replace struts 1.x with Spring MVC
I am looking to breaking up the modernization into the following phases:
Phase 1 - Change all jsp pages to HTML 5 and CSS 3
Phase 2 - Change all DAO classes to Spring JDBC Template or Spring JPA
and transactions managed by Spring
Phase 3 - Ultimately, replace Struts 1.x Action Forms, Actions with Spring MVC
Before I start the changes, I would like to find out if it is possible for:
Struts 1.x with HTML 5 and CSS 3? I am looking at replacing all struts 1.x html taglibs with HTML 5 and JSTL/EL.
Running Struts 1.x with Spring 3/4? Is it possible to run non-spring managed pojo with Spring beans?
What should I take note of and how/what are the best practices to handle this modernization process? The code base is about 500k of HTML/JSP codes and 3 million Java codes.
It's been a while since I last worked with Struts 1.x, but I see no problem replacing at least most of the Struts tags with JSTL/EL. You should be able to paint HTML5 with Struts 1.x JSPs. I remember working using little or no Struts tags, only JSTL/EL, but this was before HTML5.
You can invoke Spring Context from any Struts ActionForm or, essentially any class within your webapp. You'll probably have to do it manually though and not with annotations, something like this:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
With all this said, I can see you're intending to do a serious update of your app, therefore I must ask, are you positive about keeping Struts 1.x? If you want to ditch Struts tags, use Spring 3/4 and HTML 5, why not dispense with Struts entirely and migrate your app to Spring MVC? It's very easy to use, powerful and, needless to say, it integrates perfectly with the Spring components implementing your business logic, persistence, etc.
Cheers.
(Not an answer, informational.)
There's no reason you can't have an S1 app running alongside Spring MVC. It's a reasonable way to migrate piece-by-piece instead of a longer project that does a complete replacement.
Older Spring has direct support for Struts 1. Depending on your timeframe I might consider using the older Spring until you're further along.
Replacing S1 tags with pure HTML/CSS will be a pain because the S1 tags render other stuff besides just the input fields (e.g., labels, error messages, etc.) It's totally doable, especially if you write your own custom tags.
jQuery v. (AngularJS | React | similar) Switching to a full-on client-side app is a big lift, especially if your back-end isn't already designed that way. I wouldn't do that, but you could get a start on it by putting business logic in its own place and using that from the web layer. Then...
... you start to consume API calls on the client side using jQ or other client-side framework injected into the existing pages. Only then would I start considering going full SPA.
The bottom line is you have a fairly large app. Rather than converting the entire thing I would consider removing functionality from the mainline app and break it up into sub-applications, each of which could use whatever tech stack seems reasonable.
I've done a lot of project like this as a consultant: it's a lot of busywork that requires a wide range of knowledge and skills, and it's difficult to get right.

Asp.net web api and mvc - avoiding duplication

I am exploring ASP.Net web Api and I am trying to use to create a web page to basically provide option to edit and display some data from DB(MySQL) with some modifications. I also want to provide a REST Api that would be used by mobile app. Now I can do this with the ApiController(to provide REST api) and then the MVC Controller which renders the model(using View method). This works but there is lot of duplication between the API and the MVC controller. Is there a design pattern or something that avoids the redundancy?
I understand that API controller has to return JSON and the MVC controller has to return the Model for the view.
There are two general paths you can follow to remove duplication.
Use js frameworks and rely on the rest API for all data. Knockout, breeze and countless other frameworks exist to support this, because it is how SPAs are made. You can get lost in all the frameworks, so when you find the ones you like, learn them and run with them. I'm using this structure on my latest web app with knockout and sammy (for routing)
Fat model, skinny controller. How you actually handle this depends on the complexity of your data. MVC can have multiple layers. You could use the API's view as the model in the MVC's controller and view. You could present a DAL that handles queries and reference that from both controllers. Either way duplication is removed.

How to convert struts2 to SpringMVC

I don't want to debate whether or not to undertake the conversion from struts2 -> SpringMVC. I have the best reason to do it. It is what the customer is asking/paying for.
I've done struts1 years back and I've done SpringMVC. I'm hoping to configure via xml and not use Annotations that much.
My plan is to:
Take each struts2 action class, understand what action is taking place and then create a clean API for delegating to the business layer. This step is not required. It is here so we can refactor whatever makes sense.
Create a SpringMVC Controller (roughly) for every struts 2 action class.
I know that is just touching the surface of what needs to be done. Anyone have anything else to add?
Thanks in advance,
Andrew
If the struts2 actions were created properly there would be a clean API to the service layer already. Hopefully the Struts2 application is already using Spring DI. Struts2 objects could be reused. But the web layer is relatively thin so it would be best to remove any trace of the struts2 actions to simplify further development, rather than leaving weird artifacts.
There are four main parts that a user of struts is responsible for.
The Action Class
Struts2 specific tags in the view layer
Validation
Interceptors
The action class as already mentioned should be quite thin, it's main purpose is to marshal objects on their way to the view. (To marshal them it will need to set form parameters and validate them). If the objects are acquired from the service layer, then you should be able to mostly cut and paste the logic over into Spring Controllers. If you find logic that should be in the service layer, it should be pushed up.
The tags in the view layer I'm not so sure about. Probably best to replace struts specific tags with jstl tags where possible. Struts2 does not have a huge tag set, and there should be a pretty much one to one mapping between the tags but you'll need to figure out what that mapping is (and which tag lib is best).
Validation - I don't know how Spring MVC does validation.
Interceptors address cross cutting concerns, I don't know how Spring interceptors work. Spring could address the issue of custom interceptors probably with AOP.
All in all, the web tier shouldn't be very invasive... and I'm not sure what you'll gain. Be aware that if your current S2 application is not using Spring DI it is quite easy to add, along with AOP and you can even delegate the creation of actions to Spring. As such I would expect very little return in such a conversion. As an alternative, it might just be easier to start building what you need with Spring MVC, and turn the struts2 actions into web services (json is ridiculously easy). Then dismantle them piece wise when you have the time to implement them in Spring MVC. A conversion means understanding two systems and mapping them, it is messy and error prone... this has the same end effect (the removal of the struts2 framework) but would allow for productivity as well.

On which pattern are ASP.NET webforms and MVC based? PageController, FrontController?

I am trying to understand the ASP.NET WebForms and MVC from the point of view of understanding the design patterns used.
While MVC clearly looks like an implementation of FrontController, I am not very sure about WebForms pages. So, I would appreciate if anyone can help with the following questions around this.
Is WebForms based on a PageController pattern?
Are Front Controller and Page Controller both modified versions of MVC?
Can WebForms also be called a special case of MVC where distinction between controller and view is blurred?
Finally, are there any good resources on the web that can provide a detailed reference on this topic?
ASP.NET MVC is based on the Front Controller design pattern. Classic ASP.NET WebForms are based on an effort from Microsoft to bring Windows Forms event model to the web by hiding and abstracting many parts and you could apply the page controller pattern but out-of-the box it is not.
Following the order of your questions:
1//No. Webforms are based on the the "Smart UI" pattern, ie, you control the app by writing event handlers. Smart UI has its issues, but when entirely based on the desktop it works OK, in the sense that no major "fiction" is introduced into the framework for it to work. With the web, however, that works over stateless HTTP, a major fiction is introduced, essentially in the form of the ViewState that holds the state of all the controls when the page was sent to the client browser. As a result, web forms introduce a layer of complexity into your applications that is only there to sustain this ficiton. MVC eliminates this fiction.
The fiction essentially says: We will pretend that HTTP is not there between us and the client.
2//MVC removes the fiction and gives you naked HTTP. However it is more based on the Front Controller than the Page Controller pattern in that the Page Controller pattern makes testing the controller independently of Http requests is difficult, whereas MVC is specifically designed to make the controller testable independently of HTTP requests. In other words, MVC is designed to enable unit testing on the controllers as opposed to integration testing.
MVC focuses on the separation of the Model from the View, whereas Webforms/Smart UI does not make this distinction.
I suppose you could say, to eliminate the Page Controller from ASP.NET MVC, that ASP.NET refactors the impact of HTTP on the controllers to "orthogonal attributes", which is not the way I am led to believe that the Page Controller pattern works. However, don't quote me on this, I am a student of these things, not an expert.
3//No definitely NOT! As discussed above, webforms are fictional smart ui, NOT MVC in any shape or form. You can go through a few hoops to make them sort of MVC ish (a la Dino Esposito), but this is again a ficiton. Why indulge in the fiction if you have ASP.NET MVC?
A final broadside. The reason I switched from webforms to mvc was the Wizard Server Control. Its "Event Model" is a thing of cruelty that flies in the face of everything I needed to achieve (not to mention the choking proliferation of other properties, methods... Yuck!).
In 10 days I wrote a base WizardController and now my wizards are things of beauty, elegance and simplicity. I have joyfully thrown away 3 months of work on wizards in webforms to convert them to my new mini wizard framework. It is THAT bad.
As far as references on this topic I would recommend both the book "Microsoft .NET: Architecting Applications for the Enterprise" by Dino Esposito and Andrea Saltarello as well as Dino's ASP.NET Presentation Patterns article.

Resources