웹개발 교육/jsp

[48일] jsp (12) - request 내부 객체의 다양한 메소드

ewok 2022. 10. 5. 17:47

09_request.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>09_request내부객체.jsp</title>
</head>
<body>

	<h3>* request 내부 객체의 다양한 메소드 *</h3>
	<form action="09_ok.jsp">
		아이디:<input type="text" name="uid">
		<br>
		<input type="submit" value="request내부객체">	
	</form>
	
</body>
</html>

 

09_ok.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>09_ok.jsp</title>
</head>
<body>
	<h3>* request 내부객체의 다양한 메소드 결과 *</h3>
<%
	//1)한글 인코딩
	request.setCharacterEncoding("UTF-8");
	
	//2)사용자가 입력한 정보를 가져오기
	out.print(request.getParameter("uid"));
	out.print("<hr>");
	
	//3)요청한 사용자의 다양한 정보
	out.print(request.getRemoteAddr()); //사용자pc의 ip주소
	out.print("<hr>");
	out.print(request.getRemoteHost());
	out.print("<hr>");
	out.print(request.getRemotePort());
	out.print("<hr>");
	/////////////////////////////////////////////////////////
	
	// /basic04_web 해당 프로젝트 이름
	out.print(request.getContextPath());
	out.print("<hr>");
	
	// 사용자가 요청한 전체 경로의 페이지명 또는 명령어
	// http://localhost:9090/basic04_web/form/09_ok.jsp
	out.print(request.getRequestURL());
	out.print("<hr>");
	
	// 사용자가 요청한 페이지명 또는 명령어
	// /basic04_web/form/09_ok.jsp
	out.print(request.getRequestURI());
	out.print("<hr>");
	///////////////////////////////////////////////////////
	
	// 내컴퓨터 입장에서 /images 폴더의 실제 물리적 경로
	out.print(request.getRealPath("/images"));  //비추천
	out.print("<hr>");
	
	out.print(application.getRealPath("/images"));  //추천
	out.print("<hr>");
	
	 /* 
		아래 경로는 이클립스에서 톰캣서버를 실행한 경우
		I:\java202207\workspace
				     \.metadata
		             \.plugins
	                 \org.eclipse.wst.server.core
		             \tmp0
		             \wtpwebapps
		             \basic04_web
		             \images
	 */
	 //////////////////////////////////////////////////////

	 //내부변수
	 //request.setAttribute("변수명", 값);
	 //request.getAttribute("변수명");
	 request.setAttribute("user", "KOREA");
	 Object obj = request.getAttribute("user");
	 String str = (String)obj;  //다형성
	 out.print(str);
	 
	 
%>
</body>
</html>

처음 getRemoteAddr()을 통해 ip주소를 가져오면 IPv6로 되어있을 것이다. 이를 IPv4로 바꾸어 보고 싶으면 다음과 같이 설정하면 된다.

톰캣 IPv4 지정
IP주소 6자리 -> 4자리 변경
Run -> Run Configurations -> Tomcat Server -> (x)=Arguments -> VM arguemnts에 아래와 같이 추가    -> 공백 1칸 주고 -Djava.net.preferIPv4Stack=true    -> Apply

 

 

 

 

프로젝트 이름은 개발할 때 필요하고 배포할 때는 보통 도메인 이름으로 변경해준다. 그래서 getContextPath()와 같은 메서드를 사용한다.