Can I use Thymeleaf templates + bindings without sticky sessions? - java

I currently use a HA-Setup without sticky sessions. Is it generally possible to use thymeleaf templates with bound objects in non-sticky-sessions?
I am not familiar with the inner workings of thymeleaf -- neither do I have an idea how to test this...

Thymeleaf would work with the data which you put in your Spring model object. So the scope of that data is that of the request. And moreover, Thymeleaf templates are processed at the server. So the flow is:
User requests for a URL
Spring framework receives it at the server and routes it to the controller
the controller executes the method mapped. This might involve populating the Model or ModelMap object and returns either the view template name or the Model object
the view resolver retrieves the view template name and uses the corresponding view template engine to process the HTML in the view template name and then return the HTML to the response
this response is then sent to the user
So you see there is no sessions involved. But when you use Spring Security, it would use session to record the authenticated user information.
And if the user explicitly uses session in their code then it would be a problem.

Related

How does Spring MVC relate to Service, Controller and Data Access layers in a web application?

I understand the MVC Pattern and also how Spring MVC implements it.
However, how do the Rest controller, Data Access Layer and Service Layer fit into this pattern?
Is it:
Model = Database (e.g. Oracle/MySQL) and Repositories classes
Controller = Service (buisness logic) and Rest Controller classes
View = JSP / FreeMarker?
Model - is not a Database, is not a Repositories, is not an Entity. Model is abstraction, that contains all data, that is needed to be displayed. And every View has it's own model. You can consider Model as container for data between Controller and View.
In Spring model is ModelMap parameter of method of controller.
Controller - prepares Model, to pass it to View. If model is quite simple, Controller can do it by itself.
But most of models contains a lot of data. This can be multiple Entities from database, data from configuration etc. In this case Controller use lower level tier: Service, Repository. They all help the Сontroller to build model for View.
upd: It is a purpose of Controller to connect View and Model. Controller creates and fills the Model, then chooses View and pass this created Model to the View. That's how Model and View get connection.
In Spring controllers are Controller and RestController.
View - is final point where data from Model (passed by Controller) will be displayed to user. But another role of View is get commands from user, and pass it to Controller.
In Spring this may be view of any view-engine: JSP,Freemaker,Thymeleaf.
Note: usually, Controller does not use Repository directly. Traditionally, Controller works with Service, and Service uses Repository to get data from database. So relations are following: View<-Controller->Service->Repository
A controller accepts HTTP requests and often loads or save some data (from a service or DAO), and return an HTTP response. This response could be a redirect, or a view, or some JSON or a binary file.
A controller can use services, but should avoid having much logic of its own. It can also directly use data access objects, if there's no service logic required.
The model is whatever info a view needs to do its job. It is not necessarily related to a database. For example, you could have a model in a registration form, with email address and confirmEmailAddress fields. You don't store a confirmEmailAddress field in your db, so they there is not a 1-to-1 relationship between db tables and models. Also, your model could be data for a simple calculation that is not persisted.
So let me make sure I understand ...
The user interacts with an interface to view or submit data. The user calls on the interface to view some data. That call (an HTTP Request) goes to the Dispatcher Servlet (DS).
The DS then consults the handler mapping to help it decide which Controller to use.
Once chosen, the DS passes the request onto the Controller which calls the appropriate service methods, based on GET or POST. The Service method may need to interact with a Repository, which can interact with non-volatile storage (database, XML file, text file, etc), to construct a model based on defined business logic. Once complete, the model data is returned to the DS.
The DS then consults the View Resolver on which view should be used. The View Resolver picks a defined view for the request.
The DS then forwards the request onto the View, which is presented to the user.

Understanding the flow of spring framework & MVC

I am having some trouble understanding this. Can someone help me better understand this?
MVC
Model --> Java- Spring Framework
View ---> templating language(JSP velocity) & Javascript
DB --> SQL
Q-1)
Now, When I open a particular page, I can't visualize the flow. I've read about DAO, controller , service etc and I understand them individually but I am really confused when I club all together what's the order of execution? Whats the flow exactly ? Is it that first the view is loaded then it sends JS request to fetch the necessary data from backend and then the controller and service are invoked and the DAO queries the db? Then how does the API come into picture? DAO deals with the API?
Q-2)
Why do we need xyz.properties? I have removed a module from my page. If I remove a particular js file(related to that module) from the scripts.properties, then ideally that js should not get executed at all right? Then still why would I see the api call to fetch the data related to that module? I don't see the module but I sure see the api call. Why is that?
DB doesn't enter in MVC model. And you're forgetting a principal element in your analysis: the Controller. The flow goes like this:
Client performs a request to an URL
The application server gets the URL and passes the handling to the web application.
The web application using Spring MVC will handle the URL processing to the Controller: DispatchServlet, which is a Servlet.
The DispatchServlet will try handle the URL. If there's an URL mapping, then it will pass it to the class (mapped in the spring.xml config or decorated with #Controller annotation).
This controller (which in fact is part of the model) will handle the request. It will call services, daos, etc (Model) and return the necessary data to complete the response to the DispatchServlet.
The DispatchServlet will finish the request handling and, in the end, will generate the results e.g. a text/json response, or it will forward to a JSP file (View).
For question two, I never have used such scripts.properties file, so I don't know what you're talking about. Usage of a properties file is to store application properties that should not change until an application redeploy. They have 3 main advantages:
They can be easily manipulated by human users. It's no rocket science to add, edit or remove values.
Since it is a plain text, it's easier to version using a version control system like SVN, Git or another of your preference.
It provides a faster access since it is usually in the same disk as the application, so there's no much time penalty when accessing to its contents compared to a database configuration. But since it is in disk, it still has a disadvantage against RAM access only.
In simple layman's term, MVC explained in pictorial form
(inputing data) (data related part) (display rendering)
-request mapping -classes -JSP (Script,CSS,HTML)
-request param -interface -velocity
Controller ------------->Model--------------->View
||
\/
(data processing logic) (access to Databse)
-optimization -JDBC
-business logic -SQL
Service--------------------->DAO

