Spring ile RESTful web servis yazmak (15 dk):
(Kaynak: https://spring.io/guides/gs/rest-service/)
Aşağıdaki adreste HTTP GET requestlerini kabul edecek bir web servis yazalım:
http://localhost:8080/greeting
Bu servis bir json ile response versin:
{"id":1,"content":"Hello, World!"}
Requeste isim parametresi de girilebilsin:
http://localhost:8080/greeting?name=User
Bu requeste response olarak şu verilsin:
{"id":1,"content":"Hello, User!"}
1. Bir pojo yaratıyoruz
package hello;
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. Bir resource controller yaratıyoruz:
package hello;
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;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
3. Application.java yazıyoruz:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4. Build ve run ediyoruz:
Gradle için: ./gradlew bootRun
Maven için: mvn spring-boot:run
5. Servisi test ediyoruz:
http://localhost:8080/greeting adresine gittiğimizde şunu görüyoruz:
{"id":1,"content":"Hello, World!"}
İsim parametresi verdiğimizde ise:
http://localhost:8080/greeting?name=GHopper
Şunu görüyoruz:
{"id":2,"content":"Hello, GHopper!"}
Böylece Spring ile bir RESTful web servis yazmış olduk.
Hiç yorum yok:
Yorum Gönder