views:

57

answers:

2

Here is my problem, I need to map a AJAX request using spring. Now, I know that I need these two guys:

HttpServletRequest, to get the message the client sent to me and parse it from JSON(most likely) to a Map and HttpServletResponse to put my message to the client. What I do not know is the right(simple, concise) way to do that...

Here is a code sample from the springframework site:

/**
 * Normal comments here
 *
 * @@org.springframework.web.servlet.handler.metadata.PathMap("/foo.cgi")
 * @@org.springframework.web.servlet.handler.metadata.PathMap("/baz.cgi")
 */
public class FooController extends AbstractController {

    private Cruncher cruncher;

    public FooController(Cruncher cruncher) {
        this.cruncher = cruncher;
    }

    protected ModelAndView handleRequestInternal (
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        return new ModelAndView("test");
    }
}

Which is nice. Except that, as far as I can see, I cannot map a URL for each method in that class as I would do with this kind of synchronous request:

@Controller
@RequestMapping("/test")
public class ControllerTest {
    @RequestMapping(value = "/test.htm", method = RequestMethod.GET)
    public void showSearchView(Model model) {...}
    ...
}

Can I do something that simple for AJAX requests?

+1  A: 

Not sure where you found that first example on SpringSource! That is the old-bad(tm) way of doing it. I'm pretty sure AbstractController is even marked deprecated in Spring 3.

The second way works fine for mapping AJAX requests. If you really want to parse it all yourself, HttpServletRequest and HttpServletResponse are legal parameters for that handler method. However, Spring will happily do it for you: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

(If you're stuck on an older version of Spring there are also 3rd party libraries for adding JSON mapping to handlers.)

Affe
A: 

This is the answer I found. I modified the method shown in my post and added a HttpServletRequest to the method arguments.

public void showSearchView(Model model, HttpServletRequest req, HttpServletRequest resp) {
        if(req==null||resp==null)throw new RuntimeException("OLOLOLOLOL xD");
}

That's it. If anyone have a better answer or comments, I'd be glad to hear.

Diones