Microsoft MVP성태의 닷넷 이야기
Java: 1. 닷넷 개발자가 처음 실습해 본 서블릿 [링크 복사], [링크+제목 복사],
조회: 30229
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)

닷넷 개발자가 처음 실습해 본 서블릿

서블릿 테스트를 하려면 개발환경을 구축해야 겠지요. ^^ 아래의 항목들을 다운로드 해서 설치하고,

JDK (제 경우에는 JDK 6 설치)
; http://www.oracle.com/technetwork/java/javase/downloads/index.html

Eclipse IDE for Java Developers
; http://www.eclipse.org/downloads

아파치 톰캣
; http://tomcat.apache.org/
; https://www.sysnet.pe.kr/2/0/798

준비가 되었으면, Eclipse를 실행해서 예제 프로젝트를 생성한 후, HelloWorld.java 파일을 하나 추가해야 겠지요. ^^

그런데, import 구문 코드 작성하는 단계부터 다음과 같이 오류가 발생할텐데요.

how_to_test_servlet_1.png
"
The import javax.servlet cannot be resolved
"


해답은 다음의 글에 나오더군요.

[java]import javax.servlet.jsp.* can not be resolved 
; http://arima603.tistory.com/entry/javaimport-javaxservletjsp-can-not-be-resolved

즉, 기본적으로 서블릿 관련한 jar 파일이 JDK에 제공되지 않아서 그런 것인데, 이 파일들은 서블릿을 구동할 수 있는 웹 서버 측에서 보통 함께 제공되는 것 같습니다. 이 때문에 Tomcat의 압축을 해제한 '[설치폴더]\lib'에 있는 servlet-api.jar, jsp-api.jar 2개의 파일을 이클립스에 알려줘야 합니다.

이를 위해, 프로젝트 폴더를 오른쪽 버튼을 눌러 "Build Path" / "Configure Build Path..." 메뉴를 선택해서 톰캣에 있는 jar 파일들을 알려주면 됩니다.

how_to_test_servlet_2.png

그다음, 마저 서블릿 예제를 완성시키고 "Ctrl + B (Build All)" 키를 눌러 컴파일 시킵니다.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException
            {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        
        out.println("<html><body>Hello World</body></html>");
        
            }
}

그럼, 해당 프로젝트의 하위 /bin 폴더에 HelloWorld.class 파일이 생성되는데 이것을 웹 서버(톰캣)가 설치된 하위 "\webapps\ROOT\WEB-INF"에 "classes" 폴더를 생성하고 복사합니다.

"...[톰캣 압축 해제 폴더]\webapps\ROOT\WEB-INF\classes\HelloWorld.class"

아직 끝이 아닙니다. ^^ 아쉽게도 톰캣에서는 기본적으로 servlet을 활성화 해놓지 않고 있어서, 이에 대한 설정을 변경해 주어야 합니다.

JSP 0708 - TOMCAT Servlet을 돌리기위한 기본설정 2
; http://dandyboys.tistory.com/entry/JSP-0708-TOMCAT-Servlet-을-돌리기위한-기본설정-2

위의 글에 따라서 /conf/web.xml 파일을 편집기로 열고, invoker 관련 서블릿 구성(servlet, servlet-mapping)에 대해 주석을 해제합니다.

<servlet>
    <servlet-name>invoker</servlet-name>
    <servlet-class>
        org.apache.catalina.servlets.InvokerServlet
    </servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>invoker</servlet-name>
    <url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

위의 설정만 해제하고 Tomcat 6에서 웹서버를 구동하면 콘솔 화면에서 다음과 같은 오류를 확인할 수 있습니다.

Error deploying web application directory docs
java.lang.SecurityException: Servlet of class org.apache.catalina.servlets.InvokerServlet is privileged and cannot be loaded by this web application
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1146)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1079)
        at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1002)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:506)
        at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
        at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
        at org.apache.catalina.core.StandardService.start(StandardService.java:525)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

찾아보니, ^^ 다음과 같은 글이 나옵니다.

1.톰캣 6.0 서블릿 로딩 설정(context.xml)
; http://jaehwacho.springnote.com/pages/2499106.xhtml

따라서, /conf/context.xml 파일을 열어서 Context노드에 reloadable, privileged 속성을 다음과 같이 추가해 주면 됩니다.

<Context reloadable="true" privileged="true">

휴~~~, 이제 끝입니다. ^^ 마지막으로 '/bin/startup.bat' 파일을 실행하면 톰캣 웹 서버가 구동되고, "http://localhost:8080/servlet/HelloWorld" 주소를 웹 브라우저로 방문하면 실행되는 것을 확인할 수 있습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/21/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11049정성태9/24/201620965오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201622010VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625812기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627468개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620116Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620368VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621796.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619961오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619428.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626730.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623222오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625073VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628307.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624786개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620416오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624435개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622332오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621548개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617781오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620336VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627465.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621524오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622594.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623575Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622289개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621604오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...