加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 如何以spring形式绑定子类对象提交为modelAttribute

发布时间:2020-12-15 01:33:23 所属栏目:大数据 来源:网络整理
导读:我有 Class Shape { //Implementation}Class Round extends Shape{ //Implementation} 调节器 我有 @Requestmapping(value="/view/form")public ModelAndView getForm(){ModelAndView mav=new ModelAndView();mav.addObject("shape",new Round());}@RequestM

我有

Class Shape {
      //Implementation
}
Class Round extends Shape{
      //Implementation
}

调节器
我有

@Requestmapping(value="/view/form")
public ModelAndView getForm(){
ModelAndView mav=new ModelAndView();
mav.addObject("shape",new Round());
}


@RequestMapping(value="/submit",method = RequestMethod.POST)    
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape){
         if(shape instanceof Round){ //**Not giving positive result**

         }
    }

在Jsp

当我用Round对象提交表单时.在控制器端,ModelAttribute没有给出Round的实例.它只给出形状的例子.这该怎么做

最佳答案
你不能做这个.因为这是两个不同的请求生命周期.

@Requestmapping(value="/view/form")
public ModelAndView getForm(){
ModelAndView mav=new ModelAndView();
mav.addObject("shape",new Round());
}

当执行上述请求时,即使您在mav中添加了Round对象,它也已转换为html响应并发送回客户端.

因此,当您提交表单时接下来请求时,它是一个完全独立的请求,并且spring无法识别为先前的请求添加了哪个对象类型.

@RequestMapping(value="/submit",method = RequestMethod.POST)    
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape){
         if(shape instanceof Round){ //**Not giving positive result**

         }
    }

但是你可以尝试探索@SessionAttributes,使用它可以在不同的请求中维护相同的对象

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读