Kleber Mota Kleber Mota - 4 months ago 34
HTTP Question

Read variable from http context in spring controller

Let me say i want retrieve some information from http context. In my thymeleaf page, I use somethinf like that:

<span th:text="${#httpServletRequest.getHeader('Accept-Language')}"></span>


in my thymeleaf processor, however, I use a code like that:

String language = arguments.getContext().getLocale().getLanguage();
String country = arguments.getContext().getLocale().getCountry();


How I can retriee this same information in my spring controller, implemented the way below?

@RequestMapping("/insert_texto/{page}")
public ModelAndView insert_texto(Model model, @PathVariable("page") String id) {
...
}

Answer

I would annotate the servlet request or context directly in your controller:

@Autowired
ServletContext context;

@RequestMapping("/insert_texto/{page}")
public ModelAndView insert_texto(Model model, @PathVariable("page") String id)  
{
    // use context
}

Or, if you prefer, pass ServletContext as a variable to your method:

@RequestMapping("/insert_texto/{page}")
public ModelAndView insert_texto(Model model, @PathVariable("page") String id, ServletContext context)  
{
    // use context
}