Search code examples
javahttpspring-mvcrequest-mappingmodelandview

How to access Model Attribute's value and set to ModelAndView


I cant seem to find the solution for this.

I have method that returns ModelAndView to view web pages.

I store a webpage filename to model whenever a condition is true.

Example:

    @RequestMapping(value = "/process", method = RequestMethod.POST)
    public ModelAndView processRequest(HttpServletRequest request,
    HttpServletRequest response, Model model,@RequestParam("file") MultipartFile file) 
    throws IOException {
        
        if (file.isEmpty()) {
             model.addAttribute("exception", "web_file1")
        } else {
             model.addAttribute("exception", "web_file2")
        }
          
            

How can I retrieve the data stored in "exception" and set it to ModelAndView?

                ModelAndView mav = new ModelAndView();
                mav.setViewName("exception");  
                //expected:web_file2 
                //actual:exception
                return mav;
        

Solution

  •         model.addAttribute("exception", "web_file2")
    
            String sModel=model.toString();  //{exception=web_file2}
            String returnView = (sModel).substring(11,sModel.length()-1);  //web_file2
            return new ModelAndView(returnView);    
    

    I've found a way to get it,

    But I think there's a better way to do this.