상세 컨텐츠

본문 제목

서블릿 컨트롤러, 커맨드 패턴, URI 사용

JSP

by kwanghyup 2020. 7. 6. 15:08

본문

 

request.getRequestURI() , request.getContextPath() 예제   

package servletExam;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/uriExample/*")
public class URIExample extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        proceedRequest(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        proceedRequest(req,resp);
    }

    private void proceedRequest(HttpServletRequest request, HttpServletResponse response) {
        String command = request.getRequestURI(); // /myapplication/uriExample/*
        String contextPath = request.getContextPath(); // /myapplication
        System.out.println("contextPath = " + contextPath);
        System.out.println("command = " + command);

        if(command.indexOf(request.getContextPath())==0){
            command = command.substring(request.getContextPath().length());
        }
        System.out.println("command.substring = " + command);
    }
}

 

http://localhost:8080/myapplication/uriExample/boardWrite1234 요청한다면 

request.getRequestURI() :  /myapplication/uriExample/boardWrite1234 

request.getContextPath : /myapplication

command =  command.substring(request.getContextPath().length()) : /uriExample/boardWrite1234 

 

관련글 더보기

댓글 영역