vixe
vixe

Reputation: 39

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;
        

Upvotes: 0

Views: 3739

Answers (2)

vixe
vixe

Reputation: 39

        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.

Upvotes: 1

Avinash Mishra
Avinash Mishra

Reputation: 21

1.  put your  data using 
mv.addObject("exception","web_file1");

in your view retrieve data by the key ie exception ${exception}
eg : <input type="text" value="${exception}" />

2. if used spring mvc with jsp/html Ensure you have declared  a bean for viewResolver
which has following format

  

      <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>abc.jsp</value>
            </property>
        </bean>

Upvotes: 0

Related Questions