Action (1)

💻 Programming/JSP

[JSP] Actions ( 액션 )

JSP actions을 이용하면 동적으로 파일을 삽입하거나 자바빈 컴포넌트를 재사용하거나 웹브라우저를 보고있는 사용자를 다른 페이지로 포워딩시키거나 자바플러그인을 위한 HTML을 생성할 수도 있습니다.

문법은 아래와 같습니다. 

<jsp:action_name attribute="value" />

Action 요소는 기본적으로 미리 정의되어있는 기능들입니다.

SyntaxPurpose
jsp:includeIncludes a file at the time the page is requested
jsp:useBeanFinds or instantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines dynamically defined XML element's attribute.
jsp:bodyDefines dynamically defined XML element's body.

 

jsp:text

Use to write template text in JSP pages and documents.


Common Attributes ( 공통 속성 )

모든 액션 요소들에 적용되는 공통속성이 두개가 있습니다.  id 속성과 scope 속성입니다.

  • Id :  id 속성은 뭐 두말할 필요도 없는 속성이죠. Action 요소의 유니크한 id를 말합니다. 주민번호같은거죠. 그리고 JSP page내에서 이 id를 이용해서 객체로 접근이 가능합니다. Action 어떤 객체의 인스턴스를 생성하였다면 묵시적으로 정의되어있는 객체인 PageContext를 통해서 액션 id 값으로 생성된 객체를 참조할 수 있습니다. 

  • scope : Action 요소의 생명주기를 지정하는 속성입니다.  id 속성과 scope 속성은 직접적으로 연결되어 있습니다. 해당 id 를 갖는 객체의 생명주기를 결정하는 속성이기 때문이죠. scope 속성은 다음 네가지 값을 가질 수 있습니다. (a) page, (b)request, (c)session, and (d) application.
     

The <jsp:include> Action

페이지에 파일을 추가하는 액션이죠. 

문법은 아래와 같습니다. 

<jsp:include page="relative URL" flush="true" />

 include directive와는 다르게 페이지가 요청이 될 때 파일을 삽입합니다. include directive의 경우에는 페이지가 로드(번역)될 때 파일을 삽입하죠. 

 

include action과 관련된 속성들은 아래와 같습니다.

AttributeDescription
pageThe relative URL of the page to be included.
flushThe boolean attribute determines whether the included resource has its buffer flushed before it is included.

Example:

date.jsp  

<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>

main.jsp  

<html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page="date.jsp" flush="true" /> </center> </body> </html>

 

 

실행 결과는 아래와 같습니다.

The include action Example

Today's date: 12-Sep-2010 14:54:22

The <jsp:useBean> Action

useBean 액션은 다양하게 사용될 수 있다. 특정 객체를 검색을 해서 얻어오는데 만약 검색이 실패하면 객체를 생성을 해줍니다.  

문법은 아래와 같습니다. 

<jsp:useBean id="name" class="package.class" />

빈 클래스가 한번 로드되면 빈 프로퍼티를 수정하거나 읽어오기 위해서 jsp:setProperty 와 jsp:getProperty 액션을 사용할 수 있습니다. 

 

useBean action과 관련된 속성들은 아래와 같습니다. 

AttributeDescription
classDesignates the full package name of the bean.
typeSpecifies the type of the variable that will refer to the object.
beanNameGives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.

 

The <jsp:setProperty> Action

setProperty 액션은 빈의 프로퍼티를 수정합니다. Bean 이 당연히 정의가 되어있어야 겠죠.  

이 액션은 두가지 방법으로 사용됩니다. 

1.  jsp:useBean 액션 이후에, 외부에서 사용되는 방법

<jsp:useBean id="myName" ... /> ... <jsp:setProperty name="myName" property="someProperty" .../>

 

2. jsp:useBean 액션 내부에서 사용되는 방법

<jsp:useBean id="myName" ... > ... <jsp:setProperty name="myName" property="someProperty" .../> </jsp:useBean>

1번과 같이 사용할 경우에는 Bean이 새로 생성되거나 기존의 Bean이 검색되거나 상관없이 모두 jsp:setProperty 가 실행이 되지만 2번처럼 사용할 경우에는 새로운 Bean이 생성되었을 경우에만 실행이 됩니다.  

 

setProperty 액션에서 사용되는 속성들은 아래와 같습니다.

 

AttributeDescription
nameDesignates the bean whose property will be set. The Bean must have been previously defined.
propertyIndicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
valueThe value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored.
paramThe param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.

The <jsp:getProperty> Action

getProperty 액션은 Bean의 프로퍼티를 읽어와서 String으로 변환하여 반환해줍니다.  

getProperty 액션은 두개의 속성만 가지고 있습니다. 사용법과 속성은 아래와 같습니다.  

<jsp:useBean id="myName" ... /> ... <jsp:getProperty name="myName" property="someProperty" .../>

getProperty 액션에서 사용되는 속성들은 아래와 같습니다. 주의할 점은 두개의 속성 모두 필수로 사용되어야 한다는 것입니다.

 

AttributeDescription
nameThe name of the Bean that has a property to be retrieved. The Bean must have been previously defined.
propertyThe property attribute is the name of the Bean property to be retrieved.

Example:

테스트 빈을 만들어 봅시다.

/* File: TestBean.java */ package action; public class TestBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }

그리고 컴파일해서 TestBean.class 파일을 만들고 C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action 폴더에 복사해서 넣습니다. 그리고 CLASSPATH 변수에 폴더경로를 넣어줍니다.

이제 main.jsp 파일을 만들어서 빈을 생성하고 set/getProperty액션을 사용해 봅시다. 

<html> <head> <title>Using JavaBeans in JSP</title> </head> <body> <center> <h2>Using JavaBeans in JSP</h2> <jsp:useBean id="test" class="action.TestBean" /> <jsp:setProperty name="test" property="message" value="Hello JSP..." /> <p>Got message....</p> <jsp:getProperty name="test" property="message" /> </center> </body> </html>

결과는 아래처럼 나와야 겠죠. 

Using JavaBeans in JSP

Got message....
Hello JSP...

The <jsp:forward> Action

forward 액션은 현재 페이지의 액션을 종료하고 요청을 다른 페이지나 서블릿으로 포워딩합니다.

문법은 아래와 같습니다.

<jsp:forward page="Relative URL" />

이 액션의 속성은 달랑 한개네요.

AttributeDescription
pageShould consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet.

Example:

 date.jsp

<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>

main.jsp

<html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:forward page="date.jsp" /> </center> </body> </html>

root 디렉토리에 이 파일들을 넣고 main.jsp를 요청해보세요.

메인페이지의 컨텐트를 제외한 포워딩된 페이지에서의출력은 아래처럼 나올 것입니다.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action

plugin 액션은 JSP페이지에 자바 컴포넌트를 삽입하기 위해서 사용됩니다. 브라우저 타입을 결정하고, 필요한경우 <object> 또는 <embed> 태그를 추가합니다.

필요한 플러그인이 존재하지 않으면 플러그인을 다운로드하고 자바컴포넌트를 실행시킵니다. 그 Java component는 Applet이 될 수도 있고  JavaBean이 될 수도 있습니다.  

plugin action 은 Java components를 formatting하기 위해서 공통 HTML 태그에 상응하는 여러 속성들을 가지고 있습니다.  <param> 요소 또한 Applet 이나 Bean에 파라미터를 전달하기 위해서 사용될 수 있습니다.

 

<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class" width="60" height="80"> <jsp:param name="fontcolor" value="red" /> <jsp:param name="background" value="black" /> <jsp:fallback> Unable to initialize Java Plugin </jsp:fallback> </jsp:plugin>

여기서 <fallback> 요소는 자바컴포넌트 실행시 오류가 발생했을 때 오류 메시지를 사용자에게 전달해주는 역할을 합니다. 

 <jsp:element>,  <jsp:attribute>,  <jsp:body> Action

<jsp:element>, <jsp:attribute> and <jsp:body> 액션들은 XML 요소를 동적으로 정의하기위해서 사용됩니다. 동적이라는 것은 컴파일 시가 아니라 런타임에 요청에 의해서 만들어진 다는 것을 의미합니다. 

아래는 간단한 예제입니다. 

<%@page language="java" contentType="text/html"%> <html xmlns="http://www.w3c.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <jsp:element name="xmlElement"> <jsp:attribute name="xmlElementAttr"> Value for the attribute </jsp:attribute> <jsp:body> Body for XML element </jsp:body> </jsp:element> </body> </html>

실행시키면 동적으로 아래와같은 HTML파일이 만들어집니다. 

<html xmlns="http://www.w3c.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <xmlElement xmlElementAttr="Value for the attribute"> Body for XML element </xmlElement> </body> </html>

The <jsp:text> Action

<jsp:text> 액션은 JSP 페이지와 문서를 위한 템플릿 텍스트를 쓰기위해 사용될 수 있습니다.

문법은 아래와 같습니다. 

<jsp:text>Template data</jsp:text>

바디에는 다른 요소를 가질 수 없습니다. 오로지 텍스트와 EL 표현식만 들어갈 수 있습니다. XML files에서는 ${whatever > 0}와 같은 표현식은 쓸 수 없습니다 비교연산자 > 가 사용될 수 없기 때문이죠. 대신 ${whatever gt 0} 와 같이 쓰거나 CDATA 를 이용할 수도 있습니다.

<jsp:text><![CDATA[<br>]]></jsp:text>

 XHTML을 위한 DOCTYPE 선언을 추가할 때에도 아래처럼  <jsp:text> 요소를 이용할 수 있습니다. 

<jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">]]> </jsp:text> <head><title>jsp:text action</title></head> <body> <books><book><jsp:text> Welcome to JSP Programming </jsp:text></book></books> </body> </html>

 <jsp:text> 액션 없이 한번 실행해보세요.

 

 

 

 

Reference : http://www.tutorialspoint.com/jsp/jsp_actions.htm