springboot+thymeleaf hellworld搭建

本文介绍了如何使用SpringBoot 1.5.2和Thymeleaf 3.0.2搭建项目,包括创建Maven项目、配置文件修改、templates目录建立以及Controller的创建,详细解释了每个步骤的关键点,如避免使用@RestController和@ResponseBody导致的页面无法跳转问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境说明

1、springboot 1.5.2
2、thymeleaf 3.0.2
3、idea 2017.3.5

搭建步骤

1、创建maven项目

并添加依赖:

<parent>
        <artifactId>agentservices</artifactId>
        <groupId>com.nmm.apm</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>webview</artifactId>
    <properties>
        <thymeleaf.version> 3.0.2.RELEASE </thymeleaf.version>
        <thymeleaf-layout-dialect.version> 2.1.1 </thymeleaf-layout-dialect.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

说明:spring-boot-starter-thymeleaf已经包含了spring-boot-starter-web,因此我们就不需要自己引入了。
properteis:指定了thymeleaf的版本,覆盖了springboot中默认的版本。

2、修改配置文件

在resources目录下创建application.yml,增加如下配置:

spring:
  application:
    name: webview
  thymeleaf:
    mode: HTML
    encoding: UTF-8
    contentType: text/html
    cache: false

主要的是cache,指定其不缓存,便于实时刷新,其他用默认配置就好。
thymeleaf的默认模板位置在templates,我们也可以在配置文件中指定前缀。除非存在框架冲突,一般不做修改。

3、创建templates目录

新建index/index.html页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <form action="/login" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="登录"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

其中。http://wwww.thymeleaf.org指定了thymeleaf的名称空间。这里我们并没有使用thymeleaf的东西,只是做一些基本环境搭建。

4、创建controller,并跳转:

@RequestMapping("/")
    public String index(Model model) {
        return "index/index";
    }

注意,这里controller使用@controller注解,不要使用@RestController,也不用在方法注解中添加@ResponseBody。加了这两种注解中的任一一种都会将结果作为字符串输出,而不是跳转。
到这一步,就完成了,然后,我们创建入口类,启动服务访问
http://localhost:9000即可看到登录页面。

问题说明

有可能不能跳转页面,常见原因有:
1、模板文件目录不正确
2、使用了@RestController注解,或者@ResponseBody
3、pom文件中没有设置properties,指定thymeleaf版本。

代码地址

https://github.com/niemingming/agentservice

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值