จะสร้างโปรแกรม MCV ได้อย่างรวดเร็วได้อย่างไร?
อ้างถึงตัวอย่างฤดูใบไม้ผลิอย่างเป็นทางการ: https://spring.io/guides/gs/serving-web-content/
1. สปริง MVC รวมกับเทมเพลต thymeleaf
หลังจากสร้างโครงการ Maven ให้แก้ไขไฟล์ pom.xml
<Project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http:/MANCMMMMMMMMMMMMMMMMMMMMMMMMMMBM http://maven.apache.org/xsd/maven-4.0.0.xsd "> <moderVersion> 4.0.0 </modelversion> <roupid> com.github.carter659 </groupid> <RoupID> org.springframework.boot </groupid> <ratifactid> Spring-Boot-Starter-Parent </artifactid> <cersion> 1.4.2.release </version> </parent> <name> Spring02 </name> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <java.version> 1.8 </java.version> </premerties> <pernceies> </perctency> <predency> <roupId> org.springframework.boot </groupid> <ratifactid> Spring-Boot-Devtools </artifactid> <plorial> True </onftiveal> </การพึ่งพา> </การพึ่งพา <ArtIfactId> Spring-Boot-Maven-Plugin </artifactid> </plugin> </plugins> </uffer
เพิ่มไฟล์คลาสของคอนโทรลเลอร์ "MainController.java":
แพ็คเกจ com.github.carter659.spring02; นำเข้า org.springframework.stereotype.controller; นำเข้า org.springframwork.ui.model; นำเข้า org.springframework.web.bind.annotation. โมเดล) {model.addattribute ("ชื่อ", "Liu Dong"); กลับ "ดัชนี"; -แก้ไขไฟล์ app.java
แพ็คเกจ com.github.carter659.spring02; นำเข้า org.springframework.boot.springapplication; นำเข้า org.springframework.boot.autoconfigure.springbootapplication; @springbootaplication -
จากนั้นคลิกขวาในโครงการเพื่อเข้าสู่เส้นทางการสร้าง Java
เพิ่มโฟลเดอร์ "และโฟลเดอร์"
เพิ่มโฟลเดอร์ "ทรัพยากร" ในไดเรกทอรีหลัก
แก้ไข "ไม่รวม" ของ "ทรัพยากร":
เข้า"**"
สร้างโฟลเดอร์ "เทมเพลต" ภายใต้ SRC/Main/Resources และสร้างไฟล์ HTML ใหม่ "index.html"
<! doctype html> <html xmlns: th = "http://www.thymeleaf.org"> <head> <meta http-equiv = "content-type" text = "text/html; charset = utf-8"/> $ {name} + '!' "/> </body> </html> ป้อน http: // localhost: 8080 เพื่อตรวจสอบว่าทำงานได้สำเร็จหรือไม่:
ด้านบนเป็นหน้าแบบไดนามิกที่ทำโดยใช้เทมเพลต thymeleaf ดังนั้นวิธีการใช้ทรัพยากรคงที่ในแอปพลิเคชัน MVC
2. ทรัพยากรคงที่
สร้างโฟลเดอร์ "คงที่" ใหม่ภายใต้ SRC/Main/Resources
และคัดลอกไฟล์รูปภาพในโฟลเดอร์
แก้ไขไฟล์ "index.html" ก่อนหน้าและเพิ่มแท็ก IMG
<! doctype html> <html xmlns: th = "http://www.thymeleaf.org"> <head> <meta http-equiv = "content-type" text/html; charset = utf-8 "/> /> <p th: text = "hello, ' + $ {name} +'! '" /> </body> </html>ในเวลานี้ปรากฏการณ์ปรากฏขึ้นทันที:
เราพบว่าโปรแกรมจะโหลดโดยอัตโนมัติเพราะมันขึ้นอยู่กับ "devtools" ใน maven
ในที่สุดรีเฟรชหน้าเว็บและทดสอบว่าทรัพยากรคงที่ถูกโหลดหรือไม่
PS: Spring Boot ส่วนใหญ่ส่งเสริมเทมเพลต thymeleaf ในขณะที่ภาษาใช้ XML ซึ่งโดยส่วนตัวแล้วฉันคิดว่าไม่สะดวกมากนัก
ดาวน์โหลดรหัส: https://github.com/carter659/spring-boot-02.git
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น