JSP & Servlet

2020 jsp(java server page) & servlet(ServerApplicationLet) 12.기본값 사용하기

Jungsoomin :) 2020. 6. 27. 11:10

사용자가 직접 키값을 주지않아도 응답할 수 있는 방법은 없을까?

방법은 기본 값 설정에 있다.

http://~~/hello?cnt=20 에서
http://~~/hello?cnt=
http://~~/hello?
http://~~/hello

모두 가능하다. 어떻게 해석되는지 살펴보자.

http://~~/hello?cnt=20 > "20"
http://~~/hello?cnt= > ""
http://~~/hello? > null
http://~~/hello > null

사용자의 전달을 허용하려면 묵시적으로 약속된 값이 있어야한다.

int cnt = 100; 기본 값을 잡아주고

String 변수로 req.getParameter("cnt")의 값을 받고 if 문으로 조건을 걸어둔다고 보면 이렇게 된다

 

@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");

		PrintWriter out = resp.getWriter();

		String cnt_ = req.getParameter("cnt");

		int cnt = 100;

		if (cnt_ != null && !cnt_.equals("")) {
			cnt = Integer.parseInt(cnt_);
		}

		for (int i = 0; i < cnt; i++) {
			out.println((i + 1) + " : 안녕 <br>");
		}
	}

 

 

 

본적으로 100번이 동작하고 키값을 주면 해당 cnt에 맞게 출력됨을 볼 수 있다.

하지만 클라이언트가 이렇게 키값을 줄까..? 그렇지 않다.


 



a 태그에 href 값에 해당 키값을 넣어보고 html 파일을 실행해보면 클릭시 해당 키값에 맞는 value 대로 출력됨을 알 수 있다.