SlideShare a Scribd company logo
자바 웹 개발 시작하기
(7주차 : 국제화, 확인검증, 예외처리)
2011. 12. 09

DEVELOPMENT #2

이덕곤
§  간단한 게시판을 커뮤니티를 만들어보자!
§  DataBase : MySQL, JDBC, DBCP
§  하이버네이트, 기초 쿼리(CRUD)
§  Transaction(TX)
§  쿠키와 세션
§  커뮤니티 프로젝트의 시작
§  로그인과 테스트와 국제화, 검증, 예외처리
§  jUnit : 단위 테스트 전략 알아보기(다음시간)
§  세션과 로그인 처리
§  국제화 : I18N
§  Validation
§  예외처리 : Exception
§  과제 : 국제화된 커뮤니티로 만들어 오기
§  세션에 사용자 정보를
담아서 인증합니다

package com.starpl.study.base.bean;
public class UserSession
{
private boolean logged;

§  세션 객체를 제작

private int userIdx;
private String userName;

§  저장할 정보

private String nickName;
private String userId;

§  로그인 여부 : boolean

private String email;

§  사용자 번호 : int

public int getUserIdx() {

§  아이디 : String

return userIdx;

§  이름 : String

}
public void setUserIdx(int userIdx) {

§  별명 : String

this.userIdx = userIdx;

§  전자우편 : String

}
}
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAda
pter">
<property name="customArgumentResolvers">
<list>
<bean class="com.starpl.study.base.aop.GlobalArgumentResolver" />
</list>
</property>
<property name="messageConverters">
……
</property>
</bean>
<mvc:interceptors>
<bean class="com.starpl.study.base.aop.RequestInterceptor" />
</mvc:interceptors>
package com.starpl.study.base.aop;
public class GlobalArgumentResolver implements WebArgumentResolver {
@Override
public Object resolveArgument(MethodParameter methodParameter,
NativeWebRequest webRequest) {
if (UserSession.class == methodParameter.getParameterType()) {
HttpSession session = (HttpSession) webRequest.getSessionMutex();
if (session != null) {
UserSession userSession = (UserSession) session.getAttribute("userSession");
if (userSession != null) {
return userSession;
} else {
return new UserSession();
}
}
}
return UNRESOLVED;
}
}
package com.starpl.study.base.aop;
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception
{
HttpSession session = request.getSession();
UserSession userSession = (UserSession) session.getAttribute("userSession");
if (userSession != null) {
request.setAttribute("_USER", userSession);
} else {
request.setAttribute("_USER", userSession = new UserSession());
}
return true;
}
}
§  확인 : 시스템 구성 단위가 목표한 대로 동작하기 위한
작업으로, 시스템의 모든 계층에 꼭 필요함
§  JSR 303 Bean Validation
§  도메인 객체를 확인하기 위한 Java 표준 기술
§  어노테이션으로 확인 규칙을 명시

