Servlet parameter, korean handling

parameter

  • form태그의 submit버튼을 클릭해서 데이터를 서버로 전송하면, 해당 servlet에서는 HttpServletRequest객체를 이용하여 parameter값을 얻을 수 있다
  • getParameter(name) - namevalue값을 줌
  • getParameterValues(name) - name의 값이 여러개 일때
  • getParameterNames() - 해당 form태그의 하위 태그들 줌
1
2
String id = request.getParameter("id");
String pw = request.getParameter("pw");

korean handling

  • TomcatISO-8859-1방식을 기본 문자 처리 방식으로 하기 때문에 별도의 인코딩이 없으면 한글이 깨져보임
  • Get방식과 Post방식에 따라서 한글 인코딩 방법이 다름
  • Get방식 -> <server.xml>수정

    1
    <Connector URLEncoding="EUC-KR" port="8181"/>
  • Post방식 -> request.setCharacterEncoding() 메소드 이용

    1
    2
    3
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("EUC-KR");
    }
Comments

Servlet's way to run

Servlet작동 순서

  • 클라이언트에서 servlet요청이 들어 오면 서버에서는 servlet컨테이너를 만들고, 요청이 있을 때마다 스레드 생성

Servlet 라이프 사이클

  • 응답속도가 높아서 사용도가 높음
  • 최초 요청시 객체 생성 후 메모리에 로딩되고, 이후에는 기존 객체 재활용 -> 속도 빠름
  1. Servlet 객체 생성 - 최초 한번
  2. init() 호출 - 최초 한번
  3. service(),doGet,doPost() 호출 - 요청시 매번
  4. destroy()호출 - 마지막 한번 (자원 해제)

Servlet 선처리, 후처리

  • Servlet의 라이프 사이클 중 init(), destroy()에 선, 후처리 가능

  • @PostConstruct - Init()호출

  • destroy() - @PreDestroy
Comments

Servlet start

  • Servlet클래스는 HttpServlet를 상속 받음

    1
    2
    3
    4
    5
    @WebServlet("/Hworld")   
    public class Helloworld extends HttpServlet {
    private static final long serialVersionUID = 1L;
    ...
    }
  • 요청처리객체 및 응답처리객체를 톰캣에서 받음

    1
    2
    3
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().append("Served at: ").append(request.getContextPath());
    }
  • get방식, post방식 - form태그 method속성값

    • doGet호출 : URL값으로 정보가 전송되어 보안에 약함
    • doPost호출 : header를 이용해 정보가 전송되어 보안에 강함
  • doGet()

    • htmlform태그의 method속성이 get일 경우 호출
    • 웹브라우저 주소창을 이용하여 servlet을 요청하면 호출
  • doPost()

    • htmlform태그의 method속성이 post일 경우 호출
  • Context Path

    • WAS(Web Application Server)에서 웹애플리케이션을 구분하기위한 Path
    • 이클립스에서 프로젝트를 생성하면 자동으로 server.xml에 추가
Comments

Servlet

Servlet특징

  • 동적 웹애플리케이션 컴포넌트
  • .java확장자
  • 응답은 html 이용
  • java thread이용하여 동작
  • MVC패턴에서 controller로 이용됨

Mapping하는 방법

  1. .java - @WebServlet으로 매핑

    1
    2
    3
    4
    5
    @WebServlet("/Hworld")   <-- 여기!
    public class Helloworld extends HttpServlet {
    private static final long serialVersionUID = 1L;
    ...
    }
  2. web.xml - web.xml 파일에 매핑 정보 추가

    1
    2
    3
    4
    5
    6
    7
    8
    <servlet>
    <servlet-name>helloworld</servlet-name>
    <servlet-class>com.javalec.ex.Helloworld</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>helloworld</servlet-name>
    <url-pattern>/hw</url-pattern>
    </servlet-mapping>
Comments

JSP

JSP특징

  • 동적 웹애플리케이션 컴포넌트
  • .jsp확장자
  • 응답은 html 이용
  • 서블릿으로 변환되어 실행
  • MVC패턴에서 view로 이용됨
Comments

python Exception Raise

Exception raise

