ecsimsw

Servlet mapping 본문

Servlet mapping

JinHwan Kim 2020. 5. 10. 03:24

Servlet mapping

 

  brower에서 servlet을 요청할 때 서버의 servlet 절대 위치를 직접 경로로 한다면, 길이가 길어 복잡할 뿐만 아니라 보안에도 취약할 것이다.

fullPath : http://localhost:port/ContextPath/Servlet Path/SubName

mappedPath :http://localhost:port/ContextPath/SubName

  그래서 경로를 별명처럼 다른 경로로 맵핑하여 servlet의 경로로 사용한다.

 

 

0. 초기 설정

 

  프로젝트를 생성하고 WEB-content/ WEB-INFO 아래에 web.xml이 없다면 아래 사진처럼 프로젝트를 우 클릭하고 java EE Tools -> Generate Deploy Descriptor Stub을 클릭한다.

 

  web.xml은 서버 환경 설정을 위한 파일이라고 생각해두자.

  java resource / src 아래에 패키지를 생성하고, servlet 파일을 생성한다. 위 예시에서는 패키지 명이 com.ecsimsw, servlet 명은 ServletEX으로 하였다.

 

 

1. web.xml을 이용한 방식

 

  web.xml에 servlet 파일을 등록하고, 맵핑할 경로를 직접 입력한다.  

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>helloJSP</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- servlet registering -->
  <servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.ecsimsw.ServletEX</servlet-class>
  </servlet> 
  
   <!-- servlet mapping -->
  <servlet-mapping>
  <servlet-name>myServlet</servlet-name>
  <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
</web-app>

  매핑할 서블릿의 경로를 servlet-class에 적고, servlet-name으로 그 서블릿의 이름을 정한다. 

 

  아래 servlet-mapping에서, servlet-name을 지정하고 url-pattern을 정한다.

 

  경로는 servlet이 위치한 프로젝트명/url-pattern으로 정해질 것이다.

http://localhost:8090/helloJSP/hello

 

 

2. 어노테이션을 이용한 방법

 

  servlet class의 상단에 @WebServlet 어노테이션과 url-pattern을 지정하는 것으로 경로를 정할 수 있다.

@WebServlet("/hello")
public class ServletEX extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletEX() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		PrintWriter out = response.getWriter();
		out.print("<p>hello</p>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

 

3. 기본 contextPath 정하기

 

  이런 식으로 했는데도 응답이 안된다면,(404 오류가 난다면) contextPath를 확인하는 것이 좋다.

 

  또는 contextPath를 수정하는 것으로 기본 경로를 조정할 수 있다.  

  하단의 Tomcat server를 더블 클릭하고 modules를 클릭하여 모듈 적용이 되어있나 확인하자. 없다면 add를 통해 기본 경로를 직접 등록하고, 또는 기본 경로를 다르게 하고 싶다면 Edit을 눌러 경로를 변경할 수 있다.

 

 

Tip.

 

  web.xml 파일의 경로와 어노테이션으로 지정한 경로가 동일하지 않으면, 그 둘의 경로 모두에서 요청 처리가 가능하다.

 

  예를 들어, xml에서는 /hello1으로, 어노테이션으로는 /hello2로 맵핑했다면, 두 경로 모두 같은 응답을 처리하게 된다.

Caused by: java.lang.IllegalArgumentException: 이름이 [myServlet]과 
[com.ecsimsw.ServletEX]인 두 서블릿들 모두 url-pattern [/hello]에 매핑되어 있는데, 
이는 허용되지 않습니다.

  반대로, 두 방식으로 설정한 경로가 일치하면서, servlet-name이 일치하지 않으면 서로 다른 서블릿에 같은 경로를 매핑한 것으로 여겨 위와 같은 예외를 발생한다.

    

 

 

 

 

 

 

'Server application > Web, Servlet' 카테고리의 다른 글

WEB / URL 예약 문자와 인코딩  (0) 2020.05.11
Servlet / get & post  (0) 2020.05.10
Servlet 생명 주기  (0) 2020.05.10
JSP / 초기 설정  (0) 2020.05.09
Apache / Tomcat  (0) 2020.03.01
Comments