§  hibernate-validator-4.2.0.Final.jar
§  validation-api-1.0.0.GA.jar
§  스프링 폼 태그와 연동
<bean id="validator“
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolvers">
……
</property>
<property name="messageConverters">
……
</property>
<property name="webBindingInitializer">
<bean
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
</property>
</bean>
package com.starpl.study.model.domain;
public class UserJoinCommand
{
@Length(min = 4, max = 16) private String userId;
@Length(min = 4, max = 16) private String userName;
@Length(min = 4, max = 16) private String nickName;
@Length(min = 4, max = 16) private String userPassword;
@Length(min = 4, max = 16) private String userPassword2;
@Email @NotBlank private String email;
// getter, setter 정의
}
@RequestMapping(value = { "/join" }, method = RequestMethod.POST)
public String joinUser(HttpServletRequest request, Model model,
@Valid UserJoinCommand userJoinCommand, BindingResult result)
{
// @Valid 수행 후 에러가 있으면
if (result.hasErrors())
{
// 다시 가입폼으로 보내줍니다.
return viewBase + "/join";
}
…… // 이상이 없으면 가입 처리
}
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<style>
.form-item { margin: 20px 0; }
.form-label { font-weight: bold; }
.form-error-field { background-color: #FFC; }
.form-error-message { font-weight: bold; color: #900; }
</style>
<form:form commandName="userJoinCommand">
<div class="form-item">
<div class="form-label">userId:</div>
<form:input path="userId" size="20" cssErrorClass="form-error-field"/>
<div class="form-error-message"><form:errors path="userId" /></div>
</div>
</form:form>
§  선택이 아닌 필수
§  properties 파일에 저장
§  messages_en.properties
§  messages_ko.properties
§  Properties Editor 플러그인 필요
§  이클립스 마켓에서 다운
§  properties 파일을 ascii값으로 변경
§  "안녕하세요“ 변경하면…
"uc548ub155ud558uc138uc694"
<bean id="messageSource" class="org.springframework.context.support.ReloadableResour
ceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"/>
<property name="basename" value="/WEB-INF/view/i18n/messages" />
</bean>
<bean id="messageSourceAccessor" class="org.springframework.context.support.Messa
geSourceAccessor">
<constructor-arg ref="messageSource" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<bean class="com.starpl.study.base.aop.RequestInterceptor" />
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleRe
solver" />
§  messages_en.properties
§  org.hibernate.validator.constraints.NotBlank.message=Can not be empty.
§  org.hibernate.validator.constraints.Length.message
=length must be between {2} and {1}.
§  already_login_err=Have already Logined.
§  not_login_err=No login information.

§  messages_ko.properties
§  org.hibernate.validator.constraints.NotBlank.message=비워둘 수 없습니다.
§  org.hibernate.validator.constraints.Length.message
=길이는 {2}와 {1} 사이 여야합니다.
§  already_login_err=이미 로그인 되어 있습니다.
§  not_login_err=로그인 정보가 없습니다.
§  자바에서 사용하기
§  @Autowired private MessageSourceAccessor msa;
§  msa.getMessage("not_login_err");

§  JSP에서 사용하기
§  <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
§  Locale = ${pageContext.response.locale}
( <a href="?locale=ko_kr">ko</a>|<a href="?locale=en_us">us</a> )
§  <fmt:message key="Join"/>
§  에러(Error) 프로그램 코드에 의해서 수습될 수 없는 심각한 오류
§  예외(Exception) 프로그램 실행 중에 발생하는 예기치 않은 사건 중
프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류
§  예외가 발생하는 예
§  정수를 0으로 나누는 경우
§  배열의 첨자가 음수 또는 범위를 벗어나는 경우
§  부적절한 형 변환이 일어나는 경우
§  입출력을 위한 파일이 없는 경우 등

§  자바 언어는 프로그램에서 예외를 처리할 수 있는 기법을 제공
§  예외 블록의 지정
try {
...... // try 블록 : 예외가 발생할 가능성이 있는 문장을 지정한다
}
catch(예외타입N 매개변수N) {
...... // 예외 처리 블록 N
}
finally {
...... // finally 블록 : 예외의 발생여부와 상관없이 무조건 수행
}

§  예외를 발생시키기 위해 throw 문 사용
throw new 예외객체타입(매개변수);
Ex : throw new StarplStudyI18nException("already_login_err");
public class StarplStudyException extends RuntimeException
{
private static final long serialVersionUID = 1L;
String message;
/**
* @param message
*/
public StarplStudyException(String message)
{
super(message);
this.message = message;
}
}
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.starpl.study.base.bean.StarplStudyException">
common/exception</prop>
<prop key="com.starpl.study.base.bean.StarplStudyI18nException">
common/exceptionI18n</prop>
</props>
</property>
</bean>
<%@ page language="java“
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" /><title>에러</title>
<link type="text/css" rel="stylesheet" href="/res/css/board.css" />
</head>
<body>
<p align="center">${exception.message}</p>
<div class="button"><a href="javascript:history.back()">뒤로</a></div>
</body>
</html>
§  세션을 사용해 로그인을 관리할 수 있습니다
§  국제화된 어플을 만들 수 있습니다
§  유효성 검사를 할 수 있습니다
§  예외처리를 할 수 있습니다
§  그동안 수고하셨습니다. 다음주 부터는 실전!! ^^*
§  프로젝트 설계
§  명세서를 만들어 보자
§  로그인과 보드의 통합
§  단위테스트
§  동작하는 소프트웨어가 포괄적인 문서보다 우선
이다 : 애자일 동맹 선언 중
§  Properties Editor
http://blog.kangwoo.kr/6
§  국제화
http://choija.com/216
§  Validation
http://www.slideshare.net/kingori/spring-3-jsr-303
§  예외처리
http://blog.ohmynews.com/icorea77/34761
http://ivis.changwon.ac.kr/wiki/index.php?title=%EA%B7%B8%EB%
A6%BC:Java_%EC%98%88%EC%99%B8%EC%B2%98%EB%A6
%AC_%EC%84%B8%EB%AF%B8%EB%82%98.ppt&redirect=no
자바 웹 개발 시작하기 (7주차 : 국제화, 확인검증, 예외처리)

More Related Content

PDF
자바 웹 개발 시작하기 (9주차 : 프로젝트 구현 – 추가적인 뷰)
PDF
자바 웹 개발 시작하기 (4주차 : MVC)
PDF
자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)
PDF
자바 웹 개발 시작하기 (8주차 : 명세서, 단위테스트, 통합)
PDF
자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)
PDF
자바 웹 개발 시작하기 (2주차 : 인터넷과 웹 어플리케이션의 이해)
PDF
20131217 html5
PDF
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
자바 웹 개발 시작하기 (9주차 : 프로젝트 구현 – 추가적인 뷰)
자바 웹 개발 시작하기 (4주차 : MVC)
자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)
자바 웹 개발 시작하기 (8주차 : 명세서, 단위테스트, 통합)
자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)
자바 웹 개발 시작하기 (2주차 : 인터넷과 웹 어플리케이션의 이해)
20131217 html5
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)