Occuring exception by raise

  • raisekeyword can make an exception in specific situation
  • IndexError occurs when __getitem__method(which implements indexing when sequance type class is made) goes out of the index range

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class SquareSeq:
    def __init__(self, n):
    self.n = n
    def __getitem__(self,k):
    if k >= self.n or k < 0:
    raise IndexError # out of index range, IndexError occurs
    return k * k
    def __len_(self):
    return self.n

    s = SquareSeq(10)
    print s[2], s[4]
    for x in s: # repeating until IndexError occurs
    print x,
    print s[20] # out of the index range

Customized exception class

  • Generally It is implemented by extending Exceptionclass
    (Other exceptions are unusual)
  • How to raise the exception
    • Same to built-in exception. Using raise [class instance]
  • How to catch the exception from Customized exception class
    • Using the class’ name like except [class name]
  • In the example below, except Big catches Bigand Small exception
    -> Because Smallis Big‘s sub-class’

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Big(Exception):
    pass

    class Small(Big):
    pass

    def dosomething1():
    x = Big()
    raise x # x is exception object, it can use raise

    def dosomething2():
    raise Small()

    for f in (dosomething1, dosomething2):
    try:
    f()
    except Big:
    print "Exception occurs!"

Passing exception

  • After raisekeyword, with exception, additional message can follow

    1
    2
    3
    4
    5
    6
    7
    def f():
    raise Exception, 'message!!!'

    try:
    f()
    except Exception, a:
    print a
  • When except keyword is used, exception message in initializer can be taken as 2nd parameter.

    1
    2
    3
    4
    5
    6
    7
    8
    a = 10
    b = 0
    try:
    if b == 0:
    raise ArithmeticError('you are dividing by 0')
    a/b
    except ArithmeticError, v:
    print v
Comments

python 예외 발생시키기

Exception raise

raise로 예외 발생하기

  • 예외를 특정 상황 조건에서 raise키워드를 통해 발생시킬 수 있다.
  • 아래 예는 시퀀스 형 클래스를 설계할 때 인덱싱을 구현하는 __getitem__메소드에서 인덱스가 범위를 넘을 때 IndexError를 발생시킨다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class SquareSeq:
    def __init__(self, n):
    self.n = n
    def __getitem__(self,k):
    if k >= self.n or k < 0:
    raise IndexError # 인덱스 범위를 벗어나나면 IndexError발생
    return k * k
    def __len_(self):
    return self.n

    s = SquareSeq(10)
    print s[2], s[4]
    for x in s: # IndexError가 발생하는 시점까지 반복
    print x,
    print s[20] # 인덱스 범위를 넘음

사용자 정의 예외 클래스

  • 일반적으로 Exception클래스를 상속 받아 구현
    (나머지 예외들은 일반적으로 나타나기 힘든 예외들이다)
  • 예외 발생 방법
    • 내장 예외 발생 방법과 동일하게 raise [클래스 인스턴스]와 같이 해당 예외 클래스의 인스턴스를 던진다
  • 사용자 정의 예외를 잡는 방법
    • except [클래스이름]과 같이 해당 예외 클래스의 이름을 사용한다.
  • 아래 예에서 except Big이 잡는 예외는 BigSmall이다
    -> SmallBig의 하위 클래스 이기 때문

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Big(Exception):
    pass

    class Small(Big):
    pass

    def dosomething1():
    x = Big()
    raise x # x는 예외객체이므로 raise가능

    def dosomething2():
    raise Small()

    for f in (dosomething1, dosomething2):
    try:
    f()
    except Big:
    print "Exception occurs!"

예외값 전달하기

  • raise키워드 뒤에 예외와 함께, 추가 메시지를 함께 던질 수 있다.

    1
    2
    3
    4
    5
    6
    7
    def f():
    raise Exception, 'message!!!'

    try:
    f()
    except Exception, a:
    print a
  • 생성자 안에 넣어준 에러 메시지는 except키워드 사용시에 두 번째 인자로 해당 메시지를 받을 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    a = 10
    b = 0
    try:
    if b == 0:
    raise ArithmeticError('0으로 나누고 있습니다.')
    a/b
    except ArithmeticError, v:
    print v
Comments

python 예외처리

