سؤال

This is the short description of my situation...

  • I have spring bean BookingServiceImpl which implements BookingService
  • BookingService has method: RoomDescription getRoomDescriptionById(String roomId);
  • I also have JSP page with javascript on it
  • I want to do something like this in javascript

    var roomDescription = bookingService.getRoomDescriptionById(222);

    /// ... use roomDescription

The question is: is there any existent framework which does things like that (magically allows to cal spring beans from javascript without additional boiler-plate code, assuming all parameters and method results are JSON-friendly)?

هل كانت مفيدة؟

المحلول

Spring provides mechanisms to expose RESTful endpoints via the Web MVC framework

The documentation is very good. A Controller definition for your specific example could look like this:

@Controller
@RequestMapping(value = "/rooms/{roomId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Room getRoom(@PathVariable String roomId, ModelMap modelMap) {    
    return bookingService.getRoomById(roomId);
}

On the javascript side, you could use jQuery to make an ajax call to retrieve the data. Here is an example of what that could look like:

$.getJSON('http://yourserver.com/rooms/222',
    function(room) {
       // Do something with room.description
    });

This is a basic example (without proper error handling, security, etc). It's the closest thing to an existent framework that I'm aware of for Spring RESTful calls from javascript. If you need to access the Room data on the client side javascript then you'll need to expose it via some Spring construct (e.g. a Controller)

نصائح أخرى

Take a look at DWR. This is as close as you will get to creating js clients. http://directwebremoting.org/dwr/documentation/server/integration/spring.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top