[ Servlet Mapping ]
- Servlet 문서는 자바로 된 웹 프로그래밍 문서로서 MVC 패턴에서 Controller를 담당한다.
이때, 특정 URL로 요청시 해당 Servlet 문서가 동작할 수 있도록 Mapping(맵핑) 작업을 해주어야 하는데 이와 같은 작업에는
두가지 방식이 있다.
- [ Mapping 방식 ]
1. web.xml 에서 맵핑 설정하기
2. Annotation(어노테이션)을 이용하기
먼저, web.xml에서 맵핑을 설정할 경우
해당 Servlet 문서를 생성한 뒤, web.xml에 들어가서
다음과 같이 설정한다.
아래는 Helloworld라는 Servlet class 파일에 대한 맵핑을 설정한 것이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?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" id= "WebApp_ID" version= "3.1" > <display-name>ex</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> <servlet-name>hellWorldServlet</servlet-name> <!-- 이름 지정 --> <servlet- class >com.java.ex.Helloworld</servlet- class > <!-- Servlet class 지정 --> </servlet> <servlet-mapping> <servlet-name>hellWorldServlet</servlet-name> <url-pattern>/hw</url-pattern> <!-- http: //localhost:80/ex/hw 로 맵핑된다. -> 컨텍스트패스/hw --> </servlet-mapping> </web-app> |
두번째로 어노테이션을 이용한 맵핑 방식이다.
@WebServlet 의 괄호 안에 맵핑할 URI 패턴을 적어준다.
현재 프로젝트의 컨텍스트 패스가 /ex임으로 http://localhost:80/ex/hw 로 해당 Servlet 문서가 맵핑된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.java.ex; 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; @WebServlet ( "/hw" ) // 두번째, 어노테이션을 이용한 Servlet 맵핑 방법 public class Helloworld extends HttpServlet { private static final long serialVersionUID = 1L; public Helloworld() { super (); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append( "Served at: " ).append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } |
'스터디 > JSP' 카테고리의 다른 글
[ servlet 초기화 파라미터, 컨텍스트 파라미터, 서블릿 컨텍스트 리스너] (0) | 2017.08.08 |
---|---|
5. Servlet에서의 HTML Form태그, servlet Parameter, 한글처리 (0) | 2017.08.08 |
4. servlet의 라이프사이클(lifecycle) (0) | 2017.08.08 |
3. servlet의 doGet(), doPost()와 PrintWriter 객체 (0) | 2017.08.08 |
1. [ JSP 웹 기본 지식 및 작동 원리 ] (0) | 2017.08.06 |