doc-ver.0.1

1. 서론
 Struts2 프레임워크는, JavaEE 기반의 웹어플리케이션 개발 시에, Model 2 기반의 개발을 쉽게 할 수 있도록 MVC 패턴의 적용을 도와주는 프레임워크이다. 실상 MVC 패턴 적용이라고 하기는 하기만, Struts2 는, View 와 Controller 정도의 분리를 돕는데 주된 기능을 한다.

 자세한건 시간나는대로 문서를 업데이트 해가며 내용을 추가 해 보겠다.

2. Hello Struts2 해보기
 가. 두가지 방식의 Configuration

  Struts2 는 XML 방식, Java SDK 1.5 이상에서 지원하는 Annotation 방식 의 두가지 방식을 통하여 Configuration 을 가능하게 한다. 개념적으로, 아래 그림처럼 가능하다는 얘기이다.


   XML 방식에서 사용되는 XML 예제는 아래와 같다.
<action name="Login" class="manning.Login">    <result>/AccountPage.jsp</result>    <result name="input">/Login.jsp</result></action><action name="Registration" >    <result>/Registration.jsp</result></action><action name="Register" class="manning.Register">    <result>/RegistrationSuccess.jsp</result>    <result name="input">/Registration.jsp</result></action>

   Annotation 방식의 예제 코드는 아래와 같다.
