Page 1 of 2 12 LastLast
Results 1 to 10 of 13

Thread: Spring mvc - ajax rookie - how shown values from server object ModelAndView

  1. #1
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default Spring mvc - ajax rookie - how shown values from server object ModelAndView

    Hello guys i need your help in this topic

    well my case is this i have a controller with spring mvc like this

    Code:
    public class TestAjax implements Controller {
    
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		Map<String, String> domain = new HashMap<String, String>();
    		System.out.println("ManoloTestAjax");
    		domain.put("dateString", "fecha");
    		domain.put("strings", "some string");
    		return new ModelAndView("ajaxtest", "domain", domain);
    now in the client (ajaxtets.jsp) i have and recieve response from the server

    Code:
    function handleStateChange() {
        if(xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                alert("from server won!!!!"); <---- works
                parseResults();
            }
        }
    }
    Code:
    <h1>Hello World!</h1>
    <H2><fmt:message key="welcome"/></H2>
    <input name="test" value="test" type="button" onclick="doRequestUsingPOST();">
    <h3>Date string: <c:out value="${domain.dateString}" /></h3>
    <h3>Mi Muņeca: <c:out value="${domain.strings}" /></h3>
    i read a book about how wok with ajax (the server side is java servlets),
    but in all the examples i saw that send the information in format xml,
    now i know that the controller can send a "ModelAndView"

    so sorry for my ignorance, how can i show the "ModelAndView" in the jsp??,
    because when i recieve the information form the server
    the jsp fields
    Code:
    <c:out value="${domain.variable}"
    show nothing

    thats mean how should i manage the xmlHttp object to show the information from the server because is an object not a xml response how the classical examples of the book

    thanks for advanced
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  2. #2
    Join Date
    Dec 2006
    Location
    Sebastopol, California
    Posts
    40

    Default

    Very interesting topic. To just give a simple narrative of how I've been doing AJAX...

    First of all, grab one of the js libraries that simplify the whole request cycle... YUI-ext has been very nice for me. There is a prepackaged way to do what you want with the YUI-ext.

    http://www.yui-ext.com/deploy/yui-ext/docs/

    If you are simply generating replacement content for a <div/>, then this is all the javascript you need:

    var mgr = new YAHOO.ext.UpdateManager('searchbox');
    mgr.update('/search/showbox.html');

    These lines find the element with id "searchbox" and replace its contents with the result of calling the url at /search/showbox.html

    To do fancier things is a little more complex but I've found that this library is just magnificient.

    So in other words prepare your controller and view as you would normally, getting it just ready on the server side for insertion into the page. Then the AJAX call will take care of the rest. I don't think there is any way to propagate the ModelAndView object all the way down to javascript unless you're using some kind of emitter technology like DWR.

    So I guess what your example code is missing is that you need a separate view template for the stuff your AJAX call is returning.

    I hope that helps some, Charles

  3. #3
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    hi grechaw

    thanks for the reply

    First of all, grab one of the js libraries that simplify the whole request cycle
    a good amount i think so

    If you are simply generating replacement content for a <div/>, then this is all the javascript you need:
    yes, it is the tipical examples of the book (for all book) , again with java servlets but always returning the information like xml format
    , no like an object returned by a controller in spring mvc


    So in other words prepare your controller and view as you would normally, getting it just ready on the server side for insertion into the page. Then the AJAX call will take care of the rest.
    i did it

    I don't think there is any way to propagate the ModelAndView object all the way down to javascript unless you're using some kind of emitter technology like DWR.
    yes you right, it seems that DWR is the solution

    So I guess what your example code is missing is that you need a separate view template for the stuff your AJAX call is returning
    i will read carefully DWR solution

    thanks for your opinion Charles

    dr_pompeii
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  4. #4
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    hello guys

    after reading the book "Pro Ajax and Java Frameworks" only chapter 4 and 7
    i learnt how work with DWR, good framework (chapter 4)

    and seeing how work DWR with Spring (chapter 7), really i see that not work really with the Controller , instead work directly with the service,

    so if the normal bevaviour is that a jsp file call a controller and then it call the service, its not happens with DWR, why???, DWR can transform data types from java to js and viceversa like String, ArrayList etc etc, and DWR can send parameters to be used by the server

    but in a Controller like

    Code:
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		Map<String, String> domain = new HashMap<String, String>();
    		System.out.println("ManoloTestAjax");
    		domain.put("dateString", "fecha");
    		domain.put("strings", "some string");
    		return new ModelAndView("ajaxtest", "domain", domain);
    is capable DWR to convert an object ModelAndView to js???? ,
    if the answer is yes, how pls
    and imposible send parameters to the controller

    really i am lost about how work with a controller/DWR , i can do it with the service directly of course, but is this not brake the rules of the pattern mvc???

    thanks for advanced for suggestions
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  5. #5
    Join Date
    Dec 2006
    Location
    Sebastopol, California
    Posts
    40

    Default

    I confess I don't see the motivation for wanting your ModelAndView in js. ModelAndView is just a wrapper object for a Model and a View. The view is completely a server-side phenomenon... why would the browser or js have any need to know about it?

    If you want to push the complete modelMap out to the client, you could serialize it as JSON or XML... Or just make sure that the rendered view provides everything you need to pick up on the client side.

    Charles

  6. #6
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    hello grechaw

    I confess I don't see the motivation for wanting your ModelAndView in js. ModelAndView is just a wrapper object for a Model and a View.
    yes u right, and i am agree

    The view is completely a server-side phenomenon... why would the browser or js have any need to know about it?
    what happens if i need wrap in the model 2 arraylist and one pojo?
    Code:
    domain.put("somearrayinfo1", service.getListX());
    domain.put("somearrayinfo2", service.getListY());
    domain.put("person", service.getPerson(SomeParameterfromClientsideAjax));
    If you want to push the complete modelMap out to the client, you could serialize it as JSON or XML... Or just make sure that the rendered view provides everything you need to pick up on the client side.
    i dont know much about json or if is the unique solution for my case, but is risky work ajax with the spring service directly??? , if not,should i call the server 3 times (to get 2 array and one pojo) ???

    i hope you see my point

    regards
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  7. #7
    Join Date
    Dec 2006
    Location
    Sebastopol, California
    Posts
    40

    Default

    Thus far I've stayed clear of DWR, but I've only written the simplest of AJAX apps. It really looks like your problem has very little to do with Spring MVC. Think of the whole package that your controller is making, after having rendered the view.

    If all you're looking to do is serialize your data for use in javascript, then you'll probably want to bypass the whole ModelAndView approach. Just construct your ModelMap, and then serialize the data (JSON is very nice for this). Then instead of returning a ModelAndView from the controller, intercept the response and throw the serialized data to it.

    handleRequest {
    ... create a serialized object
    response.getOutputStream().write(serializedMap);
    response.getOutputStream().flush();
    return null;
    }

    When your javacript hits this controller and gets the response back, it can parse it and use the data as it sees fit. There's no need for a view template.

    BTW I have found the firebug plugin for Firefox ABSOLUTELY INDISPENSIBLE for working with any kind of ajax...

  8. #8
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    hi

    then you'll probably want to bypass the whole ModelAndView approach. Just construct your ModelMap, and then serialize the data (JSON is very nice for this).Then instead of returning a ModelAndView from the controller, intercept the response and throw the serialized data to it.
    is this heavy in process information???

    There's no need for a view template.
    why are you telling this??

    BTW I have found the firebug plugin for Firefox ABSOLUTELY INDISPENSIBLE for working with any kind of ajax...
    i never heard this bug, and until now i dont have any problem with ajax in firexox (i work in linux), so the question is when happen this bug???

    can you share a simple example of your suggested solution with JSON and ModelAndView??
    i never work with JSON, i just learnt DWR and now i have your option

    again:
    is risky work ajax with the spring service directly???

    but what way is better? , yours with JSON or my option?? and why?

    best wishes
    thanks for your time
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  9. #9
    Join Date
    Dec 2006
    Location
    Sebastopol, California
    Posts
    40

    Default

    I actually haven't used the JSON approach that I described... I've only used HTML divs as the AJAX partial because I dont' need to do much data work on the js end. But here's a controller method:

    Code:
    public ModelAndView tocPartial(HttpServletRequest request, HttpServletResponse response) {
            String fpi = request.getParameter("fpi");
            ModelAndView mav = new ModelAndView("tocPartial");
            mav.addObject("toc",service.getHtmlToc(fpi));
            return mav;
        }
    So the service layer just puts an object into the mav with key "toc".
    The view is a velocity template. Here is the complete file:
    Code:
    <div id="currentToc">  
    $toc
    </div>
    And the javascript that calls and makes use of it.
    Code:
    loadToc: function(elem, fpi) {
        	var responseSuccess = function(o) {
        		o.argument.elem.style.display = "none";
        		o.argument.elem.innerHTML = o.responseText;
        		Toc.buildTreeFromToc(fpi);
     	  		var tocButton = YAHOO.util.Dom.get('tocbutton-'+fpi);        
    			tocButton.style.cursor = 'pointer';
        	}
        	var responseFailure = function(o) {
        		o.argument.elem.innerHTML('<span style="color: red">Fatal Error: '+o.statusText+'</span>');
        	}
        	var callback = {
    	    	success:responseSuccess,
           		failure:responseFailure,
           		argument: {elem: elem }
        	}
        	var params = "fpi="+fpi;
            YAHOO.util.Connect.asyncRequest('POST','/toc.html',callback,params) ;	             
        },
    ...
    So there's an example of using a view to replace a part of a page (here, whatever element is passed to the AJAX function.) They key is making your view something that can be parsed with javascript.

    is risky work ajax with the spring service directly???
    I've always been nervous about it, but I think that DWR is really well done. Just separate the beans you want to expose into their own context file so it's easy to see what DWR has access to. So I guess I dunno.

    Firebug is an extension that lets you examine AJAX requests as they happen, as well as the structure of the DOM. I highly recommend it:

    http://www.getfirebug.com/

    Charles

  10. #10
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    hello grechaw

    thanks so much for your time and by share code, it is appreciate

    why are you using?
    Code:
    public ModelAndView tocPartial(HttpServletRequest r....
    and not the classical
    Code:
    protected ModelAndView handleRequestInternal(HttpServletRequest request,	HttpServletRespons
    in first glance by the protected access i think, but the protected access must be in your controller right? or your recieve error by the extention of the class,such as, extends AbstractController {

    about your YAHOO.util.Dom i must read more about that, i dont understand all, but i have now the main idea

    I've always been nervous about it, but I think that DWR is really well done.
    me too

    Just separate the beans you want to expose into their own context file so it's easy to see what DWR has access to. So I guess I dunno.
    i dont think that the author did a silly chapter using directly DWR with a bean service instead of a controller, making security problems or risk

    if you know a book or a nice link tutorial for YAHOO/ajax pls share it

    about http://www.getfirebug.com/, good link, thanks!, i thought that was a bug of firefox, lol

    regards
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •