티스토리 뷰

이전글을 좀더 간단하게 사용하는 방법

 

스프링_post로 보내기 get으로 보내기

MyController.java @Controller public class MyController { @RequestMapping(value="getPost/index") public String getPostIndex() { return "getPost/index"; } @RequestMapping(value="getPost/result",metho..

rla5378.tistory.com

MyController.java

package com.care.getPost.ex02;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("getPost")
public class MyController {

	@RequestMapping(value="index")
	public String getPostIndex() {
		return "getPost/index";
	}
	
	@GetMapping("result")
	public String getResult(HttpServletRequest req,Model model) {
		String id = req.getParameter("id");
		String pw = req.getParameter("pw");
		model.addAttribute("id",id);
		model.addAttribute("pw",pw);
		model.addAttribute("method", req.getMethod());
		
		return "getPost/result";
	}
	@PostMapping("result")
	public String PostResult(HttpServletRequest req,Model model) {
		String id = req.getParameter("id");
		String pw = req.getParameter("pw");
		model.addAttribute("id",id);
		model.addAttribute("pw",pw);
		model.addAttribute("method", req.getMethod());
		
		return "getPost/result";
	}
}

MyController페이지 빼고 나머지의 구성은 동일합니다.

 

@Controller
@RequestMapping("getPost")
public class MyController {

	@RequestMapping(value="index")
	public String getPostIndex() {
		return "getPost/index";
	}

먼저 MyController 클래스 전체에 RequestMapping("getPost")를 해줍니다.

그렇데 되면 전에는 getPostIndex()에서 (value="getPost/index")였던것이 getPost가 mapping되면서 간단하게 (value="index")가 되었습니다.

 

@GetMapping("result")
	public String getResult(HttpServletRequest req,Model model) {}
@PostMapping("result")
	public String PostResult(HttpServletRequest req,Model model) {}

전에는 @RequestMapping 어노테이션을 사용했지만 이번에는 어노테이에서 아예 get,Post방식을 나눠주었습니다.

이전 방식은 @RequestMapping(value="getPost/result",method = RequestMethod.GET) 이렇게 방식들을 수기로 입력해줘야해서 좀더 길어졌지만

@GetMapping @PostMapping 를 사용하여 더 깔끔하게 볼 수 있게 되었습니다.

 

이렇게 get방식와 post방식을 나눠 사용하는 이유가 뭐냐 하면 방식에 따라 실행시킬 일을 나눠 시킬 수 있다는 점입니다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함