1.通过spring在线创建一个maven工程
地址:https://start.spring.io/
2.编写Controller
2.1GreetingController.java
package com.syh;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(
@RequestParam(value="name", required=false, defaultValue="World") String name) {
System.out.println("greeting");
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
2.2编写POJO类
Greeting .java
package com.syh;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
2.3最终工程结构
3.运行
工程项目右键->RunAs->Spring Boot App
如遇到提示 “找不到或无法加载主类 com.syh.MavenGenarate2Application”
则在项目跟目录下运行已下命令:
mvn compile
mvn package
mvn install
4.测试
http://localhost:8080/greeting?name=world
输出:
{
id: 3,
content: "Hello, world!"
}