导读 Spring Boot非常适合Web应用程序开发。 我们可以使用嵌入式Tomcat,Jetty或Undertow轻松创建自包含的HTTP服务器。 大多数Web应用程序将使用spring-boot-starter-web模块快速启动和运行。

关于SpringBoot中的mvc

在SpringBoot中使用mvc与springmvc基本一致,我们甚至可以按照springmvc中的标准来完成控制器的实现。

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;
}

当我们访问浏览器地址时得到对应的结果:

我们可以发现这里跟springmvc中controller写法无二,其余的service层和dao层也均是按常规写法,用@Service和@Repository标记service与dao即可。

关于SpringBoot中mvc(静态资源-视图)

默认情况下,Spring Boot将从类路径或ServletContext的根目录中的名为/static(或/ public或/resources或/META-INF/resources)的目录提供静态内容。

在静态内容当中我们可以放js,css样式等文件,除Web服务,我们还可以使用Spring MVC来提供动态HTML内容。Spring MVC支持各种模板技术,包括Thymeleaf,FreeMarker和JSP。当然SpringBoot不推荐用JSP来作为视图层,通常情况我们把模板放在src/main/resources/templates下。

以下目录就是典型的模板与静态资源目录结构,按照上述规则我们把静态资源js文件放在static目录下,模板文件(这里使用的是Freemarker)放在规定的目录下:

springBoot添加对jsp的支持

原则上来说,SpringBoot不推荐使用Jsp做为视图层,如果想用Jsp,我们需要包含以下的依赖:

     <dependency>
                     <groupId>org.springframework.boot</groupId>
                     <artifactId>spring-boot-starter-tomcat</artifactId>
                     <scope>provided</scope>
              </dependency>
        <dependency>
          <groupId>org.apache.tomcat</groupId>
             <artifactId>tomcat-jasper</artifactId>
            <version>8.5.28</version>
    </dependency>     
 

在application.properties做相关视图的配置:

spring.mvc.view.suffix=/WEB-INF/jsp/
spring.mvc.view.prefix=.jsp

原文来自:https://www.cnblogs.com/niechen/p/7765056.html

本文地址:https://www.linuxprobe.com/mvc-springboot-learning.html编辑:薛鹏旭,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/