What's hot (20)

PDF
자바 웹 개발 시작하기 : 계획
PDF
자바 웹 개발 시작하기 (10주차 : ㅌㅗㅇ ㅎㅏ ㄹㅏ)

PDF
Facebook은 React를 왜 만들었을까?
PPTX
세미나 Spring mybatis
PPTX
Spring boot-summary(part2-part3)
PDF
실전! 스프링과 함께하는 환경변수 관리 변천사 발표자료
PDF
React Native를 사용한
 초간단 커뮤니티 앱 제작
PPTX
영속성 컨텍스트로 보는 JPA
PDF
overview of spring4
PPTX
Spring mvc
PPTX
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
PDF
Spring-Boot (springcamp2014)
PDF
Spring boot 공작소(1-4장)
PPTX
스프링군살없이세팅하기(The way to setting the Spring framework for web.)
PDF
[오픈소스컨설팅]MyBatis Basic
PPTX
HeadFisrt Servlet&JSP Chapter 3
 
PDF
Jpa 잘 (하는 척) 하기
PDF
역시 Redux
PDF
React 튜토리얼 2차시
PDF
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
자바 웹 개발 시작하기 : 계획
자바 웹 개발 시작하기 (10주차 : ㅌㅗㅇ ㅎㅏ ㄹㅏ)

Facebook은 React를 왜 만들었을까?
세미나 Spring mybatis
Spring boot-summary(part2-part3)
실전! 스프링과 함께하는 환경변수 관리 변천사 발표자료
React Native를 사용한
 초간단 커뮤니티 앱 제작
영속성 컨텍스트로 보는 JPA
overview of spring4
Spring mvc
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
Spring-Boot (springcamp2014)
Spring boot 공작소(1-4장)
스프링군살없이세팅하기(The way to setting the Spring framework for web.)
[오픈소스컨설팅]MyBatis Basic
HeadFisrt Servlet&JSP Chapter 3
 
Jpa 잘 (하는 척) 하기
역시 Redux
React 튜토리얼 2차시
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
Ad

Viewers also liked (16)

