【问题标题】:How to access Model Attribute's value and set to ModelAndView如何访问模型属性的值并设置为 ModelAndView
【发布时间】:2020-08-17 17:07:05
【问题描述】:

我似乎找不到解决办法。

我有返回 ModelAndView 来查看网页的方法。

每当条件为真时,我都会存储一个网页文件名来建模。

例子:

    @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")
        }
          
            

如何检索存储在“异常”中的数据并将其设置为 ModelAndView?

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

【问题讨论】:

    标签: java http spring-mvc request-mapping modelandview


    【解决方案1】:
            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);    
    

    我找到了办法,

    但我认为有更好的方法来做到这一点。

    【讨论】:

      【解决方案2】:
      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>
      

      【讨论】:

      • 谢谢,但我需要在我的 java 控制器 (java) 中检索数据,而不是在视图 (jsp/html) 中。如果可能的话
      • 是任何 html/jsp 的“例外”,你是如何调用 url /process 的?您需要从该视图本身发送该数据,并通过 @RequestParam/@Pathvariable 绑定到控制器中
      • exception 不是文件名,我使用Model 将值存储到exceptionmodel.addAttribute("exception", "web_file2"),我认为我不需要通过视图发送数据,因为我对于我拥有的每个条件,还有其他文件名。
      猜你喜欢
      • 2016-12-13
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多