π
2024λ
01μ 11μΌ
41μΌμ°¨ : Spring (1)
java http ν΅μ
public class WebServer1 {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8081);
System.out.println("8081 μλΉμ€ μμ");
while (true) {
try (Socket socket = serverSocket.accept()){
String httpRes = "HTTP/1.1 200 OK \r\n\r\n" + "hello world";
socket.getOutputStream().write(httpRes.getBytes("UTF-8"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class WebServer2 {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8081);
System.out.println("8081 μλΉμ€ μμ");
while (true) {
try (Socket socket = serverSocket.accept()){
String httpRes =
"HTTP/1.1 200 OK \r\n" +
"Content-Type: text/html; charset=UTF-8\r\n\r\n" +
"<html>" +
"<body>" +
"<h1> Hello World </h1>"+
"<p> μλ
νμΈμ μ¬λ¬λΆ </p>"+
"</body>"+
"</html>"
;
socket.getOutputStream().write(httpRes.getBytes(StandardCharsets.UTF_8));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class WebServer3 {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8081);
System.out.println("8081 μλΉμ€ μμ");
while (true) {
try (Socket socket = serverSocket.accept()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()){
sb.append(line+"\n");
}
if(sb.toString().contains("POST")){
char[] buffer = new char[1024];
br.read(buffer);
System.out.println("POST body data : " + new String(buffer));
System.out.println("POST all data : " + sb);
}
String httpRes = "HTTP/1.1 200 OK \r\n\r\n" + "ok";
socket.getOutputStream().write(httpRes.getBytes("UTF-8"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Spring Http Get ν΅μ
@Controller
@RequestMapping("hello")
public class HelloController {
@GetMapping("String")
@ResponseBody
public String helloString(){
return "hello_String";
}
@GetMapping("screen")
public String helloScreen(){
return "screen";
}
@GetMapping("screen-model")
public String helloScreenModel1(Model model){
model.addAttribute("data", "νν¬μ€");
return "screen";
}
@GetMapping("screen-model-RequestParam")
@ResponseBody
public String helloScreenModel2(@RequestParam(value = "name") String inputName, Model model){
model.addAttribute("data", inputName);
return "screen";
}
@GetMapping("screen-model-PathVariable/{name}")
public String helloScreenModel3(@PathVariable String name, Model model){
model.addAttribute("data", name);
return "screen";
}
}
Spring μ€μ΅ github λ§ν¬