Convert String to View in Spring Controller - java

I have a framework which generating a jsp in a string variable, depends on parameters in json file.
How do I convert this string to jsp, return it from controller and render it?
In general. I have a table on the upper part of page. And after I click on a row, on the bottom part of the page I need to display the part of view generated in the controller "on the fly".

I believe you have to use some template engine for such tasks.
You see, jsp pages are not just a templates for population values into placeholders, in some moment they will be compiled to servlet-like java classes(could be on the first hit or precompiled when application starts or even compiled with project itself using build tool plugin) and from that moment on this compiled classes are responsible for all interaction, not a jsp engine.
Please try to explain why do you need such thing on a simple example, I'm sure it has to be another way for achieving this.

Related

Better programming JSP one page vs multiple pages

JSP Application programming
Which is better
Coding in minimal number of JSP pages with multiple if conditions
For example inserting sales,costs,expenses,customers,products etc with an if statement with variables.
if(variableValue=='Sales'
{
Sales insert code
}
else if(variableValue='Costs'
{
costs insert code
}
Creating multiple pages.
salesinsert.jsp
costinsert.jsp
etc
which is better and good programming. what are the advantages and disadvantages in short term and long term
Performance
Maintanence
Migration to a different technology stack (such as java to python)
I know it is not good to write application logic in JSP. But unfortunately i cannot change it now. Both the ways i am coding logic in jsp page itself
This code isn't compatible with MVC pattern you should follow:
The model is the central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application.
A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
The third part or section, the controller, accepts input and converts it to commands for the model or view.
JSP is view component and should decide which data to represent, but controller,
which can be ActionServlet in struts
ActionServlet acts like FrontController pattern.
It all depends on the size of the JSP pages:
Put it in the same page if the resulting JSP file has a reasonable size (less than 300 lines)
Create seperate JSP files / tag files if the combined page would be too big and if you can split it without adding a lot of complexity for passing data to the sub pages.
if statements in JSP files aren't necessarily application logic. Often you have the case that depending on some value part of the page is shown or not. I'd rather call this view logic. The same goes for for loops if you have a repeating view element.
You certainly don't want to have SQL, data manipulation, data validation etc. in JSP.

Dynamic Jsp pages - Taking too long

I have a project which gives the user interface to create the Dynamic forms on the fly.
User can select different fields like textbox, textarea, date etc and create a model for the same.
Once the user chooses the component and creates a form, then we need to show that form at a specifies place. The form components are rendered through common jsp page which accepts pojo object and then distributes that object to our own custom created tags for input,checkbox,radio,date etc.
Issue is it takes very 10-15 seconds to render the form.
Is there a way i can create templates or say html code of created forms and store them in DB and render through them. (Provided i am able to still bind data using Spring MVC, show dropdown values, selected or saved data in the fields.)
You may want to take a look at Metawidget. It renders different forms inside a common JSP as you describe, and does not have the 10-15 second issue you are seeing.
Metawidget is Open Source, so you can examine how it works, or even use it 'as is' (it is designed to be embedded inside projects such as yours). There's a good example tutorial here: http://metawidget.org/doc/reference/en/html/ch01s03.html#section-introduction-part2-web
Better way is to create you own custom tags and remove repeated code.
This will decrease the compilation time and further decreases the loading time of the page.

MVC Architecture issue

I have been reading a lot on MVC but really don't know if i am clear on the concepts of MVC or not
recently developed an application what i did is
1)on jsp load called a function
2)using AJAX called a servlet and servlet is there performing all the logic
3)servlet called a java bean and a java class to perform some logic and return result
4)based on the result returned form the class i am displaying an image say if result is 1 then image A ,if 0 then Image b
5)on servlets POST method i am using out.println()-->to write the complete output
6)the function on jsp after returning the call will set the innetHTML of required div by the output generated by the servlet
now say the output servlet is producing is the table
instance name|instance state
now if i want at some time to change the display for this table to say
instance state|instance name
to do the above mentioned change i have to recompile my servlet and redeploy the war
is it really a MVC?
and someone suggested me to use JSON store object of a bean containing data as JSON and then return the JSON object to the jsp
and at jsp using this object contruct the table!
any pointers on this will be of great help!!
Whether you have to redeploy usually depends on your development environment. If your using an IDE that builds automatically as you make changes, and the server is run from the IDE you are using, you may not need to rebuild the war. You can always try to view the source code to see if you need to redeploy. Back end code usually has to be redeployed.
Based on the ajax reponse obtained.
You can hide or show the images that you tend to.
How about getting the image link instead of out.print printing the bytes[] if i am not wrong.
When you want to redirect to another page, how about redirecting it from the servlet itself using response redirect.
Lets have a quick look at what is MVC?
MVC(Mode-view-controller ) as the name suggests is software architecture pattern , which encourages application to have its Model Classes (i.e domain models / DTOs) views (i.e can be JSP, JSON etc) and controller (i.e Servlet) to be as modularized as possible so that it encourages re-usability, loose-coupling between the different layers and Seperation of Concerns.
So the key idea behind this to encourage Seperation of Concerns .
Say i want to change the view from JSP to freemarker view , if MVC is tighly followed , i should be able to accomplish the change with minimum to no impact to Controller layer (i.e Servlets)
Well you see this can only be achieved if had clear layer separation in my webapp.
If i had just scattered all the functions without regard to MVC like having views generated from the Servlet, or making service level calls like accessing the DB directly from the Controller etc is bad because any change in the view or the Database layer will cause massive changes at the Servlet .
So to answer your question , your servlet should not directly produce the HTML output.
Store all the objects that would want to generate view in Request Attribute and access it in JSP
And to recompile Sevlet doesnt mean you dont follow MVC , just that by following MVC your changes are minimal and are grouped at a single place.
For now drop JSON concept , make it plain and simple
Go through this tutorial , which fairly explain you how to achieve a neat MVC
Jsp MVC tutorial.
Once you grasp , you can always add more complex things like JSON, AJAX , Asynchronous Request etc

