新聞中心
經(jīng)典MVC模式中,M是指業(yè)務(wù)模型,V是指用戶界面,C則是控制器,使用MVC的目的是將M和V的實(shí)現(xiàn)代碼分離,從而使同一個(gè)程序可以使用不同的表現(xiàn)形式。其中,View的定義比較清晰,就是用戶界面,下面為大家分享一下SpringBoot中的mvc具體使用方法。

關(guān)于SpringBoot中的mvc
在SpringBoot中使用mvc與springmvc基本一致,我們甚至可以按照springmvc中的標(biāo)準(zhǔn)來完成控制器的實(shí)現(xiàn)。
package com.bdqn.lyrk.study.springboot.controller;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author chen.nie
*/
@Controller
@RequestMapping("/index")
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
@GetMapping("/number/{number}/Desc/{desc}")
@ResponseBody
public BeanEntity bean(@PathVariable ("number") int number, @PathVariable("desc") String desc) {
return new BeanEntity(number,desc);
}
}
@Data
@AllArgsConstructor
class BeanEntity {
private int number;
private String desc;
}
當(dāng)我們訪問瀏覽器地址時(shí)得到對應(yīng)的結(jié)果:
我們可以發(fā)現(xiàn)這里跟springmvc中controller寫法無二,其余的service層和dao層也均是按常規(guī)寫法,用@Service和@Repository標(biāo)記service與dao即可。
關(guān)于SpringBoot中mvc(靜態(tài)資源-視圖)
默認(rèn)情況下,Spring Boot將從類路徑或ServletContext的根目錄中的名為/static(或/ public或/resources或/META-INF/resources)的目錄提供靜態(tài)內(nèi)容。
在靜態(tài)內(nèi)容當(dāng)中我們可以放js,css樣式等文件,除Web服務(wù),我們還可以使用Spring MVC來提供動(dòng)態(tài)HTML內(nèi)容。Spring MVC支持各種模板技術(shù),包括Thymeleaf,F(xiàn)reeMarker和JSP。當(dāng)然SpringBoot不推薦用JSP來作為視圖層,通常情況我們把模板放在src/main/resources/templates下。
以下目錄就是典型的模板與靜態(tài)資源目錄結(jié)構(gòu),按照上述規(guī)則我們把靜態(tài)資源js文件放在static目錄下,模板文件(這里使用的是Freemarker)放在規(guī)定的目錄下:
SpringBoot學(xué)習(xí)之mvcSpringBoot學(xué)習(xí)之mvc
springBoot添加對jsp的支持
原則上來說,SpringBoot不推薦使用Jsp做為視圖層,如果想用Jsp,我們需要包含以下的依賴:
org.springframework.boot
spring-boot-starter-tomcat
provided
org.apache.tomcat
tomcat-jasper
8.5.28
在application.properties做相關(guān)視圖的配置:
spring.mvc.view.suffix=/WEB-INF/jsp/
spring.mvc.view.prefix=.jsp
當(dāng)前文章:SpringBoot中的mvc具體使用方法
分享路徑:http://www.dlmjj.cn/article/cdhhidj.html


咨詢
建站咨詢
