如何在Spring中将变量从java传递给jsp


问题内容

在Spring框架中,我想将一些变量(对象)传递给jsp页面。我可以通过以下方式传递一个对象:

 ModelAndView modelAndView= new ModelAndView("JspPageName", "message", message); 
 return message

但是如何将多个对象从Java发送到jsp。实际上,我知道我可以创建一个对象数组并发送该数组,但是我想知道执行此操作的最佳方法我的将数据发送到jsp的代码是这样的:

@Controller
public class DomainEkleController {
    private DomainJDBCTemplate  domainJDBCTemplate;
    private MemurJDBCTemplate memurJDBCTemplate;
    @ModelAttribute("Domain")
    public Domain getDomain()
    {
        return new Domain();
    }

    @Autowired
    @Qualifier("domainJDBCTemplate")
    public void setDomainJDBCTemplate(DomainJDBCTemplate domainJDBCTemplate) {
        this.domainJDBCTemplate = domainJDBCTemplate;
    }

    @Autowired
    @Qualifier("memurJDBCTemplate")
    public void setMemurJDBCTemplate(MemurJDBCTemplate memurJDBCTemplate) {
        this.memurJDBCTemplate = memurJDBCTemplate;
    }

    @RequestMapping(value="/DomainEkle")
    public ModelAndView domainEkle() {

        List<Memur> memurlar=memurJDBCTemplate.getAll();
        System.out.println(memurlar);
        /*for(Memur x:memurlar)
        {
            System.out.println(x.getIsim());
        }*/
        String message = "Hello World, Spring 3.0!";
        ModelAndView domain_ekle= new ModelAndView("DomainEkle", "message", message);
        return domain_ekle;
    }




    @RequestMapping(value="/DomainEkle",method=RequestMethod.POST)
    public ModelAndView domain_eklendi_fonksiyon(@ModelAttribute("Domain")Domain domain,   ModelMap model)
    {




        model.addAttribute("domain_adi", domain.getDomain_adi());
        model.addAttribute("sunucu_no", domain.getSunucu_no());
        model.addAttribute("tarih", domain.getTarih());
        model.addAttribute("ilgili_memur_no",domain.getIlgili_memur_no());

        String message="Domain Kaydi Yapilmistir!";
        ModelAndView dm_eklendi=new ModelAndView("DomainEkle","message",message);

        domainJDBCTemplate.addDomain(domain);
        return dm_eklendi;

      }

}

问题答案:

您会注意到ModelAndView有一个接受Map<String, ?>

ModelAndView mav = new ModelAndView("someView", map);

因此,构建一个包含模型属性的地图

 Map<String, Object> map = new HashMap<>();
 map.put("attrib1", someAttrib);

您可以在此映射中放置尽可能多的键值对对象,然后将其传递给构造函数或调用

mav.addAllObjects(map);

添加所有属性的方法。这些属性将最终在HttpServletRequestJSP可以使用的位置。

最终等于将ModelModelMap作为参数传递给处理程序方法。与您的domain_eklendi_fonksiyon()方法相同。