Spring Security ACL tags for REST Services

I am new to Posting question in Stack Overflow.
I am currently implementing Spring Security ACL for my REST Services.
What i want is a way to hide and show certain UI tags based on ACL entry.
Since i am using REST Services - All my calls from UI are ajax based and returns a JSON.
Now with Spring Security ACL tags its required to send a DomainObject to the tag so that it can resolve the authorization.
Since i get a JSON from backend i cant create a DomainObject.
Also the time i return a JSON to frontened the JSP will be delivered in first place so the security tag will not be effected.
Best Regards
Sriram
I solved this by returning a json which will have crud variables marked true or false depending on the users access control and in the ui I show/hide using this data.

Is the Java HttpSession ID visible to FreeMarker templates?

From a FreeMarker template in a Java EE web application, I need to access the sessionID (i.e. HttpSession.getId()). Long story short, it's being passed to an outside analytics provider so they can build reports about what users do during their browsing session.
Obviously, I just add the session ID to the model object which gets passed to FreeMarker. However, this application is a bit of a mess... one FreeMarker template may be used by multiple controllers passing various model objects. For maintainability, it would be far easier if I could just access the session ID from the FreeMaker template without having to change all those model classes.
I've found FreeMarker documentation referencing "application", "session", and "request" scope. However, this format does not return a value:
${Session.id}
I suspect "scope attributes" doesn't include all getter methods on the HttpSession object (such as getId())... but rather just those values which can be fetched from HttpSession.getAttribute().
Is there an easy way to access the Java EE session ID from a FreeMarker template, without having to explicitly pass it through the model object?
You can put it in the model before rendering the template.
Normally you can put the request object in the model in some base method, which is invoked when rendering all templates. That way all templates will have the request, which you need anyway. Then you access the session via the request object. That's what we've done, and it works fine.

Best way to show the user full name in a JSP header file with a spring/struts framework?

I have a JSP struts application that uses Spring to integrate with the services/dao/database. Basically, struts uses spring to get the data from the DB, it builds the form and forward them to the JSP files.
I have a header file that is injected in each JSP file using Tiles. I would like to show "Welcome John Doe" on each page inside the header. Where "John Doe" is the name of the currently logged user.
What would be the best approach to do that? The solution that I can think of is:
Use a Spring Filter the catch the http request. Load the user from the database using a cookie that contains the user id(*) and put the name in a session bean named "CurrentUser"
In "header.jsp", get the spring application context. Using it, load the bean "CurrentUser" and get the name. Put the name in the html.
I think I could get this to work. But I'm not certain this is the best way to do it. Any thought on my approach?
(*) Of course, the cookie will be encrypted
Although it may be an extremely large hammer for your fairly simple use-case, we have gotten a really neat spring-jsp integration (jsp 2.1 required!) by using ELResolver. By following this tutorial you can basically inject any spring managed bean into your el-context and allow it to be accessed using jsp-el like this:
${spring.mybean.myproperty}
You can choose to inject pre-defined beans into your el-context or simply pass "mybean" to getBean and allow almost anything spring-managed to be accessible from jsp. mybean could easily be a session-scoped spring bean.
I'm not totally sure how this would align with tiles, though.
Are you not already storing some sort of User object in Session?
If so, I would just add a "getFullName()" method to this domain object and have the DAO populate it when it returns it. Ideally you should populate the User object when the user logs in, store it in session, and not need to load all of the user's details again from the database on each and every page request.
(Are you not using Spring Security? If so, they provide a pretty simple way to store a UserDetails-like object in Session, and easy access to it.)
I'd vote against both of your approaches because
This means (at least) an extra database call per page request
This wouldn't work if other users shared the same bean in the same context. Also, you really shouldn't have JSP files (which are your presentation layer) interacting with data services directly.

Categories

Resources