request.getParameter() 메서드는 HTTP 요청의 파라미터 값을 얻기 위해 사용하는 것이다.
로그인 폼에 ID를 입력하는
<input type="text" name="id"> 가 있고,
서블릿에서 String strId = request.getParameter("id"); 와 같은 방식으로
클라이언트가 입력한 ID가 뭐였는지 알 수 있다.
로그인에 성공을 했다면, 서블릿은 회원정보를 JSP에게 보내줘야 한다.
여기서 다른 곳으로 정보를 넘겨주기 위해서 request 객체의 속성(Attribute)를 사용한다.
회원 정보 중, '휴대폰번호'를 JSP에게 넘겨주기 위해서
서블릿에서 request.setAttribute("phone",strPhone); 로 속성을 집어넣고,
JSP에서 <% String strPhone = (String)request.getAttribute("phone") %>
<% String phone = (String)request.getAttribute("phone") %> 로 속성을 얻어온다.
둘의 가장 큰 차이점은 리턴 타입이다.
getParameter() 메서드는 String 타입을 리턴하고,
getAttribute()는 Object 타입을 리턴하기 때문에 주로 빈 객체나 다른 클래스를 받아올 때 사용한다.
getParameter()는 웹 브라우저에서 전송받은 request 영역의 값을 읽어오고
getAttribute()의 경우 setAttribute() 속성을 통한 설정이 없으면 null 값을 리턴한다.
ex)
request.getParameter("num") 은 웹 브라우저에 전송 받은 request 영역에서 name 값이 "num" 인 것을 찾아 그 값을 읽어오지만,
request.getAttribute("num") 은 request.setAttribute("num","123")과 같이 setAttribute()를 통해 값을 설정하지 않으면
null 값을 리턴 받게 된다.
// test1.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>Session</title>
</head>
<body>
<form action="test2.jsp" method="post">
<input type="text" name="num" />
<input type="submit" />
</form>
</body>
</html>
// test2.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>Session</title>
</head>
<body>
<%-- num 값으로 123을 넘겨 받았을 때 --%>
<%=request.getParameter("num") %><br> <%-- 123 --%>
<%=request.getAttribute("num") %> <%-- null --%>
<hr>
<%= request.setAttribute("num","1234");
<%= request.getParameter("num") %><br> <%-- 123 --%>
<%= request.getAttribute("num") %> <%-- 1234 --%>
</body>
</html>
출처 JSP - getParameter()와 getAttribute()의 차이점 (hsprnote.blogspot.com)
'Backend > JSP SERVLET' 카테고리의 다른 글
[Servlet]MVC Pattern (0) | 2022.07.01 |
---|---|
[JSP] 쿠키, Cookie (0) | 2022.06.30 |
[JSP] 세션(Session) (0) | 2022.06.28 |
[JSP] 내장 객체(implicit object) (0) | 2022.06.28 |
[JSP] useBean, setProperty, getProperty (0) | 2022.06.27 |