Spring Boot(1)-HelloWrold

来源:互联网 发布:Linux http代理 编辑:程序博客网 时间:2024/06/16 16:23

1.环境

  • Mac
  • IntelliJ IDEA

2.操作步骤

很简单的就写完了,代码才几行。

2.1工程配置

1)使用IntelliJ的Spring 初始化配置,快速建立工程:
这里写图片描述

2)设置工程名:
这里写图片描述

3)选择web模块:
这里写图片描述

4)建立好后的工程:
这里写图片描述

2.2编写代码

在Application中写代码,就不单独建立Controller了:

package com.example;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }    @RequestMapping("/")    String index() {        return "Hello World";    }}

2.3 运行

运行工程,在浏览器中输入:localhost:8080, 就可以看到Hello World了。
这里写图片描述
五行代码搞定HelloWrold.

3.知识点

3.1问题

@Controller和@RestController的区别?

3.2解答

@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

  1. 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

    例如:本来应该到success.jsp页面的,则其显示success.

  2. 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。

  3. 如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

0 0
原创粉丝点击