Can tiles have action classes?

In Stuts2 I am using Tiles plugin to create a layout for the website (menu, footer, header etc.) that is consistent on every page.
Now each tile is just a static HTML content.
Is it possible to make a Tile more dynamic by eg. calling a Footer action class every time the footer is to be rendered? For example: to fetch footer content from database.
If I was to do that inside every page's action class in my application this would make for a very unusable code...
So maybe it is possible from Tile perspective?
There is only one way to do what you ask with a tiles version less than 2.2.2 and that is with a "preparer".
This however is not an integration with struts2 but would mean the preparer it self will access the service layer to get the required content for the view and all that content would need to be set though tiles attributes.
With tiles versions 2.2.2 and higher:
You can use OGNL expressions within tiles attributes, this can allow access to some struts2 interaction as well as static method access. With static method access you can call a method to return a string how ever you want. Creating such a string would be on par with writing a scriptlet.
To upgrade you need to either manually override some jars to get tiles 2.2.2, or to get version three you will need to implement your own result type: How to integrate Struts 2 with Tiles 3.
I don't actually recommend either of the above methods at this time, tiles 3 is recommended but not as an excuse to do something as bad as writing a scriptlet. It would probably be better to use the s:action tag in a tile, as mentioned by David or use an Ajax method as mentioned by Jaiwo99. The reason being that both these methods keep with struts2 while the ones I presented would be unusual and be harder to maintain. Personally I would lean towards the ajax methods.
Struts2 along with the struts2-json-plugin makes creating json services very simple. Tiles is a nice system for reducing boiler plate. If ajax is used heavily the two really can compliment each other. You can make a lot of reusable ajax components, just be sure to not hard code the urls of actions. Always use the s:url tag and assign that to JS variables.
Try following code:
$('#footer').load('your/action/with/namespace');
i'm assuming your footer is with id footer, everytime you open a page, your footer action class will be called and the data can be fetched dynamically.

Easy way for AXAX refresh JSP or Spring MVC page?

This seems a bit like a rudimentary question for java web development but...
How would I go about refreshing data in a JSP page? I mean, I get the basics (use jQuery for AJAX, Spring MVC for the "Controller" & get data requests). What has me stumbling is what is the easiest way to render the updated data to the page (given, the JSP is all server side...which is not conducive to client side updates)?
I've considered:
Using Mozilla Rhino + Velocity in the javascript - this seems a bit cumbersome
Using the "new" Spring AJAX MVC improvements - the examples for this seem a bit confusing to me.
Returning a semi-rendered String in the Spring Controller get method via the business logic+velocity - I'm not sure if it is "correct" to do it this way, it feels a bit dirty to build up the view object in the Controller class.
Is there an easy way to do what I am asking? I basically have an html table that needs to be repopulated on an interval. Surely I'm missing something here.
TIA
My suggestion would be to specify a div for the content you want to refresh.
At the specified intervals, reload the div with fresh content from the server. I would recommend generating the html at the server and just jQuery('').load() the url. But you could also just get json data from the server and create your markup on the fly, but this is problematic with large records.
Hope that helps.
About generating JSON or a partial view in the controller, both options are valid. I'd go with JSON if the HTML to generate/modify isn't too complex, and I'd choose returning a HTML fragment for something like refreshing a big table, or load a new complex panel, etc. To generate JSON I usually go with a Spring MVC controller method with a bean return type annotated with #ResponseBody.

Categories