简体   繁体   English

ServletContext 无法通过将其作为 Spring MVC 中的参数传递来进行注入

[英]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大家好,我正在尝试在我的以下方法中获取 ServletContext,但是在将其作为参数传递时它没有被注入,因为它应该由 spring 自动注入,但它不起作用不知道为什么这是我在其中的以下代码想要servlet上下文

@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但是当我尝试通过将 ServletContext 声明为 class 变量以及像这样的自动装配注释并从方法中删除参数来使用自动装配时

@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 .它工作得很好,所以我的重点是为什么当我将它作为参数传递时它不起作用。

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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM