STS: Spring Boot and Spring MVC

  第一次使用 Spring Tool Suite,感觉很好用,但是想使用 Spring Starter Project 创建一个 Spring MVC 项目,却不知道怎么做。费了好大劲儿,终于搞明白了,特此记录一下。
  注:Spring Tool Suite Version: 3.7.2.RELEASE

创建新的 Spring Starter Project。

  点击菜单 File -> New -> Spring Starter Project,打开 New Spring Starter Project 对话框。

这里写图片描述

  将 Name 改为 hellomvc。

这里写图片描述

  点击〖Next >〗按钮,进入下一个对话框。展开 Template Engines,选中 Thymeleaf。

这里写图片描述

  注:由于 Spring 官方不推荐使用 jsp,所以模板引擎选择了“Thymeleaf”。参见:Spring MVC Template Engines

  然后点击〖Finish〗按钮,创建 hellomvc 项目。

  STS 生成的 hellomvc 项目结构如下图所示:

这里写图片描述

创建 HomeController

  在项目名称 hellomvc 上点击鼠标右键,在弹出菜单上选择 New -> Class,打开 New Java Class 对话框,在 Name: 中输入 HomeController,然后点击〖Finish〗创建 Controller。

这里写图片描述
  
  打开刚刚创建的 HomeController.java 文件,编辑代码如下所示:

package com.example;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class HomeController {
    @RequestMapping("/")
    public String index(Locale locale, Model model) {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );
        return "index";
    }
}

创建模板

  在 src/main/resources 下面的 templates 文件夹上点击鼠标右键,在弹出菜单上选择 New -> Other…,打开 New 对话框,展开 Web 节点,选中 HTML File,然后点击〖Next >〗按钮,进入 New HTML File 对话框。

这里写图片描述

  将 File name: 改为 index.html,然后点击〖Finish〗按钮,创建 index.html 文件。

这里写图片描述

  打开刚刚创建的 index.html 文件,编辑代码如下所示:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot and Spring MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h3>Spring Boot and Spring MVC</h3>

    <P th:text="'The time on the server is ' + ${serverTime}"></P>

</body>
</html>

运行 Application

  在项目名称 hellomvc 上点击鼠标右键,在弹出菜单上选择 Run As -> Spring Boot App。
  如果在 Console 窗口里出现 Started HellomvcApplication in 2.314 seconds 这样的字样,表示 Application 已经正常运行,这时打开浏览器,在地址栏中输入 http://localhost:8080 即可查看 hellomvc 的运行结果。
  如果 Console 窗口里出现了 Failed to start connector [Connector[HTTP/1.1-8080]] 的字样,说明你的计算机的 8080 端口已被占用,需要更换一个没被占用的端口才能启动。
  注:STS embedded Tomcat 的默认端口是 8080,可以在 application.properties 里更改。
  打开 src/main/resources 下面的 application.properties 文件,编辑文件内容如下所示:

server.port=8081

  然后重新运行 Application,即可正常启动了。打开浏览器,在地址栏中输入 http://localhost:8081 查看运行结果。


参考:Spring Boot with Thymeleaf tutorial

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值