PDF
20141229 dklee docker
PDF
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
PDF
Starpl 20111012 스타플5를_만들기_시작하며
PPTX
SpringMVC 전체 흐름 알아보기
PDF
8주 dom & event basic
PDF
7주 JavaScript Part2
PDF
4주 CSS Layout
PPTX
Database design
PPTX
자바 프로그래밍 Agile(1장 시작하기)
PDF
NDC12_Lockless게임서버설계와구현
PDF
구글 앱 엔진의 활용(Google App Engine) 2부
PDF
P2P Transfers
PPTX
유니티3D 그리고 웹통신
PDF
Anatomy of a Data Product and Lending Club Data
PDF
NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉
PPTX
스마트폰 온라인 게임에서 고려해야 할 것들
20141229 dklee docker
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
Starpl 20111012 스타플5를_만들기_시작하며
SpringMVC 전체 흐름 알아보기
8주 dom & event basic
7주 JavaScript Part2
4주 CSS Layout
Database design
자바 프로그래밍 Agile(1장 시작하기)
NDC12_Lockless게임서버설계와구현
구글 앱 엔진의 활용(Google App Engine) 2부
P2P Transfers
유니티3D 그리고 웹통신
Anatomy of a Data Product and Lending Club Data
NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉
스마트폰 온라인 게임에서 고려해야 할 것들
Ad

Similar to 자바 웹 개발 시작하기 (7주차 : 국제화, 확인검증, 예외처리) (20)

PDF
02.실행환경 실습교재(데이터처리)
KEY
Html5 performance
PDF
okspring3x
PPTX
4-3. jquery
PPTX
Jenkins를 활용한 javascript 개발
KEY
vine webdev
PPTX
Scala, Spring-Boot, JPA의 불편하면서도 즐거운 동거
PPTX
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
PDF
[아꿈사/111105] html5 9장 클라이언트측 데이터로 작업하기
PDF
Okjsp 13주년 발표자료: 생존 프로그래밍 Test
PDF
(Spring Data JPA)식별자(@Id, Primary Key) 자동 생성, @GeneratedValue의 strategy 속성,Ge...
PDF
Resource Handling in Spring MVC
PDF
#33.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PPTX
Xe3.0 frontend validator
PDF
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
PPTX
Hacosa jquery 1th
PDF
테스트
PPTX
4-1. javascript
PPTX
E government framework
PDF
20150912 windows 10 앱 tips tricks
02.실행환경 실습교재(데이터처리)
Html5 performance
okspring3x
4-3. jquery
Jenkins를 활용한 javascript 개발
vine webdev
Scala, Spring-Boot, JPA의 불편하면서도 즐거운 동거
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
[아꿈사/111105] html5 9장 클라이언트측 데이터로 작업하기
Okjsp 13주년 발표자료: 생존 프로그래밍 Test
(Spring Data JPA)식별자(@Id, Primary Key) 자동 생성, @GeneratedValue의 strategy 속성,Ge...
Resource Handling in Spring MVC
#33.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
Xe3.0 frontend validator
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
Hacosa jquery 1th
테스트
4-1. javascript
E government framework
20150912 windows 10 앱 tips tricks

