I am quite new to Java/Servlets/Tomcat etc. but have a fairly good understanding of web apps from my days as a CGI/PHP developer.
I have a JSP index.jsp that presents a table from a database.
I have a Results.class that is a normal Java class (not a servlet) that queries a database and returns a string from a method: public static String displayAllResults()
The String being returned is an html table.
So in my index.jsp there is a line that says something like:
String table = Result.displayAllResults();
And then the table is displayed as I'd hoped - All good!
My question is this: is there any advantage/disadvantage to using normal Java classes instead of Java servlets in this manner or should I port all of my classes to servlets for added functionality??
You should really be using MVC frameworks like Spring MVC or struts2. You should always have clear abstractions:
Dao Layer
Service Layer
Business Layer
Model Objects
DTO's
Helpers/Utils
Whenever possible use EL languages like JSTL/OGNL on JSP pages. Never ever use scriptlets. If you use any of the above MVC frameworks, you'd probably never need to use Servlets directly!
Displaying grids with data from database use something like DisplayTag or Jqgrid (with Ajax calls)
It's generally considered poor practice to be invoking Java from a scriptlet in a JSP page. JSP is intended to do HTML formatting, with some extra intelligence around using the Locale and things like that. A better PHP, if you will. Database processing should be handled by a servlet.
I think understanding the purpose of Servlet, JSP, and normal classes will answer your question.
As per my understanding, JSP is used for View purpose, that is, rendering UI to the screen is role of jsp.
whereas, Servlets are used as a controller, whose role is to act as a bridge between your Views and Models.
Normal java classes can act as a Model, here you can perform some core business logic.
Related
So i have a sort of design question:
I have a jsp, and a controller that fetched the data for that jsp. Some of that data come from service classes.
I know that mvc pattern tells me to use the controller to call the service class and pass that info to my view (jsp).
Why can't I call the service class from my jsp directly?
You can, and that's what developers sometimes do. But you shouldn't.
MVC is about interchangeability and separation of concerns. If you call your service from JSP, you create a tight coupling, to parameters and return types, for example.
Moreover, usually, systems are not developed singlehandedly. Let's say you have getAllAdmins() method in your service, which you use for internal logic. Do you really want another developer to use it directly in JSP, and by mistake display all your admins? Probably not.
You can. You can even put everything in one class and maybe it will work. But why? Doing like that ruin all flexibility.
You think only about little example, but you should think what advantages it gives to big applications.
Read this.
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
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.
i have a question that is more design and architecture related. I am coming from a classical MVC based background and have to get my hands dirty on JSF2. I read the IBM articles on JSF2 (http://www.ibm.com/developerworks/library/j-jsf1/) and think i understand the overall concept.
I started to get in touch with JSF2 trough ROO. I have the feeling that ROO (maybe this is true for any JSF2-Type App, or maybe not) is making very strange/unclear use of beans. It is in general really not clear to me what the actual role of a Bean is! For example, if i have a view with a form that is for editing a single user-entry, i would initialize the user in a, lets call it UserBean (maybe store in in a member variable) and access this variable trough getters. If i now want to overview all users, i would again render the view in in the UserBean hold a collection of users and again access this collection trough getters. The previous description is actually the way i would do things with jsf. This means i would user the UserBean more as a statefull-service as a controller.
In a typical controller situation i would create for every type of action (list user, edit user, view user, etc) a separate controller, with specific initialized data and this way i would separated the context of the logic by controllers.
I often make use of context specific services, e.g. if i handle user's often an spread over the application, i create a user-service that handles user specific logic that is maybe to complex to be put into the itself. If i now for example look into roo generated Beans, i would find methods that programatically render forms, input fields, labels, that again store list's of users, boolean fields that indicate if data had already been loaded, single user members and a lot of methods that more look like to be put into a UserService (or whatever). I am wondering if this is the way JSF2 is intended to be used, in words: pushing everything that is related to one context into on bean, not making use of service and writing "super-controller-beans" that handle everything.
I don't really know if you get the question right, but what would maybe help me is, a hint to
a very exemplary and commendable example application that makes use of beans the way they where intended to be used in combination with jsf2 features and usecases that for example implement basic CRUD usecases around a given type of entity. (One big confusing point is, that in my case ROO always makes use of AJAX and javascript stuff like Modal-Dialogs to implement CRUD logic. I wonder if with JSF there is a more classical way to to this?[With 'classical' i mean for example URL-Based views and separated views for listing, editing and viewing entities])
a resource that enlightens typical "thats-the-way-the-good-guys-do-it" JSF-Patterns (maybe this is J2EE Patterns?).
Thanks you so much!
Please feel free the push me to concretize specific points if i am not clear!
The link for JSF2 you have posted points to JSF1.2 article. In case you want to start of with JSF2 or JSF I suggest following links.
JSF 2.0 Tutorial # mkYong.com
BalusC JSF blog
Stackoverflow wiki for jsf
I'll suggest start with plain vanilla JSF rather than ROO with JSF to get a hang of JSF.
To answer your question
First link provides you with simple jsf examples, in JSF you can have both ajax based and classical way of submitting form. In JSF 1.x versions ajax was not part and parcel of JSF it was implemented by third party component library mainly RichFaces and PrimeFaces to name few. In JSF2 there is inbuilt support for ajax, this does not apply third party components are no longer required, they still provide some extended features. I'll suggest go through this link to find differences between JSF 1.x and JSF 2.
Patterns I am not aware of as such as specific to JSF apart code can be categorized in model - view - controller. Typical case Person represents model, PersonMangedBean plays role of controller which plays central role of getting data from view(jsp/facelets) and after processing data in bean itself or service beans handles navigation to classic views may be listPersons.xhtml.
JSF managed beans are not "super-controller-beans" handling every thing in that bean. I try to categorize things the way you mentioned i.e. have a service layer where we have all business logic may be EJB or Spring managed bean and it decouples at-least business logic away from view technology JSF whereby it(service) can be reused somewhere else as a library if designed properly.
Tip: JSF is component based framework not an action based and it has lifecycle of its own, do get a grip of that life-cycle will save lots of time and proper understanding of the framework. This link though for JSF 1.x holds good for JSF2 too, for basic understanding of life-cycle.
Hope this helps.
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.