Spring Boot快速上手2-创建一个简单的web应用

2019-10-15  本文已影响0人  咪啊p

@SpringBootApplication

上篇文章讲到DemoApplication类,里面你会发现有各main方法,这就是为什么我们能运行这个项目用run as java application 方式。 另外如果再看main方法里面只有一行代码 SpringApplication.run, 这段代码实际上就是运行Spring application context,当你运行Spring的时候,第一件事情就是告诉Spring哪里能找到配置文件,实际上我们这里就是DemoApplication类,所以这个类不仅是个boot class,而且还带有额外的必须配置信息。如果你想了解更多这个方面的信息,到Spring framework reference页面,找到章节“composing Java-based configurations”,里面会有详细说明。

这个类有个annotation @SpringBootApplication, 大概介绍下这个annotation的作用,基本上这个是几个annotation的集合:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

创建一个web application

Maven依赖

首先要确认maven里面已经加入对spring-boot-starter-web的依赖,这个我们在上篇文章里面已经做过了。

创建Controller

然后我们需要创建一个controller,比如名字叫做DemoController


create controller

然后我们加一个简单的hello的方法,见如下代码:
第一,这个地方类上需要加上@Controller,声明这是一个Controller
第二,方法上我们要加上@RequestMapping, 指定请求的地址,我这个地方指定的是"/hello", 你可以随意指定你需要的地址
第三,返回的地方我们需要加上@ResponseBody,用来告诉SpringMVC,这个请求要返回一个String

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DemoController {

    @RequestMapping("/hello")
    public @ResponseBody String hello() {
        return "Hello World!";
    }
}

ok,一切就绪,我们可以再次运行这个项目,当你在IDE的console上看到Spring启动完成后,你就可以到浏览器上访问你的项目看看效果,敲入http://localhost:8080/hello,浏览器上会出现如下结果

image.png

总结

这样一个简单的web application就创建了。让我们总结下:

接下来,我们会看看如何发布一个war包

上一篇 下一篇

猜你喜欢

热点阅读