Monday, 25 January 2016

ServletContextAware Controller class with Spring

I rarely need to save state within the Servlet Context via an application scope, but recently I did and here is what your controller class would look like to get access to the ServletConext with Spring. I was using Spring Boot 1.3.2.RELEASE.

In short you implement the "org.springframework.web.context.ServletContextAware" interface as shown below. In this example we retrieve an application scope attribute.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CommentatorController implements ServletContextAware
    private static final Logger log = LoggerFactory.getLogger(CommentatorController.class);
    private static final JsonParser parser = JsonParserFactory.getJsonParser();

    private ServletContext context;

    public void setServletContext(ServletContext servletContext)
        this.context = servletContext;

    @RequestMapping(value="/", method = RequestMethod.GET)
    public String listTeams (Model model)
        String jsonString = (String) context.getAttribute("riderData");
        List<Rider> riders = new ArrayList<>();

        if (jsonString != null)
            if (jsonString.trim().length() != 0)
                Map<String, Object> jsonMap = parser.parseMap(jsonString);
                List<Object> riderList = (List<Object>) jsonMap.get("Riders");

                for (Object rider: riderList)
                    Map m = (Map) rider;
                            new Rider((String)m.get("RiderId"),

                //"Riders = " + riders.size());
                model.addAttribute("ridercount", riders.size());
            model.addAttribute("ridercount", 0);

        model.addAttribute("riders", riders);

        return "commentator";


No comments: