오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)
다음과 같은 설정 파일이 존재한다.
web.xml : Web Application Descriptor(DD)라고 하며 Struts2 필터를 등록한다.
struts.xml : Action, interceptor, result와 관련된 설정을 한다.
Struts.properties : 프레임워크의 동작방식을 정하는 설정 파일
1. web.xml
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Struts1과는 달리 Struts2에서는 Servlet이 존재하지 않으며 모든 요청이 들어오면 FilterDispatcher가 받아서 Controller 처럼 제어를 하게 된다.
2. struts.xml
Application의 전체 제어에 관련된 설정을 하는데 이 파일은 클래스패스의 루트(/WEB-INF/classes)에 위치해야 한다. Struts.xml 파일은 내부적으로 default 설정 파일을 포함하고 있는데 이 디폴트 설정 파일에는 디폴트 패키지가 있는데 상속이 가능하다. 따라서 디폴트 패키지를 상속해서 패키지 설정을 하면 편리하게 할 수 있는데 모든 패키지는 디폴트 패키지를 상속해서 작성하게 될 것이다.
struts.xml에 대한 default 설정 파일은 배포판의 struts2-core-2.0.14.jar의 루트에 struts-default.xml 이라는 이름으로 포함되어 있으며 이 파일은 struts.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>
<!—내부적으로 include 하고 있으므로 생략해도 된다 à
<include file=”struts-default.xml” />
<package name="hello" extends="struts-default">
<action name="hello" class="hello.HelloWorldAction">
<result name="SUCCESS">/result.jsp</result>
</action>
</package>
</struts>
[Package]
Package는 result-types, interceptors, action등을 논리적인 단위로 그룹핑 하는 데 사용된다. Bean 설정을 제외하면 모든 설정은 패키지 안에 있다. 패키지는 다른 패키지를 상속할 수 있는데 다른 패키지를 상속하면 그 패키지의 result-types, interceptors, action 설정을 그대로 이어 받는다.
패키지에 들어가는 엘리먼트의 순서는 다음과 같다.
result-types
interceptors
default-interceptor-ref
default-action-ref
global-results
global-exception-mappings
action
struts-default.xml 파일을 열어보면 struts-default라는 이름의 패키지가 있으며 패키지를 만드는 경우 struts-default 패키지를 상속해야 한다. 만약 그렇지 않으면 그 패키지에 정의된 많은 설정을 반복적으로 설정해야 하는 불편함이 있다.
패키지에 들어가서 속성(sttribute)는 다음과 같다.
name(필수) : 패키지명이며 유일해야 한다. 다른 패키지에서 상속 받을 때는 이이름을 사용한다.
extends(옵션) : 상속받고자 하는 패키지의 name을 입력 한다.
namespace(옵션) : 패키지내의 action 들을 URL에 매핑할 때 이 네임스페이스가 URL의 중간 경로가 된다.
abstract(옵션) : 추상패키지로 만든다.(action 설정이 없다.)
struts.xml에서 다음과 같이 namespace가 설정 되어 있다면…
<package name="hello" namespace="/tatata" extends="struts-default">
<action name="hello" class="hello.HelloWorldAction">
<result name="success">/result.jsp</result>
</action>
</package>
JSP에서는 다음과 같이 Action URL을 기술한다.
<form action=/struts2_helloworld/tatata/hello.action>
Input Your Name : <input type=text name=name>
<input type=submit>
</form>
위에서 struts2_helloworld는 Context 명이다.
/struts2_helloworld/tatata/hello.action 와 같은 요청을 받으면 마지막 “/”를 포함한 hello.action을 제외한 “/tatata” 라는 namespace를 가진 package를 찾으며 그 패키지 내에서 hello 라는 이름을 갖는 action을 찾게 되는 것이다.만약 hello라는 action을 찾지 못하면 default action을 실행하며 이도 없으면 default namespace를 찾는다. 만약 default namespace에 default action을 정의해 놓으면 어떠한 URL에도 매핑 된다.
default namespace : namespace 속성에 “”를 사용하거나 namespace 속성을 사용하지 않는다면 이것이 default namespace이다.
root namespace : root namespace인 “/”도 지원되는데 이것은 요청 URL에서 Context Path(Name) 바로 뒤에 action URL 형태로 들어왔을 때 사용되는 namespace로써 다른 namespace와 마찬가지로 지정된 action을 찾지 못하면 default namespace를 찾는다.
[include]
struts.xml 을 만들 때 한 파일에 모든 설정을 넣는다면 복잡해 질 것이다. 이를 위해 struts2 에서는 include를 이용해서 설정 파일을 나누고 통합할 수 있도록 해 준다.
<struts>
<!—내부적으로 include 하고 있으므로 생략해도 된다 à
<include file=”struts-default.xml” />
<include file=”struts1.xml” />
<include file=”struts2.xml” />
……
……
……
</struts>
각 포함된 파일은 struts.xml가 같은 형식 이어야 하며 <!DOCTYPE…> 또한 포함되어야 한며 classpath의 아무 곳에 존재하면 된다.
[interceptors]
action의 실행 전 후에 실행되는 모듈을 선언하는 요소.
interceptors : interceptor를 선언
interceptor-stack : 여러 개의 interceptor를 묶어 하나의 이름으로 참조할 수 있게 해 준다.
[action]
URL과 action 클래스를 매핑하며 action에 붙일 interceptor를 설정한다. 또한 action 수행 후의 result를 정의하며 action 수행 시 예외가 발생할 경우 예외에 따른 result를 정의한다.
다음과 같이 action이 struts.xml에 정의 되었다면…
<struts>
<package name="hello" namespace="/tatata" extends="struts-default">
<action name="hello" class="hello.HelloWorldAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
다음과 같은 요청이 들어오면 hello.HelloWorldAction 클래스가 실행된다.
/struts2_helloworld/tatata/hello.action
- action method : action 클래스에 대한 진입 메소드는 action 인터페이스에 정의되어 있다.
public interface Action {
public string execute() throws Exception;
}
Action에 execute 메소드외 여러 개의 action을 만들 수 있는데 … 하나의 action에 insert, update, delete, select와 같이 여러 개의 action method를 만들 수 있으며 이와 같이 기본 메소드가 아닌 경우에는 method 속성으로 지정한다.
<action name=”insert” class=”oraclejava.InsertAction” method=”insert”/>
- Action Support 디폴트 : 만약 action 정의에 class 속성을 사용하지 않으면 기본적으로 ActionSupport 클래스가 실행되는데 이 클래스는 execute() 메소드에서 SUCCESS를 return 한다.
만약 struts.xml에서 다음과 같이 action을 정의한다면 아무 일도 하지 않고 hello.jsp로 forward 한다.
<struts>
<package name="hello" namespace="/tatata" extends="struts-default">
<action name="hello">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
- default action : 요청한 action이 없으면 500에러가 발생하는데 매핑되어 있지 않은 URL로 요청이 들어 왔을 때 에러를 발생시키지 않고 어떤 페이지를 보여주고 싶다면 패키지 내에 default-action-ref를 정의하면 된다.
<struts>
<package name="hello" namespace="/tatata" extends="struts-default">
<default-action-ref name=”mydefault.MyDefaultAction”/>
<action name="hello" class="hello.HelloWorldAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
모든 action은 default action을 가질 수 있으며 하나의 namespace당 하나의 default action을 가질 수 있다.
- 와일드 카드 default : 패키지내의 action 설정에서 맨 마지막에 와일드카드 action을 지정하면 매칭되지 않는 모든 요청을 처리 할 수 있는데 와일드카드 default는 맨 마지막에 있어야 한다. 그렇지 않으면 와일드 카드 default 아래에 선언된 acton은 무시된다.
<action name=”*”>
<result>{1}.j네</result>
</action>
[result]
Action 클래스가 return한 결과 문자열은 result를 선택하는데 사용된다. Action 인터페이스는 다음과 같이 몇 개의 static 문자열을 제공한다. 하나의 action에는 여러 개의 result 가 올 수 있다.
public static final java.lang.String SUCCESS = "success";
public static final java.lang.String NONE = "none";
public static final java.lang.String ERROR = "error";
public static final java.lang.String INPUT = "input";
public static final java.lang.String LOGIN = "login";
public abstract java.lang.String execute() throws java.lang.Exception;
- result : result 요소는 두개의 속성을 갖는다.
name : action method가 리턴한 문자열과 매핑되는 이름(“success. error … 등”)
type : result TYPE으로 dispatcher(default), redirect 등
result 요소의 default parameter 는 location이다. 즉 파라미터를 쓰지 않고 result 요소의 body에 문자열을 기술한다면 location parameter를 의미한다.
<result name=”success” type=”dispatcher”>
<param name=”location”>/hello.jsp</param>
</result>
다음과 같은 결과이다. (name역시 success가 default 이다)
<result>>/hello.jsp </result>
- global-result : 모든 action에서 공통적으로 사용될 result 정의. 예를들면 에러나 로그인과 관련된 result 들…
[config-browser 플러그인]
웹 화면에서 action 구성을 확인할 수 있는데 struts2-config-browser-plugin-2.0.14 파일을 WEB-INF/lib에 복사 후 library path에 추가하면 된다.
다음과 같이 브라우저에서 요청을 하자.
http://localhost:8080/struts2_helloworld/config-browser/index.action
<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" /><?xml:namespace prefix = v />
이 플러그인은 자체적으로 클래스, 설정파일, 화면을 모두 가지고 있는데 struts2-config-browser-plugin-2.0.14 파일을 열어보면 struts-plugin.xml에 이 플러그인 Application의 package와 action 설정이 있고 config-browser 디렉토리에 FreeMarker로 뷰가 만들어져 있다.
다음에 배우게 되는 struts.properties의 default 설정파일인 struts2-core-2.X.jar 파일의 org/apache/struts2/default.properties에 다음과 같은 설정이 있어 struts-plugin.xml은 프레임웍을 자동으로 로드한다.
Struts.configuration.files=struts-default.xml,struts-plugin.xml,struts.xml
3. struts.properties
St이 파일은 프레임워크의 구동 방식에 대한 설정을 한다.struts.xml과 마찬가지로 classpath의 루트에 위치한다. 설정하는 모든 파라미터들은 struts.xml에서 상수 설정으로 정의할 수 있다.
<struts>
<constant name=”키” value=”값”/>
</struts>
struts.properties 파일은 struts2-core-2.x.jar 의 org/apache/struts2/default.properties 에 있는 디폴트 값을 오버라이드 할 수 있는데 그때는 디폴트값과 다른 것만 설정하면 된다. properties 파일은 클래스 경로 어떤 곳이라도 위치할 수 있다. 보통 /WEB-INF/classes 하위에 위치하는데 이클립스에서는 Java Resources (src) 의 바로 밑에서 추가한다. ( default package ) 그러면 자동으로 빌드 되면서 classes 폴더로 들어가게 된다.
스트럿츠2의 액션 확장자의 디폴트 값은 .action 이지만 struts.action.extension=do 라고 작성해주면 스트럿츠1 처럼 .do를 액션 요청으로 인식하게 된다.
#디폴트 locale과 인코딩 스키마를 지정
struts.locale=en_US
struts.i18n.encoding=UTF-8
#multipart/form-data로 인코딩된 HTTP POST 요청을 처리하는 파서 정의
Struts.multipart.parser=Jakarta
#임시 디렉토리 지정, 기본값은 javax.servlet.context.tmpdir 값을 사용한다.
Struts.multipart.saveDir=
#파일업로드 최대 사이즈
Struts.multipart.maxSize=2097152
[default.properties]
### START SNIPPET: complete_file
### Struts default properties
###(can be overridden by a struts.properties file in the root of the classpath)
###
### Specifies the Configuration used to configure Struts
### one could extend org.apache.struts2.config.Configuration
### to build one's customize way of getting the configurations parameters into Struts
# struts.configuration=org.apache.struts2.config.DefaultConfiguration
### This can be used to set your default locale and encoding scheme
# struts.locale=en_US
struts.i18n.encoding=UTF-8
### if specified, the default object factory can be overridden here
### Note: short-hand notation is supported in some cases, such as "spring"
### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here
# struts.objectFactory = spring
### specifies the autoWiring logic when using the SpringObjectFactory.
### valid values are: name, type, auto, and constructor (name is the default)
struts.objectFactory.spring.autoWire = name
### indicates to the struts-spring integration if Class instances should be cached
### this should, until a future Spring release makes it possible, be left as true
### unless you know exactly what you are doing!
### valid values are: true, false (true is the default)
struts.objectFactory.spring.useClassCache = true
### if specified, the default object type determiner can be overridden here
### Note: short-hand notation is supported in some cases, such as "tiger" or "notiger"
### Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here
### Note: if you have the xwork-tiger.jar within your classpath, GenericsObjectTypeDeterminer is used by default
### To disable tiger support use the "notiger" property value here.
#struts.objectTypeDeterminer = tiger
#struts.objectTypeDeterminer = notiger
### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data
# struts.multipart.parser=cos
# struts.multipart.parser=pell
struts.multipart.parser=jakarta
# uses javax.servlet.context.tempdir by default
struts.multipart.saveDir=
struts.multipart.maxSize=2097152
### Load custom property files (does not override struts.properties!)
# struts.custom.properties=application,org/apache/struts2/extension/custom
### How request URLs are mapped to and from actions
#struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper
### Used by the DefaultActionMapper
### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,do
struts.action.extension=action
### Used by FilterDispatcher
### If true then Struts serves static content from inside its jar.
### If false then the static content must be available at <context_path>/struts
struts.serve.static=true
### Used by FilterDispatcher
### This is good for development where one wants changes to the static content be
### fetch on each request.
### NOTE: This will only have effect if struts.serve.static=true
### If true -> Struts will write out header for static contents such that they will
### be cached by web browsers (using Date, Cache-Content, Pragma, Expires)
### headers).
### If false -> Struts will write out header for static contents such that they are
### NOT to be cached by web browser (using Cache-Content, Pragma, Expires
### headers)
struts.serve.static.browserCache=true
### Set this to false if you wish to disable implicit dynamic method invocation
### via the URL request. This includes URLs like foo!bar.action, as well as params
### like method:bar (but not action:foo).
### An alternative to implicit dynamic method invocation is to use wildcard
### mappings, such as <action name="*/*" method="{2}" class="actions.{1}">
struts.enable.DynamicMethodInvocation = true
### Set this to true if you wish to allow slashes in your action names. If false,
### Actions names cannot have slashes, and will be accessible via any directory
### prefix. This is the traditional behavior expected of WebWork applications.
### Setting to true is useful when you want to use wildcards and store values
### in the URL, to be extracted by wildcard patterns, such as
### <action name="*/*" method="{2}" class="actions.{1}"> to match "/foo/edit" or
### "/foo/save".
struts.enable.SlashesInActionNames = false
### use alternative syntax that requires %{} in most places
### to evaluate expressions for String attributes for tags
struts.tag.altSyntax=true
### when set to true, Struts will act much more friendly for developers. This
### includes:
### - struts.i18n.reload = true
### - struts.configuration.xml.reload = true
### - raising various debug or ignorable problems to errors
### For example: normally a request to foo.action?someUnknownField=true should
### be ignored (given that any value can come from the web and it
### should not be trusted). However, during development, it may be
### useful to know when these errors are happening and be told of
### them right away.
struts.devMode = false
### when set to true, resource bundles will be reloaded on _every_ request.
### this is good during development, but should never be used in production
struts.i18n.reload=false
### Standard UI theme
### Change this to reflect which path should be used for JSP control tag templates by default
struts.ui.theme=xhtml
struts.ui.templateDir=template
#sets the default template type. Either ftl, vm, or jsp
struts.ui.templateSuffix=ftl
### Configuration reloading
### This will cause the configuration to reload struts.xml when it is changed
struts.configuration.xml.reload=false
### Location of velocity.properties file. defaults to velocity.properties
struts.velocity.configfile = velocity.properties
### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext
struts.velocity.contexts =
### Location of the velocity toolbox
struts.velocity.toolboxlocation=
### used to build URLs, such as the UrlTag
struts.url.http.port = 80
struts.url.https.port = 443
### possible values are: none, get or all
struts.url.includeParams = get
### Load custom default resource bundles
# struts.custom.i18n.resources=testmessages,testmessages2
### workaround for some app servers that don't handle HttpServletRequest.getParameterMap()
### often used for WebLogic, Orion, and OC4J
struts.dispatcher.parametersWorkaround = false
### configure the Freemarker Manager class to be used
### Allows user to plug-in customised Freemarker Manager if necessary
### MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager
#struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager
### See the StrutsBeanWrapper javadocs for more information
struts.freemarker.wrapper.altMap=true
### configure the XSLTResult class to use stylesheet caching.
### Set to true for developers and false for production.
struts.xslt.nocache=false
### A list of configuration files automatically loaded by Struts
struts.configuration.files=struts-default.xml,struts-plugin.xml,struts.xml
### Whether to always select the namespace to be everything before the last slash or not
struts.mapper.alwaysSelectFullNamespace=false
### END SNIPPET: complete_file
댓글 없음:
댓글 쓰기