자바 웹 개발 시작하기 (7주차 : 국제화, 확인검증, 예외처리)

  • 1. 자바 웹 개발 시작하기 (7주차 : 국제화, 확인검증, 예외처리) 2011. 12. 09 DEVELOPMENT #2 이덕곤
  • 2. §  간단한 게시판을 커뮤니티를 만들어보자! §  DataBase : MySQL, JDBC, DBCP §  하이버네이트, 기초 쿼리(CRUD) §  Transaction(TX) §  쿠키와 세션 §  커뮤니티 프로젝트의 시작
  • 3. §  로그인과 테스트와 국제화, 검증, 예외처리 §  jUnit : 단위 테스트 전략 알아보기(다음시간) §  세션과 로그인 처리 §  국제화 : I18N §  Validation §  예외처리 : Exception §  과제 : 국제화된 커뮤니티로 만들어 오기
  • 4. §  세션에 사용자 정보를 담아서 인증합니다 package com.starpl.study.base.bean; public class UserSession { private boolean logged; §  세션 객체를 제작 private int userIdx; private String userName; §  저장할 정보 private String nickName; private String userId; §  로그인 여부 : boolean private String email; §  사용자 번호 : int public int getUserIdx() { §  아이디 : String return userIdx; §  이름 : String } public void setUserIdx(int userIdx) { §  별명 : String this.userIdx = userIdx; §  전자우편 : String } }
  • 5. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAda pter"> <property name="customArgumentResolvers"> <list> <bean class="com.starpl.study.base.aop.GlobalArgumentResolver" /> </list> </property> <property name="messageConverters"> …… </property> </bean> <mvc:interceptors> <bean class="com.starpl.study.base.aop.RequestInterceptor" /> </mvc:interceptors>
  • 6. package com.starpl.study.base.aop; public class GlobalArgumentResolver implements WebArgumentResolver { @Override public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { if (UserSession.class == methodParameter.getParameterType()) { HttpSession session = (HttpSession) webRequest.getSessionMutex(); if (session != null) { UserSession userSession = (UserSession) session.getAttribute("userSession"); if (userSession != null) { return userSession; } else { return new UserSession(); } } } return UNRESOLVED; } }
  • 7. package com.starpl.study.base.aop; public class RequestInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); UserSession userSession = (UserSession) session.getAttribute("userSession"); if (userSession != null) { request.setAttribute("_USER", userSession); } else { request.setAttribute("_USER", userSession = new UserSession()); } return true; } }
  • 8. §  확인 : 시스템 구성 단위가 목표한 대로 동작하기 위한 작업으로, 시스템의 모든 계층에 꼭 필요함 §  JSR 303 Bean Validation §  도메인 객체를 확인하기 위한 Java 표준 기술 §  어노테이션으로 확인 규칙을 명시 §  hibernate-validator-4.2.0.Final.jar §  validation-api-1.0.0.GA.jar §  스프링 폼 태그와 연동
  • 9. <bean id="validator“ class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource" ref="messageSource" /> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="customArgumentResolvers"> …… </property> <property name="messageConverters"> …… </property> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="validator" ref="validator" /> </bean> </property> </bean>
  • 10. package com.starpl.study.model.domain; public class UserJoinCommand { @Length(min = 4, max = 16) private String userId; @Length(min = 4, max = 16) private String userName; @Length(min = 4, max = 16) private String nickName; @Length(min = 4, max = 16) private String userPassword; @Length(min = 4, max = 16) private String userPassword2; @Email @NotBlank private String email; // getter, setter 정의 }
  • 11. @RequestMapping(value = { "/join" }, method = RequestMethod.POST) public String joinUser(HttpServletRequest request, Model model, @Valid UserJoinCommand userJoinCommand, BindingResult result) { // @Valid 수행 후 에러가 있으면 if (result.hasErrors()) { // 다시 가입폼으로 보내줍니다. return viewBase + "/join"; } …… // 이상이 없으면 가입 처리 }
  • 12. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <style> .form-item { margin: 20px 0; } .form-label { font-weight: bold; } .form-error-field { background-color: #FFC; } .form-error-message { font-weight: bold; color: #900; } </style> <form:form commandName="userJoinCommand"> <div class="form-item"> <div class="form-label">userId:</div> <form:input path="userId" size="20" cssErrorClass="form-error-field"/> <div class="form-error-message"><form:errors path="userId" /></div> </div> </form:form>
  • 13. §  선택이 아닌 필수 §  properties 파일에 저장 §  messages_en.properties §  messages_ko.properties §  Properties Editor 플러그인 필요 §  이클립스 마켓에서 다운 §  properties 파일을 ascii값으로 변경 §  "안녕하세요“ 변경하면… "uc548ub155ud558uc138uc694"
  • 14. <bean id="messageSource" class="org.springframework.context.support.ReloadableResour ceBundleMessageSource"> <property name="defaultEncoding" value="UTF-8"/> <property name="basename" value="/WEB-INF/view/i18n/messages" /> </bean> <bean id="messageSourceAccessor" class="org.springframework.context.support.Messa geSourceAccessor"> <constructor-arg ref="messageSource" /> </bean> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> <bean class="com.starpl.study.base.aop.RequestInterceptor" /> </mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleRe solver" />
  • 15. §  messages_en.properties §  org.hibernate.validator.constraints.NotBlank.message=Can not be empty. §  org.hibernate.validator.constraints.Length.message =length must be between {2} and {1}. §  already_login_err=Have already Logined. §  not_login_err=No login information. §  messages_ko.properties §  org.hibernate.validator.constraints.NotBlank.message=비워둘 수 없습니다. §  org.hibernate.validator.constraints.Length.message =길이는 {2}와 {1} 사이 여야합니다. §  already_login_err=이미 로그인 되어 있습니다. §  not_login_err=로그인 정보가 없습니다.
  • 16. §  자바에서 사용하기 §  @Autowired private MessageSourceAccessor msa; §  msa.getMessage("not_login_err"); §  JSP에서 사용하기 §  <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> §  Locale = ${pageContext.response.locale} ( <a href="?locale=ko_kr">ko</a>|<a href="?locale=en_us">us</a> ) §  <fmt:message key="Join"/>
  • 17. §  에러(Error) 프로그램 코드에 의해서 수습될 수 없는 심각한 오류 §  예외(Exception) 프로그램 실행 중에 발생하는 예기치 않은 사건 중 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류 §  예외가 발생하는 예 §  정수를 0으로 나누는 경우 §  배열의 첨자가 음수 또는 범위를 벗어나는 경우 §  부적절한 형 변환이 일어나는 경우 §  입출력을 위한 파일이 없는 경우 등 §  자바 언어는 프로그램에서 예외를 처리할 수 있는 기법을 제공
  • 18. §  예외 블록의 지정 try { ...... // try 블록 : 예외가 발생할 가능성이 있는 문장을 지정한다 } catch(예외타입N 매개변수N) { ...... // 예외 처리 블록 N } finally { ...... // finally 블록 : 예외의 발생여부와 상관없이 무조건 수행 } §  예외를 발생시키기 위해 throw 문 사용 throw new 예외객체타입(매개변수); Ex : throw new StarplStudyI18nException("already_login_err");
  • 19. public class StarplStudyException extends RuntimeException { private static final long serialVersionUID = 1L; String message; /** * @param message */ public StarplStudyException(String message) { super(message); this.message = message; } }
  • 20. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="com.starpl.study.base.bean.StarplStudyException"> common/exception</prop> <prop key="com.starpl.study.base.bean.StarplStudyI18nException"> common/exceptionI18n</prop> </props> </property> </bean>
  • 21. <%@ page language="java“ contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="ko"> <head> <meta charset="utf-8" /><title>에러</title> <link type="text/css" rel="stylesheet" href="/res/css/board.css" /> </head> <body> <p align="center">${exception.message}</p> <div class="button"><a href="javascript:history.back()">뒤로</a></div> </body> </html>
  • 22. §  세션을 사용해 로그인을 관리할 수 있습니다 §  국제화된 어플을 만들 수 있습니다 §  유효성 검사를 할 수 있습니다 §  예외처리를 할 수 있습니다 §  그동안 수고하셨습니다. 다음주 부터는 실전!! ^^*
  • 23. §  프로젝트 설계 §  명세서를 만들어 보자 §  로그인과 보드의 통합 §  단위테스트 §  동작하는 소프트웨어가 포괄적인 문서보다 우선 이다 : 애자일 동맹 선언 중
  • 24. §  Properties Editor http://blog.kangwoo.kr/6 §  국제화 http://choija.com/216 §  Validation http://www.slideshare.net/kingori/spring-3-jsr-303 §  예외처리 http://blog.ohmynews.com/icorea77/34761 http://ivis.changwon.ac.kr/wiki/index.php?title=%EA%B7%B8%EB% A6%BC:Java_%EC%98%88%EC%99%B8%EC%B2%98%EB%A6 %AC_%EC%84%B8%EB%AF%B8%EB%82%98.ppt&redirect=no