[SpringBoot2.4.3] RestControllerを利用する

RestControllerはビューを使わずコントローラーだけでアプリの基本部分を作成できる

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
	
	@RequestMapping("/")
	public String index() {
		return "Hello Spring-Boot World!";
	}
}

http://localhost:8080/
Hello Spring-Boot World!

### パラメータを渡す

package com.example.demo;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
	
	@RequestMapping("/{num}")
	public String index(@PathVariable int num) {
		int res = 0;
		for(int i = 1; i <= num; i++)
			res += i;
		return "total: " + res;
	}
}

http://localhost:8080/5
total: 15

おおお、一周回って基礎やると理解しやすいな。

### DataObject

package com.example.demo;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
	
	String[] names = {"hpscript","hanako","taro","sachiko","ichiro"};
	String[] mails = {"info@hpscript.com", "hanako@gmail.com", "taro@gmail.com","sachiko@gmail.com","ichiro@gmail.com"};
	
	@RequestMapping("/{id}")
	public DataObject index(@PathVariable int id) {
		return new DataObject(id, names[id],mails[id]);
	}
	
}
class DataObject{
	
	private int id;
	private String name;
	private String value;
	
	public DataObject(int id, String name, String value) {
		super();
		this.id = id;
		this.name = name;
		this.value = value;
	}
	
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	
	public String getValue() {return value;}
	public void setValue(String value) {this.value = value;}
}

http://localhost:8080/2
{“id”:2,”name”:”taro”,”value”:”taro@gmail.com”}
http://localhost:8080/0
{“id”:0,”name”:”hpscript”,”value”:”info@hpscript.com”}

おおお、なんか変に感傷的になるな〜