Skip to content
Advertisement

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

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.

Advertisement

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement