Spring mvc - Model添加属性

为了让模板引擎知道这些变量的值,我们需要在@Controller做一些工作:

import org.springframework.ui.Model;

@RequestMapping("/blogs/{id}")

public String index(@PathVariable("id") long id, Model model) {

    // 这里我们模拟一些数据

    model.addAttribute("title", "This is a blog with id = " + id);

    model.addAttribute("createdTime", "2015-08-11");

    model.addAttribute("content", "This is content");

    return "index";

}

扫描二维码关注公众号,回复: 327532 查看本文章

在上面的代码中,index()方法增加了一个Model类型的参数。通过Spring MVC框架提供的Model,可以调用其addAttribute方法,这样Thymeleaf可以访问Model中的变量从而进行模板渲染。上述例子中可以看到,title变量的值是根据URL中的@PathVariable来确定的,虽然简单,但是这已经是一个动态页面了。

在Servlet编程中,如果希望在页面中动态渲染信息,一般需要往HttpRequest中添加属性,然后在JSP中获取。其实Model的属性实际上也是放在HttpRequest的属性中,但是Spring MVC提供了更高层的抽象,帮你屏蔽了HttpRequest,你看到的只有直接以MVC中M(即Model)。

如果你依然希望希望HttpRequest、HttpResponse和HttpSession等原生的Servlet API对象,往Controller方法中增加对应类型的参数即可,你在方法中就能直接使用了,Spring MVC会传递给你正确的对象,

猜你喜欢

转载自nethub2.iteye.com/blog/2330468