request and session attribute value returns null in @ModelAttribute method

1.8k views Asked by At

Am using spring mvc i want to access an request attribute inside @ModelAttribute method but its giving only null

@RequestMapping(value = "/abc", method = RequestMethod.GET, params = "data")
    public ModelAndView aaaa()
             {
        String courseId = httpServletRequest.getParameter("courseValue");
        System.out.println("course value data :" + courseId); // here am getting value

        httpServletRequest.setAttribute("courseId", courseId); // setting in request 
         attribute
        WebUtils.setSessionAttribute(httpServletRequest, "courseId", courseId);
        // setting in   session attribute
        ModelAndView modelAndView = new ModelAndView("abc");
        return modelAndView;
    }



   @ModelAttribute("termList")
   public Map<String, String> def(HttpServletRequest httpServletRequest) 
    {
    String courseId = (String) WebUtils
            .getSessionAttribute(httpServletRequest, "courseId");
    System.out.println("course value in term :" + courseId); // here its giving null
    Map<String, String>map = courseSubLinkService.getTermDetailsBasedOnCourseId
            (courseId);

    httpServletRequest.setAttribute("termList", map);
    return map;

   }

I dont know where i did wrong please help me to get this value

1

There are 1 answers

1
mvb13 On

From Spring docs:

@ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller

This means that in moment when def is invoked HttpServletRequest hasn't attribute that you need because you set this attribute in aaaa method that will be invoked after def.