Exception Handling

  • 구문 에러(Syntax Error)

    • 문법적 에러
    • IDE에서는 구문에러 체크해줌
    • 파이썬은 상대적으로 문법이 간단해서 에러 발생 비율이 낮거나 다른 도구로 제거 가능
  • 예외(Exception)

    • 구문 에러는 없으나 프로그램 실행 중 더 이상 진행할 수 없는 경우
    • 예외가 발생하면 프로그램이 종료됨
    1. NameError (정의되지 않은 변수 사용)

      1
      4 + boo*3
    2. ZeroDivisionError (0으로 나누는 경우)

      1
      2
      3
      a = 10
      b = 0
      c = a / b
    3. TypeError (ex: 문자열 + 수치형 자료)

      1
      '2' + 2
    4. IndexError (참조 범위를 넘어서 인덱스 사용)

      1
      2
      l = [1,2]
      print l[2]
    5. KeyError (등록되지 않은 키로 사전 검색)

      1
      2
      d = {"a":1, "b":2}
      print d['c']
    6. IOError (존재하지 않는 파일을 열고자 할 때)

      1
      a = open('aaa.txt')

예외 처리 방법

  1. try,except,else,finally절 사용하기

    • 예외가 발생할 만한 상황을 예상하여 상황별로 전체 코드 흐름을 제어할 수 있다
    • try,except,else,finally

      • 구조
        1
        2
        3
        4
        5
        6
        7
        8
        try:
        (예외 발생 가능한) 일반적인 수행문들
        except Exception:
        예외가 발생하였을 때 수행되는 문들
        else:
        예외가 발생하지 않았을 때 수행되는 문들
        finally:
        예외 발생 유무와 관계없이 무조건 수행되는 문들

  • 예외 처리를 하면 예외 발생시 프로그램이 종료되지 않는다.

    1
    2
    3
    4
    5
    a = 0
    try:
    print 1.0/a
    except ZeroDivisionError:
    print 'zero division error!!!'
  • msg변수: ZeroDivisionError를 정의한 사람이 발생될 때 주는 메시지
    ex: float division by zero

    1
    2
    3
    4
    5
    6
    7
    8
    def division():
    for n in range(0, 5):
    try:
    print 10.0 / n
    except ZeroDivisionError, msg
    print msg

    division()
  • try절 안에서 간접적으로 호출한 함수의 내부 예외도 처리 가능

    1
    2
    3
    4
    try:
    spam()
    except NameError, msg:
    print 'Error -', msg

    ,대신 as로도 사용가능

    1
    2
    3
    4
    5
    # 위와 동일한 예제
    try:
    spam()
    except NameError as msg:
    print 'Error -', msg
  • except뒤에 예외를 명시하지 않으면 모든 예외에 대해 처리됨

    1
    2
    3
    4
    5
    try:
    spam()
    print 1.0/0.0
    except:
    print 'Error'
  • 여러 예외들 각각에 대해 except절로 다중처리 가능

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    b = 0.0
    name = 'aaa.txt'
    try:
    print 1.0 / b
    spam()
    f = open(name, 'r')
    '2' + 2
    except NameError:
    print 'NameError !!!'
    except ZeroDivisionError:
    print 'ZeroDivisionError !!!'
    excpet (TypeError, IOError):
    print 'TypeError or IOERror !!!'
    else:
    print 'No Exception'
    finally
    print 'Exit !!!'

같은 부류의 예외 다 잡아내기

  • 예외 클래스의 상속에 의한 계층 관계를 이용하여 여러 예외들을 한꺼번에 잡을 수 있다.
  • 예를 들어, ArithmeticError의 하위 클래스로서 FloatingPointError, OverflowError, ZeroDivisionError가 존재하기 때문에 이들 하위 클래스 예외가 발생하면 ArithmeticError로 처리할 수 있다.

  • 예외가 임의의 except에서 잡히면 다른 except에서는 잡히지 않는다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def dosomething():
    a = 1/0

    try:
    dosomething()
    except ZeroDivisionError:
    print "ZeroDivisionError occured"
    except ArithmeticError:
    print "ArithmeticError occured"
Comments

python Exception Handling

Exception Handling

  • Syntax Error

    • Grammatical error
    • IDE checks syntax error automatically
    • Becasue python’s grammar is simpler relatively, error occur rate is smaller and it is easy to delete errors
  • Exception

    • the cases having no syntax errors, the program can’t progress
    • Occuring exception, the program ends
    1. NameError (Usiung undefined variable)

      1
      4 + boo*3
    2. ZeroDivisionError (Dividing by 0)

      1
      2
      3
      a = 10
      b = 0
      c = a / b
    3. TypeError (ex: String + Number type)

      1
      '2' + 2
    4. IndexError (Using index over the range of index)

      1
      2
      l = [1,2]
      print l[2]
    5. KeyError (Searching dictionary by unregisted key)

      1
      2
      d = {"a":1, "b":2}
      print d['c']
    6. IOError (Opening not existing file)

      1
      a = open('aaa.txt')

