I understanding how the Model and Controller sections of the MVC pattern and [Spring MVC][1] work.
However, I am not sure on the View.
E.g.: If I want to send data back when my Rest end point is hit e.g. users/{user}, if I send back a JSP/ThymeLeaf page or a, how does it work?
Is the view response sent by the controller?
How is JSP different from sending a JSON response?
The view is the rendered string output. So in general you could say that there is no difference between the JSP output and JSON since both are just string responses which get interpreted by the client. But normally JSP is used for output html sites(Java Server Pages, Html rendered/generated by the server) and JSON to deliver pure data in an object structure.
The controller(in MVC general) is the middleware between model and view, so when the view gets an input the controller digest the events and manipulate the data and also when the model changes the controller triggers the gui to update.
Since the html/web world is a bit different(request->response) the Spring-MVC controller is getting the user input and triggers the rendering of the output string. So you could say the controller is delivering.
The controller is the one who changes things while the data and view are static without it.
I am going to write about tiles and spring mvc. Mvc controller will react on your url like if you send request by localhost:8080/ myapp/classroom/hellostudent.html then spring controller will take /hellostudent.html and remove .html from url and match your string in tiles.xml file.
And about json so Spring mvc comes up with json api you have to use#Responsebody to send json object to client side.
Related
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.
last time I found a example of REST app, which one REST controller returns HTML page(index.html). As a front-end was used Vue.JS and other communication was realized by REST controller returning normal JSON.
And now I stil thing how this solution looks in context of good practice of building REST API.
I add link to this controller. Home Controller
Ok. I read something and now I know that is a standard mechanism to serving view in Spring.
And now I see that HomeController is not Rest because have annotations #Controller not #RestController.
Thanks for help.
Of course NOT , Rest is use to send state information and not the UI
for UI we have other conrtoller to be used.
REST must be used when we need to send or recieve state information in form of json preferably.
Its a good programming paradigm to return JSON/XML as response to a rest call. This is separation of concern. Once the response is obtained from the Rest call we should process that to render an html object. Also this will ensure that if your rendering engine changes you will not have to change the code for the rest call. eg. You can change your view from struts to angular then your rest api code remains unchanged.
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
In many MVC frameworks when a request is made it goes to a controller/action class (based on the URL pattern among other things). If the developer wants to do something with the request object or other processes then it does that with in the execute or doGet or doPost etc methods & then forwards it to the dispatcher. The response type could be a JSON, JSP, XML etc.
I have a brightspot cms webapp in which I want to do something similar. It is based on the open source project dari framework.
In case of a object of type Content if I want to setup some pre-processing of variables to be used in the JSP page based on the request object, how can I do it? I am unable to find the point of intervention between the request going to conten type object AND request being forwarded to the backing JSP page.
I know I can just add scriptlets to the JSP page, but I had rather not do it for variety of reasons.
I was able to resolve this by adding a Filter for the URL pattern I was interested in. More info here.
I am using Starbox in my Spring page. I want to submit the user rating so I can store it in the database and not have to refresh the page for the user. How can I have a Spring controller that accepts this value and doesn't have to return a new view. I don't necessarily need to return any updated html - if the user clicks the Starbox, that is all that needs to happen.
Similarly, if I have a form with a submit button and want to save the form values on submit but not necessarily send the user to a new page, how can I have a controller do that? I haven't found a great Spring AJAX tutorial - any suggestions would be great.
If you use annotations, perhaps the more elegant way to return no view is to declare a void-returning controller method with #ResponseStatus(HttpStatus.OK) or #ResponseStatus(HttpStatus.NO_CONTENT) annotations.
If you use Controller class, you can simply return null from handleRequest.
To post a from to the controller via AJAX call you can use the appropriate features of your client-side Javascript library (if you have one), for example, post() and serialize() in jQuery.
The AJAX logic on the browser can simply ignore any data the server sends back, it shouldn't matter what it responds with.
But if you really want to make sure no response body gets sent back, then there are things you can do. If using annotated controllers, you can give Spring a hint that you don't want it to generate a response by adding the HttpServletResponse parameter to your #RequestMapping method. You don't have to use the response, but declaring it as a parameter tells Spring "I'm handling the response myself", and nothing will be sent back.
edit: OK, so you're using old Spring 2.0-style controllers. If you read the javadoc on the Controller interface, you'll see it says
#return a ModelAndView to render, or
null if handled directly
So if you don't want to render a view, then just return null from your controller, and no response body will be generated.