2009/08/11 09:34 CodeIN/Java
크리에이티브 커먼즈 라이선스
Creative Commons License
이번에는 Servlet에 대하여 정리를 해보겠습니다.
인터넷 검색을 하면은 많은 자료들이 나오는데, 제가 이해한데로 정리를 해보겠습니다.
물론 거의 퍼온 거지만요 ㅎㅎ 워낙 자료가 많아서 출처는..... 먼산~  ㅡ_-)>

Java Applet은 Web 클라이언트인 브라우저에서 수행되는 Java 실행파일이며,

Java Servlet은 Server Side Applet의 약어로 Web 서버 즉, Servlet 컨테이너에서 수행되는 Java 클래스 입니다.

이제서야 Applet이 뭔지 Servlet이 뭔지 확실하게 이해가 가는군요 :")

Servlet은 구현 시 상속해야 하는 부모 클래스가 정해져 있음.

1. Servlet, GenericServlet, HttpServlet 중 하나를 상속하여 구현한다.

2. init(), service(), destory()등의 메소더들은 정해진 순서로 호출되므로, 각 메소드가 호출되는 시점에 수행해야 할 기능이 있으면 해당 메소드를 오버라이딩한다.

3. Java Application과는 달리 단독으로 수행될 수 없다.

 

HttpServlet 클래스를 상속하는 경우 service()메서도는 브라우저로부터의 요청 방식(GET 또는 POST) 에 따라 doGet(), doPost()등 정해진 메서드들을 호출.



아래 소스는 가장 기본적인 소스이지만, 처음 공부하는 나에게는 굉장히 어려운?? 응??
public class FlowServlet extends HttpServlet{
   @Override
   public void init(ServletConfig sc){
       System.out.println("init()");
   }
   @Override
   public void service(ServletRequest reg, ServletResponse res){
       System.out.println("service()");
   }
   @Override
   public void destroy(){
       System.out.println("destory()");
   }
}

servlet의 수행 흐름에 대하여 정리를 해보겠습니다.
1. 브라우저로부터 WAS에 Servlet 수행 요청이 전송됩니다.
2. 요청된 Servlet 클래스를 찾아서 메모리에 로딩한 후 객체를 생성합니다.
3. init(ServletConfig) 메소드를 호출합니다.
4. service(ServletRequest, ServletResponse) 메소드를 호출합니다.
5. 요청 방식에 따라서 doGet(HttpServletRequest, HttpServletResponse) 또는 doPost(HttpServletRequest, httpServletResponse) 메소드를 호출합니다.
6. 출력 버퍼의 내용을 요청한 브라우저로 리턴한다.

알아 두셔야 할 사항은 Servlet 요청이 최초 요청인 경우과 두 번째 이후의 요청의 흐름이 다릅니다.


최초의 요청과 두 번째 이후의 요청의 차이점은 객체의 생성과 init() 메소드의 호출입니다.
최초의 요청에서 2번, 3번(메모리에 로딩후 객체 생성과 init()을 호출 하였기 때문)을 통해서 서블릿 객체가 생성되었기 때문에 2번 3번을 제외한 1번, 4번, 5번, 6번만 수행이 되는거져.


init() 메소드 호출과 관련된 내용을 다시 한번 훑어 보면은,
처음으로 Servlet의 요청이 들어왔을 때 해당 Servlet은 Servlet 컨테이너에 의해 자동으로 메모리에 로딩 된다. 메모리로 Servlet 클래스가 로딩된 후에 객체가 생성되는데, 이 때 init() 메소드를 호출하게 됩니다. init() 메소드는 Servlet 로딩시(최초 처음) 단 한번 호출됩니다.


posted by 조금까칠한남자
2009/08/04 16:18 CodeIN/Java
크리에이티브 커먼즈 라이선스
Creative Commons License

예전에 인터넷 찾아 가면서 이것 저것 삽질 끝에 동작 가능한 환경을 구축해본 적이 있기는 하지만...
해놓고도 뭐가 뭔지도 모르는 상황이 발생...
오늘 깔끔하게 정리를 해보겠습니다.


