日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

实现MVC模式的Web应用程序

發(fā)布時(shí)間:2025/4/5 c/c++ 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 实现MVC模式的Web应用程序 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

實(shí)驗(yàn)結(jié)果

1.添加Thymeleaf依賴

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>

當(dāng)然別忘記在application.properties文件中視圖解析器,筆者這一步出現(xiàn)錯(cuò)誤
需要配置成如下

#定位模板的目錄 spring.mvc.view.prefix=classpath:/templates/ #給返回的頁面添加后綴名 spring.mvc.view.suffix=.html

Thymeleaf模版默認(rèn)會(huì)使用templates作為視圖文件

2.創(chuàng)建實(shí)體模型
創(chuàng)建實(shí)體Bean,用于和Controller進(jìn)行數(shù)據(jù)交互
右擊com.example.demo,new-package,名字命名為model

此時(shí)包的路徑package com.example.demo.model;

package com.example.demo.model; import lombok.Data; @Datapublic class User {//private long id;private String name;private int age; }

3.創(chuàng)建控制器
控制器層用來實(shí)例化實(shí)體Bean(Model),并傳值給視圖模板
右擊com.example.demo,new-package,名字命名為controller,然后右鍵創(chuàng)建新的類

package com.example.demo.controller; import com.example.demo.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView;@Controller public class MVCDemoController {//映射URL地址@GetMapping("/mvcdemo")public ModelAndView hello() {//實(shí)例化對(duì)象User user=new User();user.setName("shizheng");user.setAge(10);//定義mvc中的視圖模板ModelAndView modelAndView=new ModelAndView("mvcdemo");//需要和html文件名相匹配//傳遞user實(shí)體對(duì)象給視圖modelAndView.addObject("user",user);return modelAndView;} }

4.創(chuàng)建用于展示的視圖
也就是html文件
右鍵templates,new創(chuàng)建新的HTML File,命名為mvcdemo
這里需要注意:html文件的名字需要和控制器層用到的名字相一致

//定義mvc中的視圖模板ModelAndView modelAndView=new ModelAndView("mvcdemo");//需要和html文件名相匹配

html文件中

<!DOCTYPE html> <!--thymeleaf模板支持--> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div><!-- 顯示由控制器傳遞過來的實(shí)體user的值--><div th:text="${user.name}"></div><div th:text="${user.age}"></div> </div> </body> </html>

5.運(yùn)行程序,會(huì)在http://localhost:8080/mvcdemo中看到文章開始的界面

筆者在做這個(gè)實(shí)例時(shí),需要問題,如果讀者遇到相似的問題,可以參考本篇博客《Spring Boot實(shí)戰(zhàn)派》 實(shí)例7實(shí)現(xiàn)MVC模式的Web應(yīng)用程序 遇到的問題

總結(jié)

以上是生活随笔為你收集整理的实现MVC模式的Web应用程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。