第四章 第一个Web页面

上一章运行入口类后,只是在IDE里打印出Hello world。这一章我们要实现在浏览器的页面输出Hello world.

修改入口类

再次打开入口类lightsword.java,

  1. 新增一个方法hello

@RequestMapping("/hello") public String hello(){ return "Hello world"; }

  1. 在类上新增@RestController注解

lightsword.java完整代码如下:

package lightsword;

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;

@SpringBootApplication @RestController public class lightsword { public static void main(String[] args){ SpringApplication.run(lightsword.class, args); }

@RequestMapping("/hello")
public String hello(){
    return "Hello world";
}

}

结果

再次运行,然后打开浏览器,访问http://127.0.0.1:9527/hello (如果没有配置9527端口的,参考上一章内容配置),结果在Web页面输出Hello world

讲解

本例中多了两个注解:

  1. @RequestMapping 它起一个地址路由的作用,例子中配置的值为"/hello",我们访问的地址就是主机(127.0.0.1:9527)加上(/hello),构成:http:127.0.0.1:9527/hello。 不难看出@RequestMapping对应的是我们的uri。

  2. @RestController 要想通用访问http:127.0.0.1:9527/hello,就可以请求我们的hello方法,就必须使用@RestController注解。它的作用就是将方法结果直接返回给调用者。

results matching ""

    No results matching ""