모델2 MVC 패턴으로 서블릿과 JSP를 이용하여 회원가입 기능을 만드는 중이었다.
중심이 되는 컨트롤러에게 회원리스트 출력, 회원가입 폼으로 이동 등의 기능들을 구분할 수 있도록 URI를 이용해 따로따로 배정을 해주었는데...
@WebServlet("/member/*")
public class MemberController extends HttpServlet {
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String nextPage = null;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String action = request.getPathInfo();
if (action == null || (action.equals("/listMembers.do"))) {
System.out.println(action);
List<MemberVO> membersList = memberDAO.listMembers();
request.setAttribute("membersList", membersList);
nextPage = "/test01/listMembers.jsp";
}
...
아무리 해당 링크로 접속해도 아무런 화면도 나타나지 않았다.
어디서부터 잘못된 것일까, 지난번의 경험을 되살려 거꾸로 하나씩 진행과정을 생각해보니 화면이 나타나지 않는다는 것은 첫 단계인 컨트롤러 서블릿에서부터 작동이 되지 않는 것 같아 아래와 같이 코드를 추가하여 테스트를 해보았다.
@WebServlet("/member/*")
public class MemberController extends HttpServlet {
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("컨트롤러 도착");
...
"컨트롤러 도착"이라는 문자를 넣어 서블릿으로 제대로 도착이 된 것이 확인되는지부터 체크해보았다. 그랬더니 콘솔에서 다음과 같은 출력 내용을 확인할 수 있었다.
컨트롤러 도착
null
그 얘긴 즉슨, 컨트롤러에 도착은 했지만 그 다음부터가 실행이 안된단 얘기였다. 됐다. 실마리 하나는 잡았다. 그럼, getPathInfo() 메서드를 실행하여 서블릿 다음의 URI를 action 변수에 넣도록 했음에도 action에서 아무런 값도 받지 못했다는 것은 해당 메서드가 제대로 작동이 안된다는 얘기라고 생각했다.
그래서 열심히 구글링을 해보았으나.. 스택오버플로우에서도 만족스러운 답을 얻지 못했다. 결국 공식 문서를 확인해보니,
getPathInfo
java.lang.String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.
This method returns null if there was no extra path information.
Same as the value of the CGI variable PATH_INFO.
Returns:a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
위와 같이 설명이 되어있었고, 그럼 목적에 맞는 메서드를 잘 쓴 것 같은데, 왜 null 값이 나오는지 아무리 생각해도 답이 안나왔다. '/' 기호를 빼보기도 하고, 서블릿 매핑 URI도 수정해보고 여러 방법을 시도해봤지만 속수무책이었다.
결국, 해당 메서드가 잘못된 것이라는 결론을 내리고 수업에서 배운 코드로 다음과 같이 수정해주었다.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("컨트롤러 도착");
String nextPage = null;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String uri = request.getRequestURI();
int index = uri.lastIndexOf("/");
String path=uri.substring(index);
if (path == null || (path.equals("/listMembers.do"))) {
...
스택오버플로우에서도 substring() 메서드를 사용하라는 조언이 있길래, lastIndexOf() 메서드를 통해 인덱스 값을 받아오고, 이를 substring에 다시 넣어 원하는만큼의(?) URI 값을 받아오는 방법으로 바꿔주었다.
결과는 드디어 작동. 이제 null 값 출력 없이 정상적으로 화면이 구현되었다.
험난한 약 30분 남짓의 시간이었다(...).
참고 : 도서 <자바 웹을 다루는 기술>
'TIL' 카테고리의 다른 글
<자바 Java> 컬렉션 프레임워크(Collection Framework) (1) - List (0) | 2021.11.13 |
---|---|
<자바스크립트> Ajax (0) | 2021.11.12 |
<자바 Java> JSP 요소 (0) | 2021.11.10 |
<트러블슈팅> DB 연동 시 쿼리문 오류 / html 내 js 실행안됨 (0) | 2021.11.09 |
<자바 Java> 커넥션풀(ConnectionPool) (0) | 2021.11.08 |