ServletContext not able to inject through by passing it as an parameter in Spring MVC

Tags: , , ,



Hi all i am trying to get ServletContext in my following method but it is not getting injected while passing it as an parameter as it should be injected by the spring automatically but its not working don’t know why this is the following code inside which I want servletcontext

@RequestMapping(value="/savetodo", method = RequestMethod.POST)
    public String saveTodo(@ModelAttribute("todoEntity") TodoEntity todoEntity,Model m,ServletContext sc) {
        todoEntity.setTodoDate(new Date());

        ArrayList<TodoEntity> allTodosArrayList =  (ArrayList<TodoEntity>) sc.getAttribute("allTodos");
        if (allTodosArrayList==null) {
            allTodosArrayList = new ArrayList<TodoEntity>();
        }
        allTodosArrayList.add(todoEntity);
        sc.setAttribute("allTodos",allTodosArrayList);
        allTodosArrayList.stream().forEach(System.out :: println);
        m.addAttribute("page","viewtodos");
        return "home";
    } 

but when I tried using the autowiring by declaring ServletContext as an class variable along with autowired annotation like this and removing the parameter from method

@Autowired
ServletContext sc;

it just worked fine so my whole point is why it is not working when I am passing it as an parameter.

Answer

ServletContext is not one of the auto-resolving method parameters in Spring controllers https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/web.html#mvc-ann-methods



Source: stackoverflow