Spring 4: Individual view layouts depending on request - spring

I am using Spring 4 MVC to display serve my web page. I now want to display the same content with different layouts wrapped around the body/content depending on the current HttpServletRequest (e.g. request.getServerName()). This means https://page1.test/page.html will be mapped to the same controller as https://page2.test/page.html and returns the same content depending on the controller logic, but page1.test draws for example a different header and footer.
As far as I know, Spring MVC is not capable of doing this. I am now planing to use Apache Tiles 3 or JSP 2.0 tags to do this. Is there any best practice and how can I do this (Spring Java Config is preferred)?

You should take a read of http://tech.finn.no/2012/07/25/the-ultimate-view-tiles-3/ just to see how far you can push Tiles-3
Indeed it can solve what you're after.
(That blog website has just been migrated from wordpress to github pages so some of the code snippets require horizontal scrolling, we're still cleaning these small formatting issues up so please excuse them)

Related

Is JSP necessary for Angular2 security for different roles

I am build an application using Angular2 as front end framework and spring boot as backend framework.
One of the seniors in my team insisted on using JSP as templates for my components in order to avoid rendering any unauthorized views.
Is that really nessecary? I saw many applications which are implemented using angular or other front end frameworks but it did not render the templates in backend, is it a good practice? isn't authenticating the requests is enough?
Also would not that be a problem for performance?
From my point of view I think JSP will prevent us from using the potentials of Angular, any help or documentation on that subject would be much appreciated.
Short: No, JSP is not necessary.
Long: One has to realize where which part runs. JSP on the server, Angular in the browser. I assume your senior colleague is concerned about displaying unauthorized data - but that is not the concern of Angular. Angular is basically just the View, and, perhaps, Controller. But it has to get the data from the server - which is usually done over some REST service. And it is the duty of that service to serve only data the user is allowed to view. So you can implement your View/Controller part in Angular, putting all the views (event the restricted ones) in, and then implement proper security into your server-side data service.
No, it's not necessary to use JSP in Angular 2.
It's correct that JSP allows you to protect the template itself from unauthorized access, but in our case it's not really a bad thing to happen from the security point of view, as access to the template without the data itself is not something dangerous; The data of course must be protected w/ your own security/authentication to prevent unwanted access to it.

Globally rewrite outbound links in a Thymeleaf / Spring MVC / Tomcat stack?

I need to globally rewrite all links to CSS / JS / Images, adding a prefix which will depend on deployment details and is the same across the entire application.
There are hundreds of links on dozen of source HTML templates so modifying at the source (as suggested here for a similar problem) is too error-prone and unsightly.
So I would like to do this programmatically, parsing the outbound HTML, and dynamically replacing each link before the HTML is returned out of the server.
Where to do it?
In Thymeleaf can I intercept the DOM and modify it before it is serialized to HTML?
In Spring MVC can I capture the view output (HTML), parse it, and re-serialize it?
Should I stay "close to the wire" and write a ServletFilter?
Or is it better to write a Tomcat Valve?
How about stepping out of the JVM altogether and have Apache mod_proxy added in front of tomcat just to parse and rewrite?
My initial hunch is that the best place to do it would be Thymeleaf, where there is more context available and it avoids an additional parse/serialize. Why generate wrong data in one layer to have it patched in another, when you could just generate the right data at the outset? Unfortunately the Thymeleaf maintainers don't agree, according to this closed Issue.
I also have this uneasy feeling that I might be reinventing the wheel. Isn't there a generic config option I can set somewhere in one of these layers?
So, to re-state the question objectively, what is the simplest solution - with the fewest lines of code written, and least number of files touched - to globally rewrite all CSS/JS/IMG links in a web application at run-time based on an application-specific algorithm?

Thymeleaf with Spring MVC 3

I have to decide on the view layer technology to use with Spring MVC 3 and I came across Thymeleaf.
Has anybody worked with Thymeleaf or has any experience with it. What will I gain and miss if I happen to choose it to work with Spring 3.
I wanted my front end designers to feel comfortable was why I was thinking if I could use thymeleaf with Spring 3 and still have all the functionalities we get with JSPs + Spring MVC 3.
Thymeleaf and Spring are a very nice match. The spring integration of Thymeleaf is done as it's supposed to be and it was nicely documented how to get started.
I use this combination since one year in several projects and I'm still happy with the choice I've made at the time.
Thymeleaf propagates the so called "Natural templating", which means that the templates can be viewed without the template engine, they are html files with additional tag attributes which browsers just ignore.
This means that a webdesigner can design the page, hand it over to the developer and get back again if changes to the layout have to be made.
While I liked this idea a lot in the beginning, I soon realized that, as developers, we tend to create components to be reused. This results often in templates having either not alot to display or also an extreme amount of elements.
Imagine some switch statement in a table cell component which renders either checkbox, textfield, select box, and so on. The table template including this cell fragment does not resolve it without an engine. Or imagine the header fragment with all the style and js declarations. Css will not be available in plain file mode.
But you can add additional html tags and remove them during processing. So natural templating is still possible. Just a lot to write :)
There are support extensions around solving this issues (using JS to pull in the fragments for example) but I havent used them as my applications are normally deployed within 30sec and I'm even able to change the templates on the fly without a redeploy.
After you also have a quite nice eco system around thymeleaf. The ability to extend Thymeleaf is done in a way I really enjoy! (Having written two smaller extensions myself).
I prefer the layout dialect instead of the include approach. That's a matter of taste i would say.
Choosing Thymeleaf over Plain JSP is clearly favorable from my point of view. Take a look at the webpage and decide for yourself ;)
I'm working with Spring 3 and Thymeleaf for a year and think it's a good choice. I came from Grails and Play and look for a good alternative and created FuWeSta. You can look at the rudimetar sample-app.

What is the need of JSF, when UI can be achieved with JavaScript libraries such as jQuery and AngularJS

I was reading about JSF that it's a UI framework and provides some UI components. But how is it better or different from number of components that are available from jQueryUI, AngularJS, React, Vue.js, Svelte, ExtJS, or even plain HTML, CSS and JavaScript.
Why should someone learn JSF?
JSF to plain JSP/Servlet/HTML/CSS/JS is like as jQuery to plain JS: do more with less code. To take PrimeFaces (jQuery + jQuery UI based) as an example, browse through its showcase to see complete code examples. BootsFaces (jQuery + Bootstrap UI based) has also a showcase with complete code examples. If you study those examples closely, then you'll see that you basically need a simple Javabean class as model and a XHTML file as view.
Note that you should not see JSF as replacement of alone HTML/CSS/JS, you should also take the server side part into account (specifically: JSP/Servlet). JSF removes the need of all the boilerplate of gathering HTTP request parameters, converting/validating them, updating the model values, executing the right Java method to do the business stuff and generating the HTML/CSS/JS boilerplate code. With JSF you basically end up with a XHTML page as view definition and a Javabean class as model definition. This greatly speeds up development.
As with every component based web MVC framework, you have in JSF less fine-grained control over the rendered HTML/CSS/JS. Adding custom JS code isn't that easy as you have to take the JSF view state in the server side into account as well (e.g. enabling a disabled button in JS side won't enable the button in JSF side, which is in turn a huge security advantage). If that is however a major showstopper, then rather look for an action based web MVC framework like Spring MVC. You'll only take into account that you have to write all that HTML/CSS/JS code (and prevention against XSS, CSRF and DOM-manipulation!) yourself. Also if you fall back from Facelets to JSP, you'll miss advanced templating capabilities as well.
On the other hand, if you have a big JSP/Servlet/HTML/CSS/JS/jQuery based website and you'd like to refactor the repeated JSP/Servlet/HTML/CSS/JS/jQuery boilerplate code into reusable components, then one of the solutions would be JSF. Custom templates, tagfiles and components can aid in this. In that perspective, JSF stands above JSP/Servlet/HTML/CSS/JS/jQuery (and that's also why it's pretty important to understand those basics before diving into JSF).
You can find a real world kickoff JSF based project here: Java EE Kickoff App. You'll see that it contains next to JSF as good HTML5, CSS3 and jQuery.
See also:
Difference between Request MVC and Component MVC
Difference between JSP, Servlet and JSF
What are the main disadvantages of JSF 2.0?
Is it possible to use JSF+Facelets with HTML 4/5?
When to use <ui:include>, tag files, composite components and/or custom components?
JSF was created to make it so that java shops didn't have to learn stuff like jQuery and build complex JS but instead focus on a purely Java stack. In a world where time is money and lots of places already focusing on Java development, one less language/piece in the stack makes training and maintaining faster and thus cheaper.
I'll add that JavaScript is easy to become a maintenance nightmare on large teams, especially if some of the developers on the project are not highly web savvy.
With Javascript and frameworks such as jQuery you have full flexibility and full control . With ext's etc you lose much control and must adapt to the framework. With JSF you totally lose control and must totally adapt to the framework. You're invoked in lifecycles etc. and finally you have no control when the call to the server can be made and where not. If you are to do something considered 'special', you're in very hard position. And in JSF world even such basic things as multicolumn table sort or fields where you can type only limited set of characters (such as number field) are considered 'special'.
However, the more flexibility you have, the more errors or bad practices you can made. High flexibility works only with highly intelligent programmers, others will turn the project into unmanagable nightmare.
But, with JSF and its limited flexibility, there's always only a few (or even only one) correct way to do something. You are very limited, you can't make shortcuts, you must write more XML etc. - but when adapting to standard, there's better control on the code the unexperienced or low-skilled programmers will produce. As a result, big corporations love JSF because it is 'safer' for them.
When I moved from GWT to JSF, I was shocked, how many things, that was natural to me, was considered highly untypical and how much simple things were so hard to achieve. What's more, even making the smallest changes, such as adding ':' sign after label, which in GWT/jQuery powered app would be changing one function generating label, required changing dozens of files with localized properties, which wasn't even considered by anyone except me strange...
The benefits of using JSF are not only in generating xhtml + css + js. Sometimes JSF imposes a restriction on the markup you can generate, like any component based framework. But JSF is not just for that, its lifecyle helps greately. After validating the input it can update the model and sync your server side beans without any effort. you just say "whatever the user types here, check if it's a number, if yes then store it in the property YY in object XX" and JSF will do all that.
So yes, you can still use JQuery, JS, etc. But JSF provides many benefits when it comes to writing server side code and saves you from a lot of boiler plate.
I strongly disagree that jsf adds anything. It only adds overhead. Doing ui stuff on the server is the most ridiculous thing ive ever heard. And javascript on large teams works great - its called reusing code.
Just wrap the jquery in some jsp tags, thats all you need and youre done, and dont endure the.shackles and scalability issues with.jsf and richfaces.
Having worked with JSF, Spring MVC, Struts, Grails, JQuery, and ExtJS my opinion is that Grails + ExtJS is one powerful combination.
I would pick Grails over JSF any day. I like the completeness of ExtJS as the client side framework and library, but it comes with a steeper learning curve than JQuery.
Here are the biggest differences between jQuery & JSF:
no MVC architecture
no state control (store date in session or conversation, auto-clean up, etc.)
no (default) validation library
no templating library
no advanced navigation/routing
client side
jQuery was never intended to be used as a full stack webframework. It was more intended for replacing low-level JS code so that writing JS becomes easier and more powerfull in less lines of code.
And it should thus mostly be used to add behaviour on HTML elements.
Having used ExtJS framework for a large web application, I know how easy it is to use. The ExtJS (Schena) is best suited for (Oracle 11g) database interactions in MVC architecture. The View was for the visual / user interactions. The controller specified the 'processing' and the triggers that needed to be used form the PLSQL packages (the API for the CRUD, SQL select queries etc.). The Model and the store files were used to 'map' the data items to the Viewer / inputs.
ExtJS is not suitable for non database intensive web interfaces - where Angular JS may be a better fit.

