SpringBoot -- 快速搭建SpringBoot项目

搭建不带JSP的项目

  1. POM中引入parent和web依赖
<parent>
 	<groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.0.5.RELEASEversion>
parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
dependencies>

 <build>
   <plugins>
         <plugin>
             <groupId>org.springframework.bootgroupId>
             <artifactId>spring-boot-maven-pluginartifactId>
         plugin>
         
          <plugin>
               <artifactId>maven-compiler-pluginartifactId>
               <configuration>
                   <source>1.8source>
                   <target>1.8target>
                   <encoding>UTF-8encoding>
               configuration>
           plugin>
     plugins>
 build>
  1. 在resource文件夹中创建application.yml(或者properties)文件,加入配置server.port=8090
  2. 编写启动类
@SpringBootApplication
public class Chapter1Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter1Application.class);
    }
}
  1. 编写Controller
@RestController
public class IndexController {

    @RequestMapping("/index")
    public Object index() {
        return "success";
    }
}
  1. 搞定,访问http://localhost:8090/index
    SpringBoot -- 快速搭建SpringBoot项目_第1张图片

搭建带有JSP的项目

  1. 在上面依赖基础上加入tomcat-embed-jasper(内置tomcat时必须加入,详情看另一篇SpringBoot中使用JSP的坑)
<dependency>
   	 <groupId>org.apache.tomcat.embedgroupId>
     <artifactId>tomcat-embed-jasperartifactId>
     <scope>providedscope>
 dependency>
  1. 在resource文件夹中创建application.yml(或者properties)文件,除了加入配置server.port=8090外,还需要加入springmvc视图解析的前、后缀配置:
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
  1. 编写启动类和上面一致
  2. 编写Controller时注意注解不能用RestController,因为默认会把String当做Json进行转换,而得不到jsp的后缀,导致不会让JspServlet进行解析,所以用Controller注解就可以了
  3. 访问同上面一样
    SpringBoot -- 快速搭建SpringBoot项目_第2张图片
  4. index.jsp的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring boot 视图解析器title>
head>
<body>
<h1>测试视图解析器h1>
body>
html>

你可能感兴趣的:(SpringBoot)