在学习Spring Boot中, SpringMVC常用的设置上下文方式 如下:

首先看一下前端booklist.html:

                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>书名</th>
                        <th>作者</th>
                        <th>价格</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="book : ${books}">
                        <td th:text="${book.id}"></td>
                        <td th:text="${book.name}"></td>
                        <td th:text="${book.author}"></td>
                        <td th:text="${book.price}"></td>
                    </tr>
                    </tbody>

1.ModelAndView

使用方法如下:

@RequestMapping("/book")
    public ModelAndView queryAll(){
        List<Book> books =bookDao.selectAll();
        ModelAndView modelAndView =new ModelAndView("booklist");
        modelAndView.addObject("books",books);
        return  modelAndView;
    }

1、高内聚低耦合原则。实质上上设计的函数尽量不带参数,便于不同系统间调用时更简单。 推荐使用ModelAndView, ModelAndView实质上是map,和web容器没有关系。

2.Model

使用方法如下:

@RequestMapping("/book")
public String queryAll(Model model){
     List<Book> books =bookDao.selectAll();
     model.addAttribute("books" ,books);
     return "booklist";
 }

SpringMVC会自动创建Model对象,但是在一些特殊情况下需要手动创建对象。

3.HttpServletRequest

使用方法如下:

 @RequestMapping("/book")
    public String queryAll(HttpServletRequest request){
        List<Book> books =bookDao.selectAll();
       request.setAttribute("books",books);
        return  "booklist";
    }

4.WebRequest

使用方法如下:

     @RequestMapping("/book")
    public String queryAll(WebRequest webRequest){
        List<Book> books =bookDao.selectAll();
       webRequest.setAttribute("books",books,WebRequest.SCOPE_REQUEST);
        return  "booklist";
    }

WebRequest和HttpServletRequest这两种方法 和WEB容器强耦合, 不利于 更换容器或者扩展。不建议这两种方式

标签云

ajax AOP Bootstrap cdn Chevereto CSS Docker Editormd GC Hexo IDEA IPA JavaScript jsDeliver JS樱花特效 JVM Linux markdown Maven MyBatis MyBatis-plus MySQL Pictures Sakura SEO shadowrocket Spring Boot Spring Cloud Spring Cloud Alibaba SpringMVC SSR Thymeleaf V2ray Vue Web WebSocket Wechat Social WordPress Yoast SEO 代理 分页 图床 小幸运 苹果iOS国外账号 苹果IOS账号