Best practice to manage the path breadcrumbs in Spring without Web flow

I am engaged in a project where I need to show path bread crumbs to the user like
Home (This is linked to home page) >> (page name)
and like
Home >> contacts
and in contacts like
Contacts >> create
Contacts >> edit
etc.
Is there a best practice how to do this in spring without he usage of spring web flow? I am not using spring web flow and simply using the spring MVC.
I'm not sure why you'd have to do this in Spring if you're not using Spring MVC.
Depending on the site's structure and the URL structure, you might want to parse the URL into something readable.
Another option is to have some sort of push/pop mechanism but since browsers have a back button which does not signal the server this is often a recipe for disaster.
I'm not sure there is any universal solution for breadcrumbs. Here are a few variants:
use the URL structure. With spring mvc this is actually a very good option, since it (since 2.5) replies a lot on nice, structured URLs
have each page (view) identify its own path in the breadcrumb (via a request parameter). It's not
place current steps in session. This would break if multiple tabs/windows are used, so you will have to use a windowId.. and essentially roll-out a "crippled" webflow.
This sort of breadcrumbs is sometimes called homeward path navigation.
If you can capture your site layout in XML then an XSL could be used to generate the breadcrumbs. The same XML site layout document could also be used to generate a side navigation menu.
See also: Separating breadcrumb (homeward path) navigation from content using XML/XSL.

Resources