[ Spring ]/Spring

[Spring] HttpServletRequest 객체

쿠릉쿠릉 쾅쾅 2022. 2. 6. 18:52
728x90

 

 

 

HttpServletRequest

  • 아이디, 비밀번호 등 데이터를 controller에 보내면 HttpServletRequest 객체 안에 데이터가 들어간다.
  • 서블릿에서 보내온 요청에 대해서 정보취득을 위해서 HttpServletRequest 객체를 사용한다.
  • 요청 URL에 대한 정보를 얻기 위해 많이 사용된다.
  • 생명 주기 : 클라이언트가 웹서버 접속 시 생성되고, 응답 메시지를 전송 후 소멸한다.

 

 

🔍 예시

http://127.0.0.1:8080/contextpath/servlcetpath/index.jsp?seq=1&type=NOTICE

 

 

✔ getRequestURL() 메서드

  • 퀴리를 제외한 프로토콜 + 도메인 + 포트번호 + 컨텍스트 경로 + 서블릿 경로를 구할 수 있다.
http://127.0.0.1:8080/contextpath/servlcetpath/index.jsp

 

 

✔ getRequestURI() 메서드

  • 요청 URL 중 포트번호와 쿼리 사이의 부분을 얻어온다.
  • 즉, 컨텍스트 경로 + 서블릿 경로를 얻어온다.
  • 일반적으로 URL과 URI는 동일한 개념으로 사용하지만 여기서는 다른 개념으로 사용된다.
/contextpath/servlcetpath/index.jsp

 

getContextPath() 메서드

  • 컨텍스트경로(context path)를 얻어온다.
/contextpath

 

 

✔ getServletPath() 메서드

  • 서블릿경로(servlet path)를 얻어옵니다.
/servlcetpath/index.jsp

 

 

getQueryString()

  • 쿼리(query)를 얻어온다.
seq=1&type=NOTICE

 

 

getServerName()

  • 도메인(domain)을 얻어온다.
127.0.0.1

 

 

getServerPort()

  • 포트(port)를 얻어온다.
8080

 

 

 

 

Model

  • HttpServletRequest 객체를 통해 데이터를 받아오고, Model 객체를 이용해서 View로 값을 넘긴다.

 

예제

@Controller
public class HomeController{

	@RequestMapping("/admin/login")
    public String login(HttpServletRequest httpServletRequest, Model model){
    	String id = httpServletRequest.getParameter("id");
        model.addAttribute("id", id);
        return "admin/login";
    }
}

 

 

🔍 @RequestParam

  • HttpServletRequest의 getParameter() 메서드 말고 @RequestParam을 이용해서 데이터를 받아올 수 있다.

 

예제

@Controller
public class HomeController{
	@RequestMapping("/admin/login")
    public String login(@RequestParam("id") String id, Model model){}
}
  • name, value : parameter 이름 (둘 중 아무거나 사용해도 된다.)
  • required : 해당 parameter가 필수인지 여부 (기본값은 true)
  • defaultValue : 해당 parameter의 기본값
  • 주의
    • required 값을 true로 해놓고 해당 parameter를 사용하지 않고 요청을 보내면 에러가 발생한다.

 

💡 annotation을 사용하지 않는 방식

@Controller
public class HomeController{
	@RequestMapping("/admin/login")
    public String login(String id){}
}
  • @RequestParam 애노테이션을 사용하지 않고도 데이터를 바로 받을 수 있다.
  • 이 경우 required가 false이고 변수명과 동일한 parameter만 받을 수 있고, defaultValue를 설정할 수 없다.

 

💡 parameter가 많은 경우 → Map 사용할 것

@Controller
public class HomeController{
	@RequestMapping("/admin/login")
    public String login(@RequestParam Map<String, String> params){
    	String data = params.get('testparam');
    }
}

 

 

 


👀 참고자료

 

 

728x90