Tomcat 설치, JDK설치나 환경 변수 설정은 정리하지 않겠습니다. :")

아래 링크 참조.

(Tomcat 설치 및 환경 변수 설정 : http://www.voiceportal.co.kr/273)

 

Tomcat의 버전이 올라가면서 보안상의 이유로 기본적으로 서블릿을 실행하지 못하도록 설정이 되어있습니다. 따라서 몇가지 설정 변경을 해주어야 하는데요.


1. %TOMCAT_HOME%\conf\web.xml을 에디터로 오픈

 

간단히 web.xml에 대하여 알아보겠습니다.

web.xml은 Web Application의 Deployment Descriptor(환경파일)로서 XML 형식의 파일입니다.

web.xml에 작성되는 내용은 다음과 같습니다.

Session의 유효시간 설정

Servlet/JSP mapping

리스너/필터 설정

보안

ServletContext의 초기 파라미터

Servlet/JSP에 대한 정의

Mime Type mapping

Welcom File list

Error Pages 처리


2. "invoker"로 검색을 해서 아래 부분의 주석을 제거 한다.

<--
<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>
-->   

3. "invoker" 로 검색하여 아래 부분의 주석을 제거 한다. 
<--
<servlet-mapping>
        <servlet-name>invoker</servlet-name>
        <url-pattern>/servlet/*</url-pattern>
    </servlet-mapping>
-->           


4. Java 컴파일러가 Servlet API를 인식할 수 있도록 %TOMCAT_HOME%\common\lib 디렉토리에 저장되어 있는 Servlet API의 압축 파일을 %JRE_HOME%\lib\ext 디렉토리에 복사한다.

servlet-api.jar 파일


(참고, 제가 사용하고 있는 tomcat 버전은 6.0.18 인데, %TOMCAT_HOME%\common\lib 이 아니라 %TOMCAT_HOME%\lib에 있습니다.)

 

 

추가 정보(참고 사이트 : http://www.jiny.kr/jiny/333)

위에 설명한 것처럼, 주석을 제거하고 tomcat을 실행해보면은 아래와 같은 Exception이 발생합니다. ivrlog.xml관련 context 파일에 문제가 있는듯 합니다.

심각: Error deploying configuration descriptor ivrlog.xml
java.lang.SecurityException: Servlet of class org.apache.catalina.servlets.InvokerServlet is privileged and cannot be loaded by this web application

Tomcat 6.x 버전부터는 다음과 같이 서블릿 리로딩에 관련된 추가적인 설정을 해주어야 한다.

 

%TOMCAT_HOME%\conf\context.xml을 수정해줘야 한다. 빨간 부분을 추가한다.

%TOMCAT_HOME%\conf\context.xml의 파일을 수정하면 여기 WAS에 loading된 모든 Web Application에 전부 적용이 된다.

<!-- The contents of this file will be loaded for each web application -->
<Context reloadable="true" privileged="true">

 

또는

 

각 Web Application별로 설정을 하려면

%TOMCAT_HOME%\conf\Catalina\localhost 디렉토리에 web application관련 context xml파일을 오픈하여 <Context> 태그를 아래와 같이 수정해주어야 한다.

빨간색 부분을 추가한다.

아래 파일은 VPTest라는 Web Application의 VPText.xml 파일의 내용이다.

<Context privileged="true" reloadable="true" antiJARLocking="true" docBase="D:\imhotk_Flagship\SelfDevelopment\VPTest\build\web" path="/VPTest"/>

 

 

Turn on Servlet Reloading 
The next step is to tell Tomcat to check the modification dates of the 
 class files of requested servlets, and reload ones that have changed  
since they were loaded into the server's memory. This slightly degrades  
performance in deployment situations, so is turned off by default.  
However, if you fail to turn it on for your development server, you'll  
have to restart the server every time you recompile a servlet that has  
already been loaded into the server's memory
. Since this tutorial  
discusses the use of Tomcat for development, this change is strongly  
recommended. 

To turn on servlet reloading, edit Edit install_dir/conf/context.xml and change 

 

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

   
Note that the privileged entry is really to support the invoker  
servlet (see the following section), so you can omit that entry if you  
do not use the invoker.

필수적으로 privileged는 해줘야 겠군요 :")

reloadable 또한 해주는 것이 편할 듯 싶습니다.

 

posted by 조금까칠한남자
2009/08/03 14:20 Gossip/Day by Day
크리에이티브 커먼즈 라이선스
Creative Commons License
8월달 온라인 강의 주제는 JSP & Servlet Programming 이다.

지난 달에는 [Power Biz Skill] 프로직장인의 성공 시크릿 (CS 노하우)을 수강하였는데 흠... 나름 재미있었음. 97점의 우수한 성적으로 이수하였음 ㅋㅋ.
그럼 나 이제 프로 직장인 되는그야???


요새는 웹에 대해서 관심은 완전 많은데.... 아는게 하나도 없으니.... 할 수 있는게 하나도 없다 으~
그래서 이번달은 웹 관련 온라인 교육을.... 아... 이런거 온라인으로 배우면 도움이 되려나...
좀 의심 스럽지만...


방금 Applet에 간단히 학습을 하였는데, 웹과 관련된 기술들을 이해하는데 좀 도움이 되는거 같다.
내가 너무 기본이 없어서 그런가?? 으흐흐
교육 내용을 정리하고 싶은데.... 이거 뭐 저작권 같은거 걸리는거 아녀??
에잇.. 뭐 이래!!

'Gossip > Day by Day' 카테고리의 다른 글

휴.. 다음달 카드값이 걱정이다..  (2) 2009/08/05
2009년 8월 3일 컴퓨터 견적  (29) 2009/08/04
JSP & Servlet Programming 온라인 강의  (2) 2009/08/03
유이 - UEE  (3) 2009/07/29
One Summer night  (7) 2009/07/29
AfterSchool - 유이 UEE  (2) 2009/07/29
posted by 조금까칠한남자
2009/03/19 12:16 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License
나는 개발을 할 때 주로 "verdana" font를 사용한다
가장 보기 쉽고 이쁘다 ^0^
그런데 JSP공부를 하는데 한글이 깨져서 나오길래 verdana font는 한글 지원이 안되나부다 했는데 그게 아니었다...

아래 소스를 응용하면 한글 깨짐 현상을 없앨 수 있다.

String test="김태정 온 보이스보탈";

test=new String(test.getBytes("8859_1"), "EUC-KR");

System.out.println("test : " + test);

김태정 온 보이스 보탈


<추가 내용>
jsp를 계속 공부하다보니까 계속적으로 한글 문제가 발생된다..
그래서 왜 유니코드를 사용한다는 java에서 이런문제가 발생되는지 궁금하였다...
그런데 이게 한글을 웹으로 전송할 때 발생되는 문제라는 것을 알게 되었다.

http://cafe.naver.com/jokerx04.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=255

위 내용을 간단히 정리를 하면은

한글 웹브라우저에서는 KSC5601코드를 기본으로 사용하는데 웹으로 전송(HTTP REQUEST)할 때는 x-www-form-urlencoded 형식으로 인코딩 된다고 한다. 그런데 서블릿은 전송된 문자들이 ISO-8859-1 표준 코드라고 생각한다. 그리고 JAVA에서는 유니코드를 사용하므로 전달된 한글코드를 ISO-8859-1로 인코딩을 한다고 한다. 그래서 웹으로 한글을 전송하게 되면은 무조건 깨진다고 봐야한다.
그래서 우리도 ISO-8859-1 형식의 유니코드로 인코딩된(깨진 상태다)놈을 다시 ISO-8859-1의 바이트 배열로 추출한다. 그 다음에 그놈을 다시 원래의 포맷인 KSC5601 형식으로 변환 해주면 된다. 또 서블릿에서 웹으로 보낼 때도 한글을 ISO-8859-1 형식으로 변환한다. 그래서 이것은 KSC5601 을 사용하는 euc-kr 로 변환해서 전송해야 한다.
이것은 JSP 페이지나 서블릿에 contentType 의 charset 을 "euc-kr" 로 설정해 주기만 하면 된다.

euc-kr 은 한글은 KSC5601 로 표현하고, 영어는 JSC5636을 사용하는 방법인데, 벨 연구소에서 제안한 유닉스 상에서 영어 외의 문자를 표현하는 방법 중에 하나이다. euc-kr 은 Extended UNIX Korea Code 의 약자이다.










참고 사이트
http://blog.daum.net/sowebpro/6952936

'CodeIN > Web' 카테고리의 다른 글

[opensource] OpenFlashChart 사용하기  (6) 2009/12/19
X internet 이란  (0) 2009/03/26
[java/jsp]한글 깨짐  (0) 2009/03/19
[javascript] contentEditable  (0) 2009/03/10
[javascript]submit()  (0) 2009/03/10
[jsp]forward  (0) 2009/03/08
posted by 조금까칠한남자
2009/03/08 20:20 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License
<body></body> 안에 아래 jsp:forward page를 넣어주면 된다.

<!--
         Holidays.jsp 에서 파일path를 parameter로 넘길때 "8859_1"을 "EUC-KR"로 넘겼으므로
         다시 넘길때는 "EUC-KR"을 "8859_1"로 넘긴다.       
     -->
<jsp:forward page="holidays.jsp">   
    <jsp:param name="filePath" value="<%=new String(filePath.getBytes("EUC-KR"), "8859_1") %>"/>
</jsp:forward>

'CodeIN > Web' 카테고리의 다른 글

[javascript] contentEditable  (0) 2009/03/10
[javascript]submit()  (0) 2009/03/10
[jsp]forward  (0) 2009/03/08
[javascript] confirm 사용법  (2) 2009/03/01
JavaScript String Replace All  (3) 2009/02/20
[javascript] dynamic 테이블 생성시 event 추가 하는 방법  (0) 2009/02/18
posted by 조금까칠한남자
TAG Forward, jsp
2009/02/16 11:41 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License

흐미.. 정말 웹은.... -0-;;


function delRow(){
    var sTable = document.getElementById("sTable");
    var lastRow = sTable.rows.length;
    if(confirm("정말 삭제 하시겠습니까?")){ 
        //테이블에서 checkbox중 check된 것만 삭제     
        for( var i=1 ; i < lastRow ; i++ ){                       
            if(document.getElementsByTagName("tr")[i].cells[0].firstChild.checked){                                       
                sTable.deleteRow(i);
                break;               
            }
        }       
    }   
}
function enabledAll(){
    var sTable = document.getElementById("sTable");
    var lastRow = sTable.rows.length;   
    for( var i=1 ; i < lastRow ; i++ ){
     //tag가 tr인 것중에서 첫번째 cell(여기서는 checkbox)을 disabled=false로 만들어라.
     //이것때문에 고생 좀 했다... false라는 것 "false"라고 하면은 안되더라.그냥 "true"는 되는데 -0-;;;.
    document.getElementsByTagName("tr")[i].cells[0].firstChild.disabled=false;       
    }
}

function disabledOthers(){   
    var sTable = document.getElementById("sTable");
    var lastRow = sTable.rows.length;       
    for( var i=1 ; i < lastRow ; i++ ){ 
        //checkbox중에서 checked 된것을 제외한 나머지를 disabled=true로만든다.        
        if(!document.getElementsByTagName("tr")[i].cells[0].firstChild.checked){
            document.getElementsByTagName("tr")[i].cells[0].firstChild.disabled="true";
        }       
    }
}


<td><input type="checkbox" id="chk" name="chk" onclick="disabledOthers();" ></td>
<input type="button" value="삭제" onclick="delRow();enabledAll();">


posted by 조금까칠한남자
2009/02/09 18:01 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License
허접하지만^^
text파일에서 값을 읽어서 테이블로 만들어 주는 것이다.
text파일 안의 내용은
A=12345678
B=12345678
C=12345678
D=12345678
....
이런 형식이며 중요한 점은 한글파일을 index.jsp에서 ReadFile.jsp 로 넘기는 것이다.
그리고 더 중요한 것은 ReadFile.jsp에서 SaveFile.jsp를 넘기는 것이다.

뭐 대충 이런 값들을 넘겨줄 때 사용한다고 생각하면 된다.


수 많은 parameter를 넘겨서 받을 때 유용하게 사용할 수 있을 것이다.

index.jsp 파일

<body>   
    <span style="font:bold 11pt Verdana;">
    <h2>근무시간 File:</h2>       
        <form method="post" action="ReadFile.jsp">
            <input id="path" type="file" name="filePath" size="80"><br>
            <input type="submit" name="submit" value="파일 읽기">
            <input type="reset" name="reset" value="취소">
        </form>
    </span>       
</body>



ReadFile.jsp 파일
<body>
        <%               
                //파라미터에서 filPath를 가져온다.
                String filePath =  request.getParameter("filePath");
                //한글이 깨지지 않도록 해준다.
                filePath = new String(filePath.getBytes("8859_1"), "EUC-KR");               
                File f = new File(filePath);
                FileReader fr = new FileReader(f);
                BufferedReader br = new BufferedReader(fr);           
                //session에 filePath를 저장해둔다.
                session.setAttribute("filePath",filePath);
        %>       
    <span style="font:bold 11pt Verdana;">
        <form name="timeTable" method="post" action="SaveFile.jsp">           
            <table border="1" width="30%">           
                <tr bgcolor="#00456c" style="color:white;">
                    <th>Service</th>
                    <th>Start time</th>
                    <th>End time</th>           
                </tr>           
                <%   
                    String line="";
                    String start="";
                    String end="";                   
                    while((line=br.readLine()) != null){                                                           
                        String[] split = line.trim().split("=");
                        start=split[1].substring(0,4);
                        end=split[1].substring(4,8);
                %>                   
                    <tr bgcolor="#00456c" style="color:white;">                                   
                        <td><input type="text" name="service" value=<%= split[0]%>></td>
                        <td><input type="text" name="start" size="30%" value=<%= start %>></td>
                        <td><input type="text" name="end" size="30%" value=<%= end %>></td>                       
                    </tr>
                <%                       
                    }           
                    br.close();
                %>           
            </table>   
                <input type="submit" value="save" size="80%">
        </form>       
    </span>
</body>


SaveFile.jsp
<%
        String[] title = new String[3];
        String[] service=null;
        String[] startTime=null;
        String[] endTime=null;       
        Enumeration en = request.getParameterNames();       
        String line="";
        int i=0;
        while(en.hasMoreElements()){
            title[i++] = (en.nextElement()).toString();   
        }       
        service = request.getParameterValues(title[0]);       
        endTime = request.getParameterValues(title[1]);
        startTime = request.getParameterValues(title[2]);       
       
        String filePath = (String)session.getAttribute("filePath");               
        FileWriter fw = new FileWriter(filePath);
        BufferedWriter bw = new BufferedWriter(fw);       
    %>
   
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <span style="font:bold 11pt Verdana;">
    File Saved!!<br>
        <table border="1" width="30%">
        <caption>Time table</caption>
            <tr bgcolor=#00456c style="color:white;">
                <th>Service</th>
                <th>Start time</th>
                <th>End time</th>
            </tr>   
                <%                               
                    for(int j=0 ; j < service.length ; j++){                       
                        service[j] = new String( service[j].getBytes("8859_1"), "EUC-KR");                       
                %>
                    <tr bgcolor="#00456c" style="color:white;">
                        <td><input type="text" name="service" value=<%= service[j] %> disabled></td>
                        <td><input type="text" name="start" size="30%" value=<%= startTime[j] %> disabled> </td>
                        <td><input type="text" name="end" size="30%" value=<%= endTime[j] %> disabled> </td>           
                    </tr>
                <%
                        line = service[j] + "=" + startTime[j] + endTime[j];                       
                        bw.write(line);
                        bw.newLine();                       
                    }               
                    bw.close();
                    fw.close();                   
                %>               
            </table>
</body>
</html>












posted by 조금까칠한남자
2009/02/09 13:50 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License
휴~
사용할 때마다 찾아서 쓰는 것보다 정리 해놓는게 좋을 것 같아서 하나씩 정리를 해본다.

아래 소스는 File을 선택하는 소스이다.
이런 간단한 것들은 앞으로 정리 좀 해두어야 겠다^^;;
소스 설명할 필요가 없을 정도로 간단하다.

<span style="font:bold 11pt Verdana;">
        <h2>근무시간 File:</h2>
        <form name="fileChooser" method="post" action="ReadFile.jsp">
            <input type="file" name="filePath" size="80"><br>
            <input type="submit" name="submit" value="파일 읽기">
            <input type="reset" name="reset" value="취소">
        </form>
</span>   



posted by 조금까칠한남자
2008/11/04 11:17 Voice Portal/WAS
크리에이티브 커먼즈 라이선스
Creative Commons License
the problem is that when you open your page in a normal way
(i.e. http://localhost:8081/yourJFSpage.jsp ) it is not in a .../faces/* path so the

there is no mapping recognized(

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>)

the Face Servletis not invoked and consequetntly there there is no FacesContext :)





'Voice Portal > WAS' 카테고리의 다른 글

[shell] tomcat 로그 파일 관리  (0) 2008/11/17
ECMA Script란  (0) 2008/11/10
java.lang.RuntimeException: Cannot find FacesContext  (0) 2008/11/04
Lambda Probe - tomcat monitoring  (0) 2008/10/28
UDDI, WSDL, SOAP  (0) 2008/05/26
Eclipse에서 Tomcat plugin사용하기  (0) 2008/05/17
posted by 조금까칠한남자
2008/10/24 10:58 CodeIN/Web
크리에이티브 커먼즈 라이선스
Creative Commons License
ReadID.java 파일을 실행했을 때(즉, local에서 실행했을 때)의
System.getProperty("user.dir")의 값은
D:\imhotk_Flagship\J2EE\workspace\IMRwiki 이다.

//these are for running ReadID.java
   private final String filePath_idList=System.getProperty("user.dir") + "\\WebContent\\idList.ini";   
   private final String filePath_nameList=System.getProperty("user.dir") + "\\WebContent\\nameList.ini";


하지만 JSP파일에서 ReadID객체를 생성하여 사용하였을 경우(단, 이클립스 상에서 실행했을 경우의 path이다. 실질적으로 war로 말아서 올리면 이런 방식으로 구현을 하면 안된다.)
System.getProperty("user.dir")의 값은
D:\imhotk_Flagship\J2EE 이다.

//these are for running JSP
   //private final String filePath_idList=System.getProperty("user.dir") + "\\workspace\\IMRwiki\\WebContent\\idList.ini";   
   //private final String filePath_nameList=System.getProperty("user.dir") + "\\workspace\\IMRwiki\\WebContent\\nameList.ini";

참고로 System.getProperty("user.dir")은 실행환경에 따라 값이 달라지므로 개발을 하고 테스트 할 때 굉장히 불편하다.
그래서 왠만하면 사용하지 않는 것이 좋다.

   

'CodeIN > Web' 카테고리의 다른 글

[jsp]많은 수의 parameter 받기  (0) 2009/02/09
[jsp]file 선택하기  (0) 2009/02/09
[JSP]file path 정하기  (0) 2008/10/24
The value for the useBean class attribute common.CustomizedQuery is invalid.  (2) 2008/10/22
[javascript]href구현하기  (3) 2008/10/22
[Javascript]Auto refresh  (1) 2008/10/20
posted by 조금까칠한남자
prev 1 2 next