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.
Related
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.
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.
I have to 4 objects, Group, sections and Questions and their options. Every Group has different Sections and Sections have Multiple Questions and Questions have options. Now I have to design form input system so that every group and sections can be covered up step by step. I’m doing all this in spring mvc.
Can you tell me a way, how can I solve this problem?
You can surely do that in Spring MVC thanks to easy list binding.
Spring MVC allows a big lot of freedom, so basically if you only use this framework, you will have to come up with a solution from scratch.
Here is a use case and a solution. It is a bit tough to implement, as it is from scratch. Feel free to adapt it to your specific needs, add whatever fancy UI framework you want, but you should get a general idea. You can skip to part III for a quick answer.
Let's say you want to create/edit a group in one single page :
you want to edit/add sections to the group
you want to edit/add questions to any section
you want to edit/add options to any question
I. Page design :
You have a JSP Group page with one big single form (again this is just an example)
There will be buttons to add nested stuff. When clicked, some javascript will show a blank form allowing with the information of the stuff. This blank form will itself have buttons to add nested nested stuff to it, and so on (until the stuff is an option).
The design is the same for existing stuff that you want to display/edit, except that the forms won't be blank
You are able to tell whether you are creating or editing the current group (context of the page or javascript/html tricks).
There may be a list of existing sections you could "drag & drop" inside a group thanks to some javascript/jQuery
II. Code design :
You have a GroupController corresponding to the JSP
The Group object has a List<Section> sections attribute, the Section object has a List<Questions> questions attribute, etc.
You have methods createGroup and editGroup
When submitting your JSP form and calling createGroup or editGroup, you are able to know if the submitted elements of the group already exist, so you can decide to add or edit/update them in the DB. All this logic could be done in another class, like a Spring service.
You always provide a possible list of existing sections (by adding this list to the model in both methods, or better yet, by doing a single method annotated with #ModelAttribute). This list could be computed in another class (a Service/DAO/both which taps the DB in the end).
III. The magic : binding the JSP form with the Java controller :
In the page you'll have a <form:form commandName="group">, and in the controller methods parameters you'll have a #ModelAttribute("group") Group group.
Now, to submit the name of the very first option, you would have this in the JSP :
<form:input path="sections[0].questions[0].options[0].name" />
(or the equivalent in html generated by some javascript).
I am working within a RESTful Web Framework that is natively script (JSP) based. The Framework has a routing mechanism that automatically sets a number Request attributes, which are then available in the JSPs (One of the attributes being a "Model" of the requested resource; which is basically just a HashMap).
The issue is 90% of the time, some amount of logic is required to be added to the JSP, be it more complex domain logic, retrieving other resource data (other Models), or scrubbing data for output.
I am looking at various establish web application design patterns for extracting domain logic out of the JSP, and keeping the JSP as logic-less as possible.
A few things to note:
Within the system im working in, the Model (the data pull from the database) is provided but the Framework (the previously mentioned HashMap); I could create my own Model wrappers around this data, but it's probably unnecessary.
JSP/Scripts are the end points for Requests - If I use a pattern that uses a Presenter/Controller-type object that returns a View bean (ViewModel?) which contains all the data the view will use, I will need to have a line in the JSP which calls the Presenter/Controller and instantiates the View bean.
Currently I've created a Presenter POJO for each Module (script), which has access to the Model (again, the Framework sets this as a Request attr), and simply instantiate it at the top of the JSP, and use it more or less like a bean.
If I understand it, correctly, I believe i've implemented the Presentation Model design pattern. [1]
Ex.
JSP looks like:
<% DemoPresenter demo = new DemoPresenter(request) %>
<%= demo.getTitle() %>
- or add it to pageContext to use w JSTL/EL -
<c:set var="demo" value="new DemoPresenter(request)"/>
${demo.title}
And the "Presenter/Controller" looks like:
public class DemoPresenter extends BasePresenter {
private String title;
public DemoPresenter(HttpServletRequest request) {
FrameworkModel model = request.getAttribute("frameworkProvidedResourceModel");
this.title = model.get("title").toUpperCase() + "!!!";
}
public getTitle() { return this.title; }
}
Any thoughts on using the Presenter obj directly in the JSP/Script, vs having it return a "logic-less" ViewModel bean that the Presenter populates w/ data? The advantage to this is I could have a single Presenter managed various "Views" of the same resource (such as Show-view, Edit-view, Summary-view, etc.) - Below is an example of how i could get various view models.
/blog/posts/1/show -> executes JSP which gets its ViewModel like so:
<% DemoDefaultViewModel default = new DemoPresenter(request).getViewModel(DemoDefaultViewModel.class); %>
/blog/posts/1/edit ->executes a JSP which gets its ViewModel like so:
<% DemoEditViewModel edit = new DemoPresenter(request).getViewModel(DemoEditViewModel.class); %>
I would like to keep a simple solution without too many extraneous pieces. I also can't get too fancy as I am working within a strict predefined framework - I just want to figure out a good way to move all my domain logic out of the JSP into more reusable, testable Java classes.
[1] http://martinfowler.com/eaaDev/PresentationModel.html
Check out struts.
I must admit to only having used the older version but the 'front controller' servlet idea seems to be what you're after . It is a special servlet to run common code and route requests.
It also has actions which can be tested outside of the web container.
The day I moved from pure JSP to struts was one of the best days of my web development life! The project started to feel organised and much easier to manage.
There are lots of MVC frameworks. For example Struts uses a front controller servlet to dispatch requests to a class (controller) depending on the resource used. The class processes the request and sends the result to the view (typically a jsp). The model is any class that represents your data. FYI, a Map is not a framework. Representing your data as a MAP only, will work, but is ugly and hard to maintain.
Without knowing your strict framework, generally accepted good practice would be to keep your business logic centralised and independent of any framework. Use your framework for plumbing only. Get your controller to mediate between your presentation and business logic, again this is just plumbing. Put your display data in the right scope (almost always the request scope) so you dont have to have scriptlets as in your example.
Over the past year I have heard alot about Velocity and NVelocity. Reading their documentation and doing searches on the net hasn't given me the answers I was looking for.
In what situation would I use this library in my development? What problem does it solve that didn't already have a solution?
Since the dawn of web apps, people started to think about separation of concerns in many applications, including web applications. The challenge is to separate what is view code from what is business code, or logic code. When jsps first arrived, many people where coding lots of logic in jsps directly (stuff like db access and other), breaking the basic principle of separation of concerns (jsps should be responsible for the presentation, not for the logic).
Velocity, Freemarker and others are templating engines that allows the separation of UI logic and business logic, thus facilitating changes in the presentation while minimizing the changes on the business side. These template engines have facilities for doing common UI tasks such as showing a block of html if some condition holds true, or iterating over a list while maintaining logic code outside of the view. This is fundamental for maintaining a complex application in the long run.
I think it's important to point out that compared to JSP/ASP.NET as a templating mechanisim, Velocity/NVelocity really 'ENFORCE' the seperation of concern.
With <% .. %> of JSP/ASP.NET, any Java/.NET code is allowed. Which is why sometimes you do see business logic code in these files.
With Velocity/NVelocity you can't embed long series of code. Instead you are really forced to pass in computed values, which Velocity/NVelocity picks up and displays them according to the way the template is designed.
Another point would be that they can work outside of a Web Container environment (at least Velocity can AFAIK). Imagine that you had designed a report template with JSP/ASP.NET. It works fine from the web. And then suddenly there is a change request to have it be done from a Desktop application. Rather than embed a Web Container in it, you could initialize Velocity/NVelocity, compute the values, then render the template.
It's a template engine. If you have a lot of static text with variable content mixed in, templates are a great way to reduce the amount of work you have to do.
It's a whole lot better than String.Format or loads of concatenation because it's not as repetitive or error prone, and far more maintainable since you can figure out exactly what your template does just by looking at it.
We use templating to generate configuration files for production, UAT, system test, contingency systems etc.
We have a master Spring configuration file into which we inject a property file. We have a master property file that is parsed by Velocity and this allows us to keep all system settings in one file.
As a bonus, for the ones interested, I recommend reading the following:
http://www.artima.com/lejava/articles/stringtemplate.html
http://www.cs.usfca.edu/~parrt/papers/ST.pdf
These are links about StringTemplate, a templating engine by Terence Parr who wrote antlr, a parser that's been used everywhere (ex: hibernate uses antlr).
1 - Velocity engine actually merges the real time data with the xyz.vm file which holds the static information 2 - The vm file uses Velocity Template Language(VTL)
(It can iterate over the java iterable java objects placed on the context , can call the methods accessible by the objects placed on the context) Situations to use Velocity - Brings the power of java to html not only to html 1-When you have to generate report mails often with varying data and constant style.(foreach support)
2-When you want to merge a real time data with dummy place-Holder in deeply nested contents
3-When you want to decide style information based on the value of the data (if else support)and many more
Refer - http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html