@Results({    @Result(name="input", value="/RegistrationSuccess.jsp" )    @Result(value="/RegistrationSuccess.jsp" )})public class Login implements Action {    public String execute() {        //Business logic for login    }}

 위 예제에 대한 설명은 이후에 자세히 설명하도록 하고, 지금은, XML 과 Annotation 방식으로 Struts2 의 설정이 가능하다는 것만 알고 넘어가자. 어떤것을 쓸것인가는 개발하기 나름이다. 그러나 Struts2 개발진은 Zero-Configuration 을 지향하고 있다. 무수히 많아지는 XML 파일을 관리하기가 너무 번거롭기 때문이다.

 Annotation 방식으로 가게 되면, 한가지 전제가 따라야 할 듯 하다. 바로, 패키지 및 액션명의 네이밍 룰 정의가 일관되고 견고해야 하며, 모두들 이를 확실히 지켜야 한다는 점 이겠다. 만약 액션명에서 패키지명을 유추하기 힘들거나, 반대로, 패키지명에서 액션명을 유추하기 힘들다면, 가독성과 유지보수성이 많이 떨어질 듯 하다.

 나. package
  package 는 상당히 중요하며, 전체적인 struts2 의 Action, result 등의 구조를 파악할 수 있다. 

  namespace 속성
   URL과 맵핑하는데 사용된다. 아래와 같은 struts2 XML 정의가 있을 때,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="chapterTwo" namespace="/chapterTwo" extends="strutsdefault">
		<action name="Name">
			<result>/chapterTwo/NameCollector.jsp
			</result>
		</action>
		<action name="HelloWorld" class="manning.chapterTwo.HelloWorld">
			<result name="SUCCESS">/chapterTwo/HelloWorld.jsp
			</result>
		</action>
	</package>
</struts>

namespace="/chapterTwo" 는, 아래와 같은 URL Mapping 구조로 해석될 수 있다.



-------
  Action 인터페이스 상속
   Action 인터페이스는 상속받아도 되고 안받아도 된다. 상속 받으면, SUCCESS, ERROR, NONE, ERROR, INPUT, LOGIN 등의 미리 정의 된 문자열 상수를 사용할 수 있고, public void execute() 함수정의를 필수로 Override 한다라는 잇점 정도가 있다. 

  ValueStack 과 JavaBean 으로의 Action
 Form 데이터 날라오면, ParameterInterceptor 에서, ValueStack 을 만들고, Action 의 setter method 를 호출하여 값을 설정해준다.
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,
 Exception 중에, 다른 Exception 은, throw 할 때, 해당 함수가 public void someFunction() throws XXXException 처럼, throws 를 반드시 명시해야 하지만, RuntimeException 은, 함수가 throws 를 정의하지 않아도 에러가 나지 않는다. 특수한 속성이 있어서 그런 듯 하다.
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

AppFuse 는, 직접 다운로드 받는게 아니라, Maven 을 통해 받아와야 한다.
이를 위해서는 Maven 을 받아서 설치해야 하는데, 받는 김에 Eclipse 용 Maven 플러그인(m2eclipse) 을 설치하려고, 하는데, Install & Update 에서, install.. 하면, equinox 어쩌구 하고 에러가 뜬다.

 이건, 내가 Maven 설치 시에, 옵셔널한 놈들도 설치하려고 해서 그런것이고, AJDT 관련 옵션을 설치하려 해서 그렇다. 에러 없이 진행하려면, AspectJ Development Tool 을 먼저 Eclipse 에 받으면 된다.
 관련 URL 은, http://docs.codehaus.org/display/M2ECLIPSE/Installation+Requirements 에 보면 설명중에 AJDT(Optional) 부분에, Eclipse Update URL 이 나와 있다.
 현재 3.4 용은  http://download.eclipse.org/tools/ajdt/34/update 에서 받으면 된단다.
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

 프로젝트 중에, JEUS 를 사용하는데 (제우스6), JSP 나 Action 은 모두 Response Header 에, Content-Type 이 UTF-8 로 잘 넘어오지만, 유독 JS 파일을 받을 때, euc-kr 로 넘어오더라. 

 JEUS 에서, 기본적으로, Encoding 정보가 별도로 없으면, euc-kr 로 넘기는 듯 싶다. Jeus 6 의 경우, WEBMain.xml 에서, 기본 인코딩 정보를 아래와 같이 설정해주면 된다.
<context-group>
...
<encoding>
        <request-url-encoding>
                <default>UTF-8</default>
        </request-url-encoding>
        <request-encoding>
                <default>UTF-8</default>
        </request-encoding>
        <response-encoding>
                <default>UTF-8</default>
        </response-encoding>
</encoding>
...
</context-group>



또, 아래 정보는 어디서 퍼온 것인데, JavaScript 별로, charset 을 지정해 줄 수 있다.

International Language Support in JavaScript

JavaScript is built to support a wide variety of world languages andtheir characters – from the old US ASCII up to the rapidly spreadingUTF-8. This page clears up some of the difficulties encountered whendealing with multiple languages and their related characters.

JavaScript and Character Sets

When working with non-European character sets ("charsets"), you mayneed to make changes to the way your page references externalJavaScript(.js) files. Ideally, your .js files should saved in theUTF-8 character set in order to maximize its multilingual features —though you can use a different charset that supports your language, atthe potential expense of users who can't support it. Once your filesare saved as UTF-8, they must be "served" in the UTF-8 charset in orderto display correctly. There are a few ways to ensure this:

Serve the Web Page as UTF-8

If your page is already served as UTF-8 (i.e. Content-type=text/html; charset=UTF-8),you don't need to make any changes — all embedded files in an HTMLdocument are served in the same charset as the document, unlessexplicitly specified not to by you. You can do this by:

  • Use the Content-type meta tag — place at the TOP of your page's <head> section.

    <meta name="http-equiv" content="Content-type: text/html; charset=UTF-8"/>)
  • Edit your webserver configuration to serve all documents as UTF-8
  • Send the Content-type header via your server-side scripts (i.e. PHP, ASP, JSP)

Use the charset attribute of the <script> tag

The easiest way to ensure your script is served as UTF-8 is to add acharset attribute (charset="utf-8") to your <script> tags in theparent page:

<script type="text/javascript" src="[path]/myscript.js" charset="utf-8"></script>

Modify your .htaccess files (Apache Only)

You can also configure your webserver to serve all .js files in theUTF-8 charset, or only .js files in a single directory. You can do thelatter (in Apache) by adding this line to the .htaccess file in the directory where your scripts are stored:

AddCharset utf-8 .js
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,



1. Prologue

 JAVA 개발하면서, log4j 를 모르는 사람은 없을듯 하다. 그만큼 오래전부터 사용 해 왔고, 성능또한 검증이 되었고, 사용법도 그리 어렵지 않아서인 듯 하다. 실제로 많은 오픈소스 프레임웍이나 라이브러리에서, log4j 에 dependency 를 걸고 있는 것만 보아도 그렇다.

 사내 프레임워크의 경우, log4j 를 사용하지는 않지만, Concept 을 다소 가져다가 쓰는 부분들이 있다. 하지만 사실 설정이나 사용 편의성, 기능의 확장성 등의 측면에서, 사내 프레임웍이 조금은 나은 듯 하기도 하다. Log4J 는 Inherit 개념으로 인해 살짝 불필요한 고민을 아키텍트나 개발자가 하게 만드는 것 같다.

 뭐 아직 많이 사용해보지는 않았으니, 내가 잘 모르는 뭔가가 있을수도..

 이번 Log4J 를 분석해가면서 한가지 원칙을 정한게 있다. "책은 안본다" 라는 원칙인데, 공부하기 싫다는건 아니고, 오픈소스 라이브러리들이 대부분 보면, Help 가 빈약하다는 느낌이다. 이것저것 쓰다보면, 안그래도 좋지않은 머리가 사용법을 다 기억하고 있는것도 아니고, Help 를 봐가면서 작업해야 하는데, MSDN 처럼 정리된 Help 가 있는것도 아니라서 난감할 때가 한두번이 아니다.

 책을 보면, 참 친절하게 설명하고는 있으나, 책 보면서 하려면, 책 없으면 못한다라는 결론이 내려져서, 이번부터는 책 없이 해보려 한다. 그래서, 여기저기를 뒤져가면서 (아 왜 지들이 만들고 사용법은 신경을 안서 그랴..) 나만의 사용법 등을 정리 해 나가기로 했다.

2. 설치 및 관련 파일

 log4j 는 apache 의 logging 프로젝트로 들어가면 된다. logging.apache.org 들어가면, log4j, log4cxx, log4net 등이 있고, 현재는 log4php 가 incubation 상태이다.

  log4j 1.2 버전을 받고 (1.3은 중단됐고, 2.0은 실험용이란다), 압축을 푼다. 현재 최신 버전은 1.2.15 버전이다.
요놈을 받아서 풀면, 아래와 같은 디렉토리 나오겠다.


- contribs 에는, 개발한 애들의 이름 밑에, 갸들의 샘플 코드들이 있고 (나중에 시간나면 뭔 코든지나 좀 살펴봐야 할듯)
- examples 에는, 샘플이 있긴 한데, 정말 별 쓰잘떼기 없는 샘플들이다. 특히, 난 lf5 밑에 있는 코드들이 예시를 든 잘된 코드구나.. 생각했드니만, 죄다 log force 5 라는 로그 보여주는, 패키지 내의 툴을 띄워서 보여줄 목적으로 만든 코드들이다.
- site 는, 지들 사이트의 문서들을 offline 에서 볼수있도록 해놓은 것들이고. (introduction 과 API 만 볼만함)
- src 는 log4j 의 소스코드
- tests 는 지들의 log4j 라이브러리 테스트 코드들을 넣어놨다. 그런데, 대부분의 properties 및 XML 설정파일들이 여기에 가지별로 있다. 하지만, XML 내에 어떤 element 가 어떤것인지는 안써있다는거~

나머지 뭐 빌드하고 자시고 할 것 없이, Eclipse 에 프로젝트 만들어서 Sample 몇개 돌려보면 될것이다. 어차피 샘플로 얻어지는 것은 별로 없더라는..

이노무 Ceki Gulcu 라는 놈이, 지 책 팔아먹을라고 제대로 된 매뉴얼은 책으로 만들어놓은듯..

3. Log4J 의 핵심 개념 몇가지

(1) Logger
 

(2) Appender

(3) Layout



반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

log4j 를 분석하다가, log4j 의 lf5 의 예제에서는, properties 파일을, 패키지 내부에 넣고,
예를 들어, 소스의 패키지가 lf5.sample 일 때, "/lf5/sample/log4j_sample.properties" 로 접근이 되는데, 내가 만든 클래스 내에서는, PropertyConfigurator.configure("/simpleTest/myapp2.log4j.properties"); 하면, 계속 파일 없다고 나오길래, lf5 의 예제 코드를 보니, 이런 부분이 있었더라는..

우선, 사용하려는 파일의 위치는 아래와 같고


잘 되는 소스코드는 이렇다.. 아래의 코드에서 무식하게 그냥 PropertyConfigurator.configure("/simpleTest/myapp2.log4j.properties");  해서 될게 아니다라는걸 깨닿게 된다.

public static final String resource = "/simpleTest/myapp2.log4j.properties";

public static URL configurationFileURL = MyApp2.class.getResource(resource);
	
	public static void main(String[] args) {
		/**
		 * 아래와 같이, property 파일을 직접 명시해주거나, 아니면, 
		 * src 의 root 에, log4j.properties 이름으로 두고, Configurator 설정을 안하면
		 * 된다~!
		 */
		PropertyConfigurator.configure(configurationFileURL);

위에서 public static URL configurationFileURL = MyApp2.class.getResource(resource); 요 부분이 핵심이다.

패키지 내부에 있는 리소스를 찾아서, URL 로 리턴해주는데,
logger.debug("Config file URL : " + configurationFileURL);
logger.debug("Config file URI : " + configurationFileURL.getFile());

위 코드로 확인해보면, 이렇게 나온다.
Config file URL : file:/E:/JavaProject/webproject/log4jtest/build/classes/simpleTest/myapp2.log4j.properties
Config file URI : /E:/JavaProject/webproject/log4jtest/build/classes/simpleTest/myapp2.log4j.properties

참 좋은 Method 같네. 담부터는 잘 활용해 먹어야 겠구만.
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

웹페이지 돌아다니다 보면, 소스코드 내용 중 문법이 Highlighting 되어서 이쁘게 나오는걸 보곤 한다.

이렇게..

class TestClass extends Object {
	public TestClass() {}
	
	public testFunction(String param) {
		System.out.println("Syntax Hilighting " + param);
	}
}

처음에 참으로 신기하고 이뻐보였다.. 나도 써보고 싶은것은 인지상정..ㅎ

사용법도 상당히 간단하다.

1. 다운받기

우선, http://alexgorbatchev.com/wiki/SyntaxHighlighter 사이트가 공식 사이트이다. 현재 버전은 2.0.320 이고
공짜로 다운로드 받아서 사용 가능하다.


위의 download 링크 눌러서 다운로드 한다. 그냥 본 블로그에 첨부파일로도 집어넣었다.
압축을 풀면 아래와 같이 세가지 디렉토리가 나온다

* scripts - 동작시에 필요한 script 들이 있다. 모든 .js 파일들이 페이지에 include 되어야 한다. 스크립트 중 shCore.js 와 shLegacy.js 스크립트는 Optimize 되어있어서 분석 불가다.
* src - 위 Optimize 된 스크립트의 소스가 있다. 사용할때는 src 디렉토리는 빼고 쓰면 된다.
* styles - 기본 및 테마 별 CSS 가 들어있는 디렉토리이다. 사용 시 몇가지를 link 해줘야 한다.

위 자료가 준비되었으면, 사용하면 된다.^^;;

2. <Header> 에 추가하기

사용법 또한 참 쉽다. HTML  코드에서 몇가지만 추가 해주면 된다.

우선, <header> 에, 아래 스크립트들을 포함한다.
<script type="text/javascript" src="scripts/shCore.js"></script>
<script type="text/javascript" src="scripts/shBrushBash.js"></script>
<script type="text/javascript" src="scripts/shBrushCpp.js"></script>
<script type="text/javascript" src="scripts/shBrushCSharp.js"></script>
<script type="text/javascript" src="scripts/shBrushCss.js"></script>
<script type="text/javascript" src="scripts/shBrushDelphi.js"></script>
<script type="text/javascript" src="scripts/shBrushDiff.js"></script>
<script type="text/javascript" src="scripts/shBrushGroovy.js"></script>
<script type="text/javascript" src="scripts/shBrushJava.js"></script>
<script type="text/javascript" src="scripts/shBrushJScript.js"></script>
<script type="text/javascript" src="scripts/shBrushPhp.js"></script>
<script type="text/javascript" src="scripts/shBrushPlain.js"></script>
<script type="text/javascript" src="scripts/shBrushPython.js"></script>
<script type="text/javascript" src="scripts/shBrushRuby.js"></script>
<script type="text/javascript" src="scripts/shBrushScala.js"></script>
<script type="text/javascript" src="scripts/shBrushSql.js"></script>
<script type="text/javascript" src="scripts/shBrushVb.js"></script>
<script type="text/javascript" src="scripts/shBrushXml.js"></script>


다음은 역시 <header> 영역 안에, CSS 를 포함시킨다.
<link type="text/css" rel="stylesheet" href="styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="styles/shThemeDefault.css"/>


그리고, 아래 두 줄의 코드를 더 추가해준다.
<script type="text/javascript">
	SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
	SyntaxHighlighter.all();
</script>


3. 내용 만들기

이제 본격적으로 SyntaxHighlighter 를 사용해보자. 정말 쉽다..
아래처럼 <pre> 태그를 쓰면 된다.
<pre class="brush: c-sharp;">
function test() : String
{
	return 10;
}
</pre>

이게 끝이다. 특이한 것은 <pre> 태그의 class 이다.
위의 예에서는 <pre> </pre> 사이의 내용을 c-sharp 문법으로 인식하라는 얘기다.
이걸 바꿀 수 있는데, 어떤 스타일이 있는지는, 다운받은 압축파일을 푼 디렉토리의
scripts 디렉토리를 보면 알 수 있다.


위와 같이 많은 종류의 js 파일들이 있는데, 대충 파일명을 보면, 어떤 문법인지 알 수 있다.
그리고, js 파일을 열어보면 내용 중에 아래와 같은 부분이 있다.
SyntaxHighlighter.brushes.JScript = function()
{
	var keywords =	'break case catch continue ' +
					'default delete do else false  ' +
					'for function if in instanceof ' +
					'new null return super switch ' +
					'this throw true try typeof var while with'
					;

	this.regexList = [
		{ regex: SyntaxHighlighter.regexLib.singleLineCComments,	css: 'comments' },			// one line comments
		{ regex: SyntaxHighlighter.regexLib.multiLineCComments,		css: 'comments' },			// multiline comments
		{ regex: SyntaxHighlighter.regexLib.doubleQuotedString,		css: 'string' },			// double quoted strings
		{ regex: SyntaxHighlighter.regexLib.singleQuotedString,		css: 'string' },			// single quoted strings
		{ regex: /\s*#.*/gm,										css: 'preprocessor' },		// preprocessor tags like #region and #endregion
		{ regex: new RegExp(this.getKeywords(keywords), 'gm'),		css: 'keyword' }			// keywords
		];
	
	this.forHtmlScript(SyntaxHighlighter.regexLib.scriptScriptTags);
};

SyntaxHighlighter.brushes.JScript.prototype	= new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.JScript.aliases	= ['js', 'jscript', 'javascript'];

위 내용 중에,
SyntaxHighlighter.brushes.JScript.aliases	= ['js', 'jscript', 'javascript'];

이 부분을 보면, <pre classes="brush: <aliase이름>"> 중에 <aliase이름> 을 뭘 줘야할 지 알 수 있다.
또, 각 문법의 사용결과 샘플은 http://alexgorbatchev.com/wiki/SyntaxHighlighter:Brushes 에서 확인할 수 있다.


친절하게도 위와 같이, aliase 와 관련 파일명도 목록으로 제공한다.

4. 끝

참 잘만들었다는 생각이 든다. 내가 돈이 없어서 donation 은 못하고 잘 쓰기로 하겠다.
Tistory 블로그에서 사용하는 방법도 나중에 시간되면 올려보도록 하겠다.

그나저나 오픈소스 프레임워크 사용법들도 익혀야 하는데 갑자기 UI 에 필이 꽃혀서 이런..
반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,