패스트캠퍼스 데브캠프 : 남궁성의 백엔드 개발 3기

Spring MVC | @GetMapping, @PostMapping, URL인코딩

Tech_JINI 2025. 3. 4. 18:04

@GetMapping, @PostMapping 

//@RequestMapping(value = "/register/add", method = {RequestMethod.GET, RequestMethod.POST})
//@RequestMapping("/register/add") //신규회원 가입화면
@GetMapping("/register/add")
public String Register(){
    return "registerForm"; //WEB-INF/views/registerForm.jsp
}

 

RequestMapping을 간단하게 쓸 수 있도록하는게 GetMapping과 PostMapping이다. 

 

   @GetMapping("/register/add")
   public String Register(){
       return "registerForm"; //WEB-INF/views/registerForm.jsp
   }

url 연결 기능만 있고 메소드가 실제로 하는 일이 없다. 

>> 위의 코드를 주석처리하고 servlet-context.xml에서 view controller로 바꾼다.

<view-controller path="/register/add" view-name="registerForm" />

view controller는 get요청만 허용한다. 

 

 

페이지를 호출했을 때 잘 나온다. (GET 요청이 성공적으로 수행되었다.)

POSTMAN을 통해서 한번 더 확인해보자.

 

해당 URL을 넣고 GET형식으로 설정한뒤 send를 눌렀을 때, 상태코드가 200번으로 응답되었다.

200번은 요청이 성공적으로 완료되었다는 의미이다.

 

 

POST 요청으로도 시도해보자.

상태 코드가 405번이 나왔다. 

상태코드 위에 마우스를 놓아보니 POST는 허용되지 않은 메소드라고 나오는 것을 확인할 수 있었다.

>> view controller 등록한 것이 get 요청만 허용하기 때문

 

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

servlet-context.xml 내에 있는 beans 태그에서 xml name 스페이스들이 4개가 있다.

이것들은 각 스키마에서 정의한 태그들을 사용하기 위해 적어두는 것이다.

 

@Controller
@RequestMapping("/register")
public class RegisterController {

    //@RequestMapping(value = "/register/add", method = {RequestMethod.GET, RequestMethod.POST})
    //@RequestMapping("/register/add") //신규회원 가입화면
//    @GetMapping("/register/add")
//    public String Register(){
//        return "registerForm"; //WEB-INF/views/registerForm.jsp
//    } >> url 연결 기능만 있고 메소드가 실제로 하는 일이 없다. >> servlet-context.xml에서 view controller로 바꾼다.

    //@RequestMapping(value = "/register/save", method = RequestMethod.POST) //post 방식으로만 회원가입 가능하게 하기
    @PostMapping("/register/save") //spring 4.3부터
    public String save(User user, Model model) throws Exception {
        // 1. 유효성 검사
        if(!isValid(user)){
            String msg ="id를 잘못 입력하셨습니다.";
            String encodedMsg = URLEncoder.encode(msg, "UTF-8");
//            return "redirect:/register/add?msg=" + encodedMsg;
            //GET방식으로 메세지를 url에 붙임 >> url재작성 (rewriting)

            model.addAttribute("msg", encodedMsg); //model에 담아서 보냄
            return "redirect:/register/add";
        }
        // 2. DB에 신규회원 정보를 저장
        return "registerInfo";
    }

맵핑될 URL의 공통 부분을 @RequestMapping으로 클래스에 적용할 수 있다.

클래스 앞에 RequestMapping이 붙으면 메서드에 붙은 Mapping과 합쳐진다.

 

이 클래스 안에 모든 메서드 앞에 '/register'이 붙게 된다. 

 

servlet과 달리 스프링에서는 맵핑을 메서드 단위로 만들어서 클래스를 많이 만들지 않아도 된다.

(servlet은 맵핑을 클래스 단위로 한다.)

>> 하나의 클래스에 모든 메서드를 넣을 순 없기 때문에 메서드를 모듈별로 나눠서 하나의 클래스에 넣어놓는다. 

 

(예시) 위의 코드는 회원 가입과 관련된 것으로 회원가입을 처리하는 register 컨트롤러에 넣어놓는다.

모듈 경로를 RequestMapping으로 잡고, 나머지에서는 Get/PostMappinf으로 그 이후 경로만 적는다. 

 

 

RequestMapping URL패턴

Spring에선 RequestMapping으로 URL패턴을 쓸 수 있다.  (?는 한 글자, *는 여러 글자, **은 하위 경로 포함)

>> Servlet에서는 @WebServlet으로 url패턴을 사용

- exact mapping

- oath mapping

- extenstion mapping

@Controller
public class RequestMappingTest {
    //  @RequestMapping({"/login/hello.do", "/login/hi.do"})
    @RequestMapping("/login/hello.do") // http://localhost/ch2/login/hello.do
    public void test1(){
        System.out.println("urlpattern=/login/hello.do");
    }

    @RequestMapping("/login/*")   // /login/hello, /login/hi
    public void test2(){
        System.out.println("urlpattern=/login/*");
    }

    @RequestMapping("/login/**/tmp/*.do")   // /login/tmp/hello.do, /login/aaa/tmp/hello.do
    public void test3(){
        System.out.println("urlpattern=/login/**/tmp/*.do");
    }

    @RequestMapping("/login/??")
    public void test4(){   // /login/hi, /login/my.car
        System.out.println("urlpattern=/login/??");
    }

    @RequestMapping("*.do") // /hello.do, /hi.do, /login/hi.do
    public void test5(){
        System.out.println("urlpattern=*.do");
    }

    @RequestMapping("/*.???") //  /hello.aaa, /abc.txt
    public void test6(){
        System.out.println("urlpattern=*.???");
    }
}

 

 

URL인코딩 - 퍼센트 인코딩

: URL에 포함된 non-ASCII문자를 문자 코드(16진수) 문자열로 변환

URL 인코딩 :  문자 코드(숫자) -> 문자열

 

 

[ URL 인코딩이 필요한 이유 ]

요청을 받는 서버가 어떤 OS를 쓰고 어떤 인코딩을 사용하는지 모른다.

 

인터넷은 모든 서버와 통신할 수 있는데,

해당 서버가 우리 같은 인코딩이나 한글OS를 사용한다는 보장이 없기 때문에

url 요청할 때 쓰는 문자는 모두 ASCII여야 한다. 

 

ASCII는 모든 인코딩에서 공통으로 들어가서 상대방이 인코딩 때문에 못받을 일이 없다.