springboot之路径映射

版本springboot2.1.6.RELEASE

1、pom依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.6.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>cn.linstgroupId>
    <artifactId>pathmappingartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>pathmappingname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

2、templates目录下创建一个hello.html
springboot之路径映射_第1张图片


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>hello spring boot!h1>
body>
html>

3、创建一个WebMvcConfig
有时候就想展示一个动态页面,但是没有数据交互。
1)一种方法是,建立一个控制器,返回视图。
如:

package cn.linst.pathmapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;


@Controller
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

启动访问:

http://localhost:8080/hellospringboot

springboot之路径映射_第2张图片

2)这里介绍另一种,实现WebMvcConfigurer接口,如:

package cn.linst.pathmapping;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hellospringboot").setViewName("hello");
    }
}

访问:

http://localhost:8080/hellospringboot

结果:
springboot之路径映射_第3张图片

你可能感兴趣的:(Spring,Boot,spring,boot)