SpringBoot -- 快速搭建SpringBoot项目

搭建不带JSP的项目

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

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

 <build>
   <plugins>
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <!--配置编译插件-->
          <plugin>
               <artifactId>maven-compiler-plugin</artifactId>
               <configuration>
                   <source>1.8</source>
                   <target>1.8</target>
                   <encoding>UTF-8</encoding>
               </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
    在这里插入图片描述

搭建带有JSP的项目

  1. 在上面依赖基础上加入tomcat-embed-jasper(内置tomcat时必须加入,详情看另一篇SpringBoot中使用JSP的坑)
<dependency>
   	 <groupId>org.apache.tomcat.embed</groupId>
     <artifactId>tomcat-embed-jasper</artifactId>
     <scope>provided</scope>
 </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. 访问同上面一样
    在这里插入图片描述
  4. index.jsp的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring boot 视图解析器</title>
</head>
<body>
<h1>测试视图解析器</h1>
</body>
</html>
发布了66 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Aeve_imp/article/details/100105814