功能:每请求1次,id值+1
简单程序:只用model,后controller直接返回结果
在src/main/java的com.example.demo包内创建com.example.demo.model包,此包内创建Test.java:
package com.example.demo.model;
public class Test {
private final long id;
private final String content;
public Test(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
实现controller:在src/main/java的com.example.demo包内创建com.example.demo.controller包,此包内创建TestController.java:此包内创建TestController.java:
(该内容是对test和test1两个请求响应,test和test1两个请求的返回结果是一样的,写两个是为强调一个Controller文件就可以处理多个请求,不用每个请求都建一个Controller)
package com.example.demo.controller;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Test;
@RestController
public class TestController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/test")
public Test dealTest(@RequestParam(value="name", defaultValue="World") String name) {
return new Test(counter.incrementAndGet(),
String.format(template, name));
} @RequestMapping("/test1")
public Test dealTest1(@RequestParam(value="name", defaultValue="World") String name) {
return new Test(counter.incrementAndGet(),
String.format(template, name));
}
}
选择项目----右键----Run As----点击Spring Boot App
通过浏览器访问http://localhost:8080/test,得输出结果,也可是test2