admin管理员组文章数量:1794759
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="www.thymeleaf"> <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 已经正常运行,这时打开浏览器,在地址栏中输入 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,即可正常启动了。打开浏览器,在地址栏中输入 localhost:8081 查看运行结果。
参考:Spring Boot with Thymeleaf tutorial
版权声明:本文标题:STS: Spring Boot and Spring MVC 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686614589a86371.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论