Java의 Dynamic Web Project 에서 쿼리스트링이 아닌 URL의 부분을 변수로 받는 방법에 대해 알아보겠습니다.
스프링의 경우에는 @PathVariable을 이용하여 해결할 수 있습니다만(링크), 이번 글에서는 스프링 프레임워크가 아닌 Dynamic Web Project에서 다루어 보도록 하겠습니다.
주소창에 board/숫자를 입력했을 때 서버가 URL에 적힌 숫자부분을 변수로 받는 코드를 작성해 보도록 하겠습니다.
package myDynamicWeb.urlpath;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyPathVariable extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("RequestURI", req.getRequestURI());
req.setAttribute("ContextPath", req.getContextPath());
req.setAttribute("ServletPath", req.getServletPath());
String num = req.getRequestURI().substring(req.getContextPath().length()+req.getServletPath().length()+1);
req.setAttribute("num", num);
req.getRequestDispatcher("/WEB-INF/views/board.jsp").forward(req, resp);
}
}
HttpServletRequest
클래스에서 getRequestURI
, getContextPath
, getServletPath
메서드를 이용하여 클라이언트가 입력한 URL이 무엇인지 알 수 있습니다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${RequestURI}<br>
${ContextPath}<br>
${ServletPath}<br>
${num}<br>
</body>
</html>
<servlet>
<servlet-name>servletboard</servlet-name>
<servlet-class>myDynamicWeb.urlpath.MyPathVariable</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletboard</servlet-name>
<url-pattern>/board/*</url-pattern>
</servlet-mapping>
<web-app>
안에 위의 코드를 입력하여 줍니다. 클라이언트가 입력한 URL이 '/board/임의값'일 때 임의값 부분이 어떤 값이든 MyPathVariable로 매핑하게 됩니다.
URL 주소창에 /board/7777를 적었을 때 서버에서 URL을 읽어 7777를 출력하는 것을 볼 수 있습니다.