How to dispose of exceptions

  1. Using try,except,else,finally statements

    • By expecting the situations making exceptions, we can control the whole code’s flow
    • try,except,else,finally

      • structure
        1
        2
        3
        4
        5
        6
        7
        8
        try:
        (possible to make errors) usual statements
        except Exception:
        the statements working when error occurs
        else:
        the statements working when error doesn't occur
        finally:
        the statements working anyway no matter error

  • Doing exception handling, when error occurs the program doesn’t stop

    1
    2
    3
    4
    5
    a = 0
    try:
    print 1.0/a
    except ZeroDivisionError:
    print 'zero division error!!!'
  • msgvariable: the message that the person who defined ZeroDivisionError gives
    ex: float division by zero

    1
    2
    3
    4
    5
    6
    7
    8
    def division():
    for n in range(0, 5):
    try:
    print 10.0 / n
    except ZeroDivisionError, msg
    print msg

    division()
  • It can handle the error from the called function in trystatement indirectly

    1
    2
    3
    4
    try:
    spam()
    except NameError, msg:
    print 'Error -', msg

    , can be replaced with as

    1
    2
    3
    4
    5
    # same code with upper one
    try:
    spam()
    except NameError as msg:
    print 'Error -', msg
  • After except, not evincing any exceptions, it takes care of all exceptions

    1
    2
    3
    4
    5
    try:
    spam()
    print 1.0/0.0
    except:
    print 'Error'
  • About many exceptions, they can be taked care by each exceptstatement

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    b = 0.0
    name = 'aaa.txt'
    try:
    print 1.0 / b
    spam()
    f = open(name, 'r')
    '2' + 2
    except NameError:
    print 'NameError !!!'
    except ZeroDivisionError:
    print 'ZeroDivisionError !!!'
    excpet (TypeError, IOError):
    print 'TypeError or IOERror !!!'
    else:
    print 'No Exception'
    finally
    print 'Exit !!!'

Catching All exception in same kind

  • By using the hierarchy of Inheritance of exception class, It can take care of many exceptions by once
  • For example, there are FloatingPointError, OverflowError, ZeroDivisionError as sub-class of ArithmeticError so, about sub-class exceptions, ArithmeticError can take care of them

  • When an exception is catched by specific except, that one is not catched in other except

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def dosomething():
    a = 1/0

    try:
    dosomething()
    except ZeroDivisionError:
    print "ZeroDivisionError occured"
    except ArithmeticError:
    print "ArithmeticError occured"
Comments

python 패키지

패키지(Package)

  • 여러 모듈들을 한데 묶어서 정리해 놓은 구조
  • 물리적으로 여러 모듈 파일을 모아 놓은 디렉토리에 해당
    • 최상위 디렉토리 이름이 패키지 이름이 된다.
    • 최상위 디렉토리 하위에 여러 서브 디렉토리는 해당 최상위패키지의 하위 패키지가 된다.
    • 모듈=파일, 패키지=디렉토리

__init__.py의 역할

  • 디렉토리를 패키지로 인식시키는 역할
  • 서브 패키지에도 패키지와 마찬가지로 필요(없으면 단순 폴더역할)

import하기

1
import Speech
  • Speech디렉토리가 sys.path(또는 PYTHONPATH환경변수)에 열거된 폴더 중 하나에 위치해야함
  • Speech/Recognition/HMM.py코드 내용
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def train():
    print "Train"
    pass

    def loadModel():
    print "LoadModel"
    pass

    def saveModel():
    print "SaveModel"
    pass

특정 함수 사용하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 사용불가. 패키지명에서 .으로 특정 모듈, 함수 가져와야함
import Speech
Speech.Recognition.HMM.train()

# 적절한 방법
import Speech.Recognition.HMM
Speech.Recognition.HMM.train()

from Speech.Recognition import HMM
HMM.train()

from Speech.Recognition.HMM import train
train()

# 모듈 내의 변수 전부 다 가져옴, 모듈이름 없이 사용가능
from Speech.Recognition.HMM import *
train()
loadModel()
saveModel()
Comments