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.
Related
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.
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
For a web application, I need to return a model to a view.
For a mobile application or API, I want to return xml or json.
Is it possible to do all of these using a single controller method, or do I have to duplicate this and create seperate API controller's etc?
With Spring MVC 3.x you can do this with just the one controller method. The trick is to wire up the appropriate ContentNegotiatingViewResolver in your Spring config. You can configure it to return the desired content type based on file extension and/or requested mime type.
It works best for methods that only add a single model attribute to the Model, otherwise the JSON/XML starts to get a bit ugly.
I often find its simpler/nicer to implement separate controller methods for my web service requests, as you can better control the format of the JSON/XML and the code is easier to maintain in the long term.
EDIT: Just to qualify my comment above, I find that complex JSP pages where there might be up to 5-10 model attributes added to the page, that the resulting JSON tends to be quite messy and you usually find you only really want 1-2 of those in the JSON. OTOH, simple pages with 1-2 models added work quite well.
This is my first time with wicket, so please bear with me.
Most examples in wicket show how with a wicket id you can automagically replace the inner HTML with different things. Using this knowledge I've hand written a form in HTML with lots of formatting and JQuery for different things, and only using Wicket to autogenerate the info for 2 select boxes. However when I try to parse the submitted information on the Wicket side, I get confused.
The only way I've figured out that's easy is using RequestCycle.get().getRequest().getRequestParameters(). to get all the passed info. It works, but I don't think that's the ideal way to use Wicket. There also seems to be a way with request handlers but I have no idea where to start, especially since a lot of documentation is out of date with the new 6.0.0 release.
What is the way I'm supposed to use Wicket with forms? Do I hand write most of the form, only let Wicket autogenerate some of the info, and use RequestCycle? Do I write a skeleton form, have Wicket autogenerate the rest, and use lots of submit handlers? Where is this documented in an easy to understand beginner tutorial?
Note: My form has several fields that are created dynamically (think "click here to add more options") and is submitted in the background with AJAX, verified, then cleared. This might complicate the Wicket side of things, but is a functional requirement
With Wicket you can think of HTML markup as if it was a template. Markup is actually almost-standard HTML. You can (and should) define wicket:id attributes for everything that will have certain behavior or logic attached (forms, buttons, links), or require some server-side processing (such as form components or nested custom components or panels). Everything else will be output in the response as it is in the markup.
Wicket will handle form submission and process the request for you. In Wicket, form components are usually defined server-side, and added to a Form component. In the Form component's onSubmit(), Wicket will have already processed the request, and the submitted values will be available in the FormComponent's Models.
So, the ideal way for Wicket to handle form submission would involve the server-side creation of any components in the form.
The following Wicket Examples page shows a basic Form with some FormComponents in it: Wicket Examples - forminput. You can even see its source code.
Also, you might find the following Wicket wiki page useful: How to do things in Wicket - Forms.
Regarding dynamic component creation, whenever a new dynamic component has to be created, you could for instance make an Ajax request that creates the component server side (wrapped in a ListView, for example), and get markup refreshed in the ajax callback.
There's an example of such a list here: Wicket in action - Building a ListEditor form component
Just to add, I found the Wicket in Action book to be an excellent resource for learning Wicket. Chapter 6 - Processing user input using forms elaborates on the subject.
Using jQuery AJAX, can we call a specific JAVA method (e.g. From an Action class)
The returned data from that Java method would be used to fill in some HTML code.
Please let me know if this can be done easily using jQuery (like it does in DWR)..Also for multiple data points in HTML, do we need to make multple AJAX requests?
The simple answer is you map your ajax calls to urls, which are in turned map to methods in your java code. The Ajax -> URI mapping happens on the client side (which ever js framework you are using, and the URI -> specific handler mapping happens within the java application)
What java framework are you using? There should be very clear and simple documentation on how to do this. For standard Java EE mappings (meaning you are not using any frameworks like Spring or Roo) I found this on google: http://javapapers.com/servlet/what-is-servlet-mapping/
"For multiple data points in HTML" I assume you are talking about having multiple parts of the html update. You can do this with multiple requests, or you can do it with one request. If you do the latter, the server needs to return all the data you need to update the dom appropriately.
It's not as transparent as with DWR--DWR handles making JavaScript look like Java. With jQuery you'll get JSON (or just HTML if/when it's easier that way). It's still pretty straight-forward, though. You'd send the Ajax request to a URL, rather than having it look like a local method call.
I'm not sure what you mean by "multiple data points in HTML" -- you get back whatever data you get back, and you can do with it whatever you want. If the response has all the data you need, then you wouldn't need to make multiple requests.