3

I am trying to use JQuery Full Calendar along with Spring MVC + Freemarker.

I have made a demo like that.

Target: I need to call the controller to fetch JSON object that contains events to render over the calendar.

Issue: I have the following freemarker that it should go to the controller and get the JSON object to render,but it doesn't go ?!!

Freemarker:

[#ftl /]

<script type="text/javascript">
    $(document).ready(function() {

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            selectable: true,
            selectHelper: true,
            select: function(start, end, allDay) {
                var title = prompt('Event Title:');
                if (title) {
                    calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allDay: allDay
                    },
                            true // make the event "stick"
                            );
                }
                calendar.fullCalendar('unselect');
            },
            editable: true,
            events: [
                {
                    url: '[@spring.url '/vacation/getVacation'/]',
                    type: 'GET',

                    data: {
                        start: 'start',
                        id: 'id',
                        title: 'title'
                    }

                }
            ]
        });

    });

body {
    margin-top: 40px;
    text-align: center;
    font-size: 14px;
    font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
}

#calendar {
    width: 900px;
    margin: 0 auto;
}

The controller:

@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    public @ResponseBody   void getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2011-07-28");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);


        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Firebug shot : enter image description here

Echo
  • 2,959
  • 15
  • 52
  • 65
  • can you use firebug to see what url the request is using? Also if you set a debug point in your controller does the code get hit? – Kevin Bowersox Apr 14 '12 at 13:48

2 Answers2

3

Finally, I make it work :) I have used the $.getJSON to fetch the json object.

FreeMarker:

   $(document).ready(function() {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();
          $.getJSON('[@spring.url '/vacation/getVacation'/]', function (data) {
            var calendar = $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                selectable: true,
                selectHelper: true,
                select: function(start, end, allDay) {
                    var title = prompt('Event Title:');
                    if (title) {
                        calendar.fullCalendar('renderEvent',
                        {
                            title: title,
                            start: start,
                            end: end,
                            allDay: allDay
                        },
                                true // make the event "stick"
                                );
                    }
                    calendar.fullCalendar('unselect');
                },
                editable: true,
                events:[data]
            });
         });
        });

Java Controller:

@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    public
    @ResponseBody
    String getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2012-4-15");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);

        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        return json;
    }
Echo
  • 2,959
  • 15
  • 52
  • 65
0
@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    @ResponseBody
    public String getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2011-07-28");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);


        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        return json; //Try simply returning the json
    }

According to spring documentation: The @ResponseBody annotation is similar to @RequestBody. This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

For example:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld()  {
  return "Hello World";
}

I am not sure if this differs from:

response.getWriter().write(json);

This post discusses the difference and one of the solutions mentions conflicts with freemarker: Does spring mvc have response.write to output to the browser directly?

Also try specifying the dataType expected in your ajax call:

$(document).ready(function () {
     var calendar = $('#calendar').fullCalendar({
         editable: true,
         eventSources: [{
         // your event source
             url: '[@spring.url '/vacation/getVacation'/]', // I was expecting here to call the controller,but nothing is happened !!
             type: 'GET',
             data: {
                 start: 'start',
                 id: 'id',
                 title: 'title,'
             },
             error: function () {
                 alert('there was an error while fetching events!');
             },
             color: 'yellow',
             textColor: 'black',
             dataType: 'json'
         }])
     };)
 };

As suggested I would also run your application in debug mode setting a debug point in the controller to see if the code is getting hit. If it is not analyze the url being used in your request with firebug.

Check the configuration file that spring uses to setup the dispatcher. Normally an InternalResourceViewResolver is registered within this configuration. Here is an example of mine:

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

If you find this configuration make sure that it is pointing the area where you are storing your jsp files.

Another thing I just notice from your comment. You said that firebug showed you were trying to hit this url:

:eventSources: [{ // your event source url: '/springway/vacation/getVacation', type: 'GET', data: { start: 'start', id: 'id', title: 'title,' }

I don't like the way that is formatted, specifically it includes the comment, which could render the rest of that line meaningless or be used in the url. I would look at this using the net panel in firebug, which shows the requests going over the wire. This will show you the true url your trying to hit.

I would also edit this line in your js:

url: '[@spring.url '/vacation/getVacation'/]',

to:

url: '/vacation/getVacation',

I am not familiar with @spring.url, but it appears to me it is doing more harm than good at the moment.

Community
  • 1
  • 1
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Hello,Thanks for your reply.I have tried the tips you told me about.However,I still have the same issue.The break point at the controller isn't called. When I used firebug the url seems fine and here it's the firbug view :eventSources: [{ // your event source url: '/springway/vacation/getVacation', type: 'GET', data: { start: 'start', id: 'id', title: 'title,' } So am I missing something here !! – Echo Apr 14 '12 at 14:59
  • When I changed the type of the request at the controller and make it 'Get' .Then browse to "http://localhost:8080/springway/vacation/getVacation" , I get :{"id":111,"title":"event1","start":"2011-07-28","url":"http://yahoo.com/"} .So now I am sure the url is fine but why it's not called at the first place !! – Echo Apr 14 '12 at 15:06
  • Do you have the console (Eclipse) open when you debug it? It should say something like resource not found or something along those lines. Copy that and put it in your answer, also taking a screen shot of your directory structure in (I'm assuming) eclipse or sts could help us help you. – Kevin Bowersox Apr 14 '12 at 15:32
  • Do you have an InternalViewResolver setup in your spring config? – Kevin Bowersox Apr 14 '12 at 15:42
  • Regarding firebug console ,I have no errors. Regarding the controller I don't have reported on the on conole of IDE as the action didn't go yet to the controller.Yes I'd already a freemarker view resolver setup into my config. – Echo Apr 14 '12 at 16:05
  • While debugging I've found out one issue at my freemarker and I've resolved it ,please review my freemarker that I have edited now. – Echo Apr 14 '12 at 16:09
  • Still doesn't go to me controller !! – Echo Apr 14 '12 at 16:22
  • Did you try removing the @spring.url portion of the code as I have mentioned in my answer? I'm not sure what that is appending to your url, but I believe it is unnecessary because '/vacation/getVacation' should get appended to your context root creating the url 'localhost:8080/springway/vacation/getVacation' which you have verfied works – Kevin Bowersox Apr 14 '12 at 16:22
  • I even tried to make a dummy thing and I put manually the "events: [ { url: 'http://localhost:8080/springway/vacation/getVacation', type: 'GET'," but no success so far !! – Echo Apr 14 '12 at 16:47
  • SO.. are there are any suggestions !! – Echo Apr 14 '12 at 17:26
  • In order to provide you with suggestions I need more information. Mainly I need you to post your spring configuration, I willing to help you but I need to know more about the problem. Also when you debug there should be messages logged in the console when the server receives the ajax request. – Kevin Bowersox Apr 14 '12 at 17:38
  • Thanks for insisting on assistance :) You can find my demo on the following url. NOTE:you should deploy it over Tomcat 7 as I use Spring 3 java based configuration:http://www.4shared.com/zip/xOTvooup/SpringWay_2.html – Echo Apr 14 '12 at 18:06
  • I've been trying to find any workarounds.I have an ajax function that goes to the controller and gets the json object:function doAjax() { $.ajax({ url: '[@spring.url '/vacation/getVacation'/]', data: ({name : "me"}), success: function(data) { jsonObject=data; } }); }Then I have used that jsonObject like the following: $(document).ready(function() { jsonObject=doAjax(); var calendar = $('#calendar').fullCalendar({ events:jsonObject }); }); The request goes to the controller and the calendar renders but the data I have requested isn't binded !! – Echo Apr 14 '12 at 20:05
  • Look at the request with firebugs and checkout the response. What do you see. – Kevin Bowersox Apr 14 '12 at 20:14
  • Kindly find the image at the post.Note when I alert(jsonObject),I get :{"id":111,"title":"event1","start":"2011-07-28","url":"http://yahoo.com/"} – Echo Apr 14 '12 at 20:27
  • @Echo no problem, I'm sorry I couldn't be of more help but I have a large grad school assignment due. I'm also not familiar with the full calendar library. – Kevin Bowersox Apr 14 '12 at 22:02