분류 전체보기 (356)

💻 Programming/JSP

[JSP] Response Object ( Server Response, Auto Refresh )

Web server가 HTTP request에 대한 응답을 브라우저에 보낼때 그 응답은 전형적으로 상태정보와 몇몇 응답 헤더들 그리고 빈 줄 그리고 문서로 이루어져 있다. 보통 아래처럼 응답이 구성된다.

HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... ( 빈 줄 ) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>

상태정보를 표시하는 첫번째 줄은 HTTP 버전 (위 예제에서는 HTTP/1.1 ), 상태코드 ( 위 예제에서는 200 ), 그리고 상태코드에 맞는 짧은 메시지 (위 예에서는 OK )로 구성됩니다.

아래 테이블의 내용은 HTTP 1.1 응답헤더의 유용한 정보들입니다.

 

HeaderDescription
AllowThis header specifies the request methods (GET, POST, etc.) that the server supports.
Cache-ControlThis header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (nonshared) caches and no-cache means document should never be cached.
ConnectionThis header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections.
Content-DispositionThis header lets you request that the browser ask the user to save the response to disk in a file of the given name.
Content-EncodingThis header specifies the way in which the page was encoded during transmission.
Content-LanguageThis header signifies the language in which the document is written. For example en, en-us, ru, etc.
Content-LengthThis header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-TypeThis header gives the MIME (Multipurpose Internet Mail Extension) type of the response document.
ExpiresThis header specifies the time at which the content should be considered out-of-date and thus no longer be cached.
Last-ModifiedThis header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests.
LocationThis header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document.
RefreshThis header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed.
Retry-AfterThis header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request.
Set-CookieThis header specifies a cookie associated with the page.


HttpServletResponse

 HttpServletResponse 객체에서 제공하는 메소드들은 아래와 같습니다.  

 

S.N.Method & Description
1String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
4boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7void addHeader(String name, String value)
Adds a response header with the given name and value.
8void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9void flushBuffer()
Forces any content in the buffer to be written to the client.
10void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
13void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
15void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
17void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
18void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
19void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20void setHeader(String name, String value)
Sets a response header with the given name and value.
21void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
23void setStatus(int sc)
Sets the status code for this response.


HTTP Header Response 예제

아래 소스는 디지털 시계를 보여주기 위해서 Refresh헤더에 5초마다 새로고침하도록 setIntHeader() 메소드를 이용해서 값을 세팅하는 것을 보여주고 있습니다.

<%@ page import="java.io.*,java.util.*" %> <html> <head> <title>Auto Refresh Header Example</title> </head> <body> <center> <h2>Auto Refresh Header Example</h2> <% // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; out.println("Current Time is: " + CT + "\n"); %> </center> </body> </html>

main.jsp 에 위 소스를 넣고 웹브라우저에서 요청하면 아래처럼 5초마다 새로고침되는 디지털 시계를 보실 수 있으실거에요.  

Auto Refresh Header Example

Current Time is: 9:44:50 PM

 

 

 

 

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

 

'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Filters ( 필터 사용하기 )  (0) 2019.02.15
[JSP] Form 데이타 처리  (0) 2019.02.15
[JSP] Request Object ( Client Request )  (0) 2019.02.15
[JSP] Implicit Objects ( 묵시적 객체들 )  (0) 2019.02.15
[JSP] Actions ( 액션 )  (0) 2019.02.15

💻 Programming/JSP

[JSP] Request Object ( Client Request )

사용자가 웹브라우저에서 웹페이지를 요청하면 웹브라우저는 웹서버로 많은 정보를 전달하게 되는데 이 정보들은 모두 HTTP request 의 헤더 내에 포함되어 전달된다. HTTP Protocol 에 대한 내용은 링크를 참조하기 바란다.

 

아래 내용은 브라우저에서 웹서버쪽으로 보내는 정보 중에 중요한 헤더 정보를 간추린 것입니다.

 

HeaderDescription
AcceptThis header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities.
Accept-CharsetThis header specifies the character sets the browser can use to display the information. For example ISO-8859-1.
Accept-EncodingThis header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities.
Accept-LanguageThis header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc.
AuthorizationThis header is used by clients to identify themselves when accessing password-protected Web pages.
ConnectionThis header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used
Content-LengthThis header is applicable only to POST requests and gives the size of the POST data in bytes.
CookieThis header returns cookies to servers that previously sent them to the browser.
HostThis header specifies the host and port as given in the original URL.
If-Modified-SinceThis header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available.
If-Unmodified-SinceThis header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date.
RefererThis header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2.
User-AgentThis header identifies the browser or other client making the request and can be used to return different content to different types of browsers.



HttpServletRequest 

 HttpServletRequest 객체에서 제공하는 메소드들은 아래와 같습니다.

S.N.Method & Description
1Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.
2Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this request.
3Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.
4Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request.
5HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
6HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.
7Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header
8Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
9ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.
10String getAuthType()
Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected
11String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
12String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
13String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14String getHeader(String name)
Returns the value of the specified request header as a String.
15String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
16String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
17String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
18String getProtocol()
Returns the name and version of the protocol the request.
19String getQueryString()
Returns the query string that is contained in the request URL after the path.
20String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
21String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.
23String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
24String getRequestedSessionId()
Returns the session ID specified by the client.
25String getServletPath()
Returns the part of this request's URL that calls the JSP.
26String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
27boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
28int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known.
29int getIntHeader(String name)
Returns the value of the specified request header as an int.
30int getServerPort()
Returns the port number on which this request was received.


HTTP Header Request 예제

아래는 HttpServletRequest의 getHeaderNames()메소드 예제입니다. 이 메소드는 현재 요청에 대한 HTTP header 정보를 읽어와서 Enumeration을 반환합니다. Enumeration을 얻어오면 우리는 hasMoreElements() 메소드를 이용해서 루프를 돌면서 nextElement() 메소드를 이용해서 헤더명을 가져올 수 있습니다. 아래 예제는 그렇게 얻어온 헤더명을 이용해서 해당 헤더명에 대한 실제 값까지 얻어와서 화면에 출력하는 기능을 하는 페이지입니다. 

<%@ page import="java.io.*,java.util.*" %> <html> <head> <title>HTTP Header Request Example</title> </head> <body> <center> <h2>HTTP Header Request Example</h2> <table width="100%" border="1" align="center"> <tr bgcolor="#949494"> <th>Header Name</th><th>Header Value(s)</th> </tr> <% Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("<tr><td>" + paramName + "</td>\n"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>\n"); } %> </table> </center> </body> </html>

위 소스코드를 main.jsp 파일에 넣고 웹브라우저에서 요청해보세요. 아래와 같은 결과를 얻을 수 있을것입니다.


HTTP Header Request Example

Header NameHeader Value(s)
accept*/*
accept-languageen-us
user-agentMozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8)
accept-encodinggzip, deflate
hostlocalhost:8080

connection

Keep-Alive
cache-control

no-cache

 

 

 

 

 

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

 

💻 Programming/JSP

[JSP] Implicit Objects ( 묵시적 객체들 )

JSP Implicit Objects는 Java 객체들입니다. 명시적으로 개발자가 선언하지 않아도 JSP Container에서 제공하는 객체들이라고 보시면 되겠습니다. 그래서 JSP Implicit Objects 를 pre-defined 변수라고 하기도 합니다.

 

JSP 는 아홉가지의 Implicit Objects를 지원합니다. 저도 아는 객체들이 눈에 보이네요.

 

ObjectDescription
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.


The request Object:

request 객체는 javax.servlet.http.HttpServletRequest 객체의 인스턴스입니다. 사용자가 페이지를 요청할 때마다 JSP engine 이 해당 요청에 대한 새로운 request객체를 생성합니다. request 객체는 HTTP header 정보를 얻어오기위한 메소드를 제공합니다. form data, cookies, HTTP methods같은 정보들이 헤더정보에 있겠죠.

request 객체와 관련된 메소드들에 대한 정보 및 사용법은 오른쪽 링크에서 확인하실 수 있습니다.  JSP - Client Request.


The response Object:

response 객체는 javax.servlet.http.HttpServletResponse 객체의 인스턴스입니다. 서버가 request 객체를 만드는 것처럼, 클라이언트로 보내기위한 response 객체도 만듭니다.

response 객체는 또한 새로운 HTTP헤더 생성을 다루기위한 인터페이스를 정의합니다. 이 객체를 통해서 JSP 개발자들은 쿠키, 날짜 스탬프,  HTTP 상태 코드등을 추가할 수 있습니다. 

response 객체와 관련된 메소드들에 대한 정보 및 사용법은 우측 링크에서 확인하실 수 있습니다.  JSP - Server Response.


The out Object:

out 객체는 javax.servlet.jsp.JspWriter 객체의 인스턴스이며 content를 response안에 보내기 위해서 사용됩니다.

처음의 JspWriter 객체는 페이지의 버퍼 사용여부에 따라 다르게 초기화됩니다.  Buffering 기능은 page 디렉티브의 buffered='false' 속성을 통해서 쉽게 off 할 수 있습니다. JspWriter 객체는 java.io.PrintWriter 클래스와 거의 동일한 메소드들을 가지고 있습니다. 하지만 JspWriter는 추가적으로 버퍼링을 다루기 위한 메소드들을 가지고 있습니다. PrintWriter 객체와는 다르게 JspWriter 는 IOExceptions을 던집니다.

 

 boolean, char, int, double, object, String, etc. 을 쓰고싶을 때 사용하는 메소드는 아래와 같습니다.

MethodDescription
out.print(dataType dt)Print a data type value
out.println(dataType dt)Print a data type value then terminate the line with new line character.
out.flush()Flush the stream.


The session Object:

session객체는 javax.servlet.http.HttpSession의 인스턴스죠.  Java Servlets의 세션과 동일한 역할을 한다고 보시면 됩니다.

session 객체는 사용자가 여러번 요청을 하게 될 때 그 요청들 사이에 세션을 추적 및 관리하기 위해서 사용됩니다.  

session 객체의 사용법은 우측 링크에서 확인하실 수 있습니다.  JSP - Session Tracking.


The application Object:

application 객체는 ServletContext객체의 wrapper객체입니다. 실제로는 javax.servlet.ServletContext 객체의 인스턴스입니다.

 이 객체는 JSP page 생명주기 전체를 대표한다고 보시면 됩니다. 애플리케이션이 종료되기 전까지 살아있는 객체죠. JSP 페이지가 초기화될 때 생성되고  jspDestroy()메소드에 의해 JSP페이지가 소멸될 때 이 객체도 소멸됩니다.

 application 객체에 속성을 추가함으로써 해당 애플리케이션을 구성하는 모든 JSP 파일들이 이곳에 접근할 수 있는 권한이 생기게 됩니다.

Application 객체의 간단한 사용법은 우측 링크에서 확인하실 수 있습니다.  JSP - Hits Counter


The config Object:

config 객체는 javax.servlet.ServletConfig 의 인스턴스입니다.  

이 객체는 JSP 개발자가 Servlet 이나 JSP 엔진 초기화 파라미터 ( paths 또는 file 위치 등 )에 접근할 수 있도록 해줍니다.

많이 쓰이지 않는 객체이며 아마 쓰게 된다면 아래와 같이 쓰는 것 말고는 정말 쓸일이 없을 것입니다. 


config.getServletName();


이건 서블릿명을 얻어오는 메소드입니다. WEB-INF\web.xml 파일의   <servlet-name> 요소에 들어있는 이름을 얻어오는 것입니다. 


The pageContext Object:

pageContext 객체는  javax.servlet.jsp.PageContext 객체의 인스턴스입니다.   pageContext 객체는 JSP page 전체를 대표합니다.

 이 객체는 페이지 정보를 얻어오기 위한 수단으로 사용됩니다.  

이 객체는 각 요청마다 request 와 response객체로의 래퍼런스를 저장합니다. application, config, session, 그리고 out 객체들은 이 객체의 속성에 접근해서 얻어올 수 있습니다.  pageContext 객체는 또한 해당 JSP page에서 발생된 directives의 정보를 저장하고 있습니다. ( buffering 정보,  errorPageURL, 그리고 page scope같은 정보들 말이죠 ).

 PageContext 클래스는 PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, 그리고 APPLICATION_SCOPE 필드들을 정의합니다. 40개 이상의 메소드를 제공하며 그 중 반은 javax.servlet.jsp.JspContext 클래스에서 상속받은 메소드들입니다.

가장 중요한 메소드 중 하나는 removeAttribute인데 이 메소드는  하나 또는 두개의 파라미터를 받습니다. pageContext.removeAttribute ("attrName") 는 모든 scope에서 attrName 속성을 제거합니다. 아래에 나온 문장은 page scope에서만 해당 속성을 제거합니다. 

 

  pageContext.removeAttribute("attrName", PAGE_SCOPE);


pageContext 객체에 대한 사용법은 우측 링크에서 확인하실 수 있습니다. JSP - File Uploading.


The page Object:

실제 페이지를 참조하고 있는 객체입니다. JSP page전체를 대표하는 객체라고 생각하시면 됩니다..

이 페이지 객체는 실제로 자바에서 나오는 this 객체의 동의어라고 보시면 되겠습니다.  


The exception Object:

exception 객체는 wrapper 객체입니다. 이전 페이지에서 던져진 exception을 가지고 있죠.  뭐 이거야 자바를 하신 분들이라면 예외처리를 위한 객체라고 금방 아실 겁니다. 뭐 더 설명할게 없네요.

이 객체에 대한 사용법은 우측 링크에서 확인하실 수 있습니다. JSP - Exception Handling.

 

 

 

 

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

💻 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 

💻 Programming/JSP

[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )

커스텀 태그를 갖고 있는 JSP페이지가 서블릿으로 변환될 때, 그 태그는 tag handler라고 불리는 객체의 operation으로 변환됩니다. 그리고나서 JSP페이지의 서블릿이 실행될 때 웹컨테이너가 그 opreation을 호출하게 되는 거죠.

JSP tag extensions 는 JSP에 직접 추가할 수 있는 새로운 태그를 만들 수 있도록 해줍니다. JSP 2.0 specification에는 이런 커스텀 태그를 쓰기위한 Simple Tag Handlers 를 제공합니다.

customer tag를 쓰려면 단순히 SimpleTagSupport 를 상속하고  doTag()메소드를 오버라이드 하면 됩니다.  

 

Create "Hello" Tag ( 사용자 정의 태그 생성하기 )

아래처럼  <ex:Hello> 를 쓰고싶다고 가정해봅시다. body 태그도 없이 말입니다. 

<ex:Hello />

custom JSP tag를 만들려면 태그 핸들러 Java class 부터 만들어야 합니다. 

아래처럼 자바 코딩을 해봅시다. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println("Hello Custom Tag!"); } }

위 코드는 doTag() 메소드에서 getJspContext() method를 이용해서 현재 JspContext object를 얻어오고 "Hello Custom Tag!"메시지를  JspWriter 객체로 보내는 기능을 넣은 것입니다.

 

이제 이 소스파일을 컴파일해서 class파일로 만들고 이 클래스 파일을 환경변수 CLASSPATH에 지정되어있는 곳에 복사해서 넣어주세요. 마지막으로 아래와 같은 태그라이브러리 파일을 생성하면 됩니다. 위치는 아래와 같습니다.

 <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib>

이제 JSP파일에서 이 Hello 태그를 사용해 봅시다.  

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello/> </body> </html>

이제 만들어진 JSP파일을 웹브라우저에서 요청해 보세요. 아래와 같은 결과가 나올 것입니다. 

Hello Custom Tag!


Accessing the Tag Body ( 태그 바디에 접근하기 )

커스텀 태그도 일반 HTML태그처럼 시작태그와 종료태그 사이에 바디부분을 추가할 수 있습니다.

<ex:Hello> This is message body </ex:Hello>

위에서 작성했던 자바소스를 아래처럼 변경합니다. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } }

여기서는 StringWriter로 읽어들인 후에 읽어들인 값을 JspWriter에서 처리하는 방식입니다.

TLD 파일도 아래처럼 변경되어야 합니다.

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> </tag> </taglib>

JSP파일은 아래처럼 변경합니다.

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello> This is message body </ex:Hello> </body> </html>

결과는 아래처럼 나와야 합니다.

This is message body


Custom Tag Attributes ( 커스텀 태그의 속성 )

 custom tags는 속성과 함께 사용될 수도 있습니다.  속성값을 받으려면 custom tag class는 setter methods를 구현해야 합니다. JavaBean setter methods와 동일하게 말이죠. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { private String message; public void setMessage(String msg) { this.message = msg; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { if (message != null) { /* Use message from attribute */ JspWriter out = getJspContext().getOut(); out.println( message ); } else { /* use message from the body */ getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } }

속성명은 "message"이고 세터메소드는 당연히 setMessage()가 되겠죠. 이제 이 속성을 TLD file에 추가합니다. <attribute> 요소를 이용해서 말이죠.

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> </taglib>

JSP파일에 메시지 속성을 이용한 태그를 추가하세요. 

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello message="This is custom tag" /> </body> </html>

결과는 아래처럼 나올 것입니다.

This is custom tag

 

 

속성에는 아래와 같은 프로퍼티들이 들어갈 수 있습니다.

PropertyPurpose
nameThe name element defines the name of an attribute. Each attribute name must be unique for a particular tag.
requiredThis specifies if this attribute is required or optional. It would be false for optional.
rtexprvalueDeclares if a runtime expression value for a tag attribute is valid
typeDefines the Java class-type of this attribute. By default it is assumed as String
descriptionInformational description can be provided.
fragmentDeclares if this attribute value should be treated as a JspFragment.

 

속성 관련 프로퍼티를 설정하는 방법은 아래와 같습니다.

.....
    <attribute>
      <name>attribute_name</name>
      <required>false</required>
      <type>java.util.Date</type>
      <fragment>false</fragment>
    </attribute>
.....

두 개 이상의 속성을 사용한다면 TLD파일에 아래처럼 추가하면 됩니다.

..... <attribute> <name>attribute_name1</name> <required>false</required> <type>java.util.Boolean</type> <fragment>false</fragment> </attribute> <attribute> <name>attribute_name2</name> <required>true</required> <type>java.util.Date</type> </attribute>

.....





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


'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Implicit Objects ( 묵시적 객체들 )  (0) 2019.02.15
[JSP] Actions ( 액션 )  (0) 2019.02.15
[JSP] Directives ( 디렉티브 )  (0) 2019.02.15
[JSP] JSP 생명 주기 ( life cycle )  (0) 2019.02.15
[JSP] 조건문, 반복문  (0) 2019.02.15

💻 Programming/JSP

[JSP] Directives ( 디렉티브 )

JSP directives 는 container에 방향이나 명령을 제공합니다. 특정 부분에 대해서 어떻게 처리를 해야 한다는 것을 말이죠

JSP directive는 servlet class 전반에 걸쳐서 영향을 미칩니다.  

문법은 아래와 같습니다. 

 

<%@ directive attribute="value" %>

Directives 는 여러개의 속성을 가질 수 있습니다. 속성과 속성 사이는 쉼표로 구분을 하고 key-value 페어로 값을 지정할 수 있습니다. 

 @ 와 directive명 사이의 빈칸 그리고 마지막 속성과 %> 사이의 빈칸은 옵션입니다. 있어도 되고 없어도 된다는 거죠. 

 

디렉티브 태그는 총 세가지 종류가 있습니다.  

DirectiveDescription
<%@ page ... %>페이지 종속적인 속성들을 정의합니다. scripting language, error page, and buffering requirements 같은 것들을 말합니다.
<%@ include ... %>로드될 때 동적으로 파일을 include합니다.
<%@ taglib ... %>페이지에서 사용될 사용자정의 액션을 포함하는 태그 라이브러리를 선언합니다. 


The page Directive

page directive 는 현재 JSP 페이지와 관련된 명령어들을 컨테이너에 제공합니다. 또한 페이지 디렉티브는 JSP페이지 아무데나 넣어도 관계가 없습니다. 하지만 일반적으로 JSP페이지의 가장 위쪽에 정의합니다.

기본문법은 아래와 같습니다.

<%@ page attribute="value" %>

XML형식은 아래와 같습니다.

<jsp:directive.page attribute="value" />

Attributes ( 속성 )

페이지 디렉티브와 관련된 속성과 목적은 아래와 같습니다. 

AttributePurpose
bufferSpecifies a buffering model for the output stream.
autoFlushControls the behavior of the servlet output buffer.
contentTypeDefines the character encoding scheme.
errorPageDefines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPageIndicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extendsSpecifies a superclass that the generated servlet must extend
importSpecifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.
infoDefines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafeDefines the threading model for the generated servlet.
languageDefines the programming language used in the JSP page.
sessionSpecifies whether or not the JSP page participates in HTTP sessions
isELIgnoredSpecifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabledDetermines if scripting elements are allowed for use.

속성에 대한 자세한 내용은 이곳에서 확인하실 수 있습니다. 


The include Directive:

include directive는 페이지가 로드될 때 동적으로 다른 파일을 include시키기 위해서 사용됩니다. 쉽게말하면 다른 페이지에 따로 기능을 구현해놓고 이것을 필요로 하는 JSP페이지에서 include하여 해당 기능을 사용하기 위해서 있는겁니다. 

역시 위치는 JSP페이지 내 아무곳에나 가져다 놓으시면 됩니다. 

문법은 아래와 같습니다. 

<%@ include file="relative url" >

file속성의 value로 들어가는 값은 파일의 상대경로라는 점을 주의하시면 됩니다.  

 

XML형식은 아래와 같습니다.

<jsp:directive.include file="relative url" />

Example:

예제를 한번 볼까요? ROOT 디렉토리에 아래처럼 header, footer, main JSP파일을 만들어 봅시다.

 

header.jsp

<%! int pageCount = 0; void addCount() { pageCount++; } %> <% addCount(); %> <html> <head> <title>The include Directive Example</title> </head> <body> <center> <h2>The include Directive Example</h2> <p>This site has been visited <%= pageCount %> times.</p> </center> <br/><br/>

footer.jsp

<br/><br/> <center> <p>Copyright © 2010</p> </center> </body> </html>

main.jsp

<%@ include file="header.jsp" %> <center> <p>Thanks for visiting my page.</p> </center> <%@ include file="footer.jsp" %>

그리고 main.jsp를 웹브라우저에서 요청을 합니다. 그러면 아래와 같은 결과가 나올것입니다. main.jsp에서는 include로 다른 jsp파일만 추가를 했을 뿐인데 눈에 보이는게 많죠? include된 jsp파일들에서 뿌리는 결과가 main에 모두 합쳐져서 나오게 되는 것입니다. 

The include Directive Example

This site has been visited 1 times.



Thanks for visiting my page.



Copyright © 2010

 

새로고침할 때마다 방문 카운트가 증가하는게 보이시나요?? ^___^ 

 


The taglib Directive:

태그 라이브러리는 사용자 정의 태그입니다.  

taglib directive는 JSP페이지에서 사용자 정의 태그를 사용하겠다고 정의하기 위해 사용합니다.

 

문법은 아래와 같습니다.

<%@ taglib uri="uri" prefix="prefixOfTag" >

XML형식은 아래와 같습니다.

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />

Example:

예제를 한번 봅시다. 

 custlib tag library 가 hello 태그를 가지고 있다고 합시다. hello tag 를 mytag​라는 prefix와 함께 사용하고 싶을 때(  <mytag:hello> ) 는 아래처럼 사용할 수 있습니다.

<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>
<html>
<body>
<mytag:hello/>
</body>
</html>

 <mytag:hello> 를 호출함으로써 hello 태그에 미리 정의되어있는 코드를 써먹을 수 있는거죠.

 

그럼 hello 태그가 어떻게 정의되어있는지 한번 볼까요?

 

지금 말고 다음 포스팅에서 보도록 하죠. 생각보다 내용이 많거든요 ㅋㅋ 참고로 여기서 사용된 hello 태그를 커스텀 태그라고 합니다.

 

 

 

그럼 좋은 하루 되세요 ^___^

 

 

 

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

'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Actions ( 액션 )  (0) 2019.02.15
[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )  (0) 2019.02.15
[JSP] JSP 생명 주기 ( life cycle )  (0) 2019.02.15
[JSP] 조건문, 반복문  (0) 2019.02.15
[JSP] JSP 시작하기  (0) 2019.02.15

💻 Programming/JSP

[JSP] JSP 생명 주기 ( life cycle )

 JSP 생명 주기라 함은 JSP 생성에서부터 소멸까지의 과정을 말하는데 이는 서블릿 생명주기와 매우 유사하고 추가적으로 JSP를 컴파일 하는 과정만 추가된 것이라고 생각하면 된다.

큰 과정만 간추리면 다음과 같습니다. 

  • Compilation ( 컴파일 ) 

  • Initialization ( 초기화 ) 

  • Execution ( 실행 ) 

  • Cleanup ( 뒷정리 ) 

그림으로 보면 아래와 같습니다. 서블릿 생명주기에서 컴파일만 추가된 것이죠. 아래 그림에는 컴파일 과정은 생략되어있네요. 

JSP Compilation:

웹브라우저가 JSP를 요청하면 JSP engine 은 우선 요청한 JSP파일이 컴파일이 필요한지를 검사합니다. 만약 한번도 컴파일 된적이 없거나 수정된 부분이 있다면 JSP engine 이 컴파일을 하게 됩니다.  

컴파일 과정은 아래와 같습니다.

  • Parsing the JSP. ( JSP 파일 파싱 ) 

  • Turning the JSP into a servlet. ( JSP를 서블릿으로 변환 ) 

  • Compiling the servlet. ( 서블릿 컴파일 ) 

JSP Initialization ( 초기화 )

컨테이너가 JSP를 로드할 때 jspInit() 메소드를 호출합니다. 요청을 처리하기 전에 말이죠. 만약 특정 JSP에서 특수한 처리가 필요하다면 이 jspInit() 메소드를 오버라이드 하시면 됩니다. 

public void jspInit(){ // Initialization code... }

일반적으로 초기화는 서블릿 초기화처럼 한번만 실행이 됩니다, 이 초기화 과정에서 개발자들은 보통 데이타 베이스 커넥션을 맺고 파일을 열고 룩업 테이블을 생성하는 과정을 처리한다고 하네요.  

JSP Execution ( 실행 )

브라우저가 JSP 페이지를 요청하고 페이지가 로드되고 초기화가 됐다면 JSP engine은 _jspService() 메소드를 호출하게 됩니다.

 _jspService() 메소드는 HttpServletRequest와 HttpServletResponse 를 파라미터로 받습니다.

void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... }

JSP의 _jspService()메소드는 요청이 올때마다 한번씩 실행이 됩니다. 그리고 요청에 대한 응답을 생성하며 모든 종류의 HttpRequest방법 ( ie. GET, POST, DELETE, PUT, etc.) 에 대한 응답을 생성합니다. 

JSP Cleanup ( 뒷정리 )

 jspDestroy() 메소드는 서블릿을 소멸시키는 메소드와 동일한 개념이라고 보시면 됩니다. 이 메소드를 오버라이드해서 필요한 처리를 해주셔도 됩니다. 데이타 베이스 커넥션을 끊는다던지 파일을 닫는 것과 같은 일들을 말이죠.

 

 jspDestroy() 메소드는 아래처럼 간단하게 생겼습니다.

public void jspDestroy() { // Your cleanup code goes here. }

 

 

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

 



'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )  (0) 2019.02.15
[JSP] Directives ( 디렉티브 )  (0) 2019.02.15
[JSP] 조건문, 반복문  (0) 2019.02.15
[JSP] JSP 시작하기  (0) 2019.02.15
[JSP] JSP란?  (0) 2019.02.15

💻 Programming/JSP

[JSP] 조건문, 반복문

자, 오늘은 컨트롤 플로우 문법에 대해서 알아보도록 하겠습니다.  

컨트롤 플로우 문법이라함은 if와 같은 조건문과 for, while과 같은 루프문을 말합니다. 

1. If-Else

우선 if...else 문에 대해서 보도록 하죠.

<%! int day = 3; %>
<html> 
<head><title>IF...ELSE Example</title></head> 
<body>
<% if (day == 1 | day == 7) { %>
      <p> Today is weekend</p>
<% } else { %>
      <p> Today is not weekend</p>
<% } %>
</body> 
</html>

 

결과는 아래과 같습니다. 

Today is not weekend

왜 이렇게 나오는건지 한줄 한줄 살펴보겠습니다.

<%! int day = 3; %>

day라는 int 타입 변수에 3이라는 값을 할당했습니다.

그리고 body 태그 내에서 if-else 문을 이용하였는데 day 값이 1 (일요일) 이거나 7 (토요일)이면 "Today is weekend"를 출력했겠지만, 우리는 day 값에 3을 할당해주었으니 "Today is not weekend"가 출력되는 것입니다. 이때 주의할 점은 if-else 문 내에서 출력하고자 하는 태그 부분은 <% %> 안에 감싸지 않았다는 점입니다.

2. Switch - Case

이제 switch - case 문에 대해서 알아보죠. 

<%! int day = 3; %> 
<html>
	<head><title>SWITCH...CASE Example</title></head>
    <body> 
    	<% 
        	switch(day) { 
            	case 0: 
                	out.println("It\'s Sunday."); 
                	break; 
                case 1: 
                	out.println("It\'s Monday."); 
                    break; 
                case 2: 
                	out.println("It\'s Tuesday."); 
                    break; 
                case 3: 
                	out.println("It\'s Wednesday."); 
                	break;
                case 4:
                	out.println("It\'s Thursday.");
                    break;
                case 5:
                	out.println("It\'s Friday.");
                    break;
                default:
                	out.println("It's Saturday.");
            } 
        %>
    </body>
</html>

 

역시 결과는 아래와 같습니다. 

It's Wednesday.

3. For - Loop

이번에는 Loop 문법에 대해서 알아보도록 하겠습니다. 

<%! int fontSize; %> 
<html> 
	<head><title>FOR LOOP Example</title></head> 
    <body> 
    	<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %> 
        <p style="font-size:<%= fontSize %>rem"> JSP Tutorial </p> <%}%> 
	</body>
</html>

 

결과는 아래와 같습니다.

 

JSP Tutorial

JSP Tutorial

JSP Tutorial

 

4. While - Loop

3번에서 for 루프로 구현한 것을 이번에는 while루프를 이용해서 구현해보도록 하겠습니다.

<%! int fontSize; %> 
<html> 
	<head><title>WHILE LOOP Example</title></head> 
    <body> 
    	<%while ( fontSize <= 3){ %> 
            <p style="font-size:<%= fontSize %>rem"> JSP Tutorial </p>
            <%fontSize++;%>
        <%}%> 
	</body> 
</html>

 

결과는 아래와 같습니다.

JSP Tutorial

JSP Tutorial

JSP Tutorial

JSP Tutorial

 

자 이제 어느정도 감이 잡히시죠?

그냥 자바 문법을 그대로 옮겨놓기만 하는 겁니다.

JSP 정말 별거 아니네요~ ㅎㅎ

while 루프를 이용한 것을 이번에는 do - while을 이용해서 한번 해보세요~ 숙제입니다~ ㅋㅋ

 

 

 

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

'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )  (0) 2019.02.15
[JSP] Directives ( 디렉티브 )  (0) 2019.02.15
[JSP] JSP 생명 주기 ( life cycle )  (0) 2019.02.15
[JSP] JSP 시작하기  (0) 2019.02.15
[JSP] JSP란?  (0) 2019.02.15

💻 Programming/JSP

[JSP] JSP 시작하기

오늘은 JSP를 만들고 실행해보는 시간을 가져보도록 하겠습니다. 

 

하지만 그 전에 앞서서 알려드릴 것이 하나 더 있습니다. 바로 Scriptlet입니다.

 

Scriptlet은 변수선언, 메소드 선언, 자바에서 사용되는 문법들, 또는 유효한 스크립트 페이지 표현등을 내부에 가질 수 있습니다.

Scriptlet의 문법은 다음과 같습니다.

<% code fragment %>

 

그리고 XML에서 사용할 때에는 아래와 같이 쓸 수 있습니다.  

<jsp:scriptlet> code fragment </jsp:scriptlet>

HTML 태그나 JSP 요소 등 모든 텍스트는 scriptlet의 내부에 써서는 안됩니다.  

아래는 JSP 사용 예제입니다.  

<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>

NOTE: Apache Tomcat 웹서버가 C:\apache-tomcat-7.0.2 에 설치되어 있다는 가정하에 위 HTML 코드를 hello.jsp 안에 작성하고 파일을  C:\apache-tomcat-7.0.2\webapps\ROOT 디렉토리에 넣습니다. 그리고 웹브라우저에서 http://localhost:8080/hello.jsp 에 접속해보세요. 물론 웹서버를 기동시키셔야겠죠?? 그럼 아래 그림처럼 결과가 나올 것입니다. 

 

 

 

 



와우~~ 해냈습니다~
우리의 첫 JSP로 만든 웹페이지에요~ ^__^ 

 

 

JSP 선언부:

선언부라는 것은 하나 이상의 변수나 메소드를 선언하는 것을 말합니다. JSP파일 내부에서 추후에 사용될 변수나 메소드를 미리 선언해두는 선언부죠.  

 

JSP 선언부 문법:

<%! declaration; [ declaration; ]+ ... %>

XML에서 사용하실 때는 아래처럼 사용하세요.

<jsp:declaration> code fragment </jsp:declaration>

아래는 JSP 선언부의 예제입니다.

<%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>

JSP 표현부:

JSP 표현부는 결과가 하나의 String으로 반환됩니다. JSP 파일내에서 HTML태그로 감싸져 있는지와는 관계없이 사용될 수 있으며 자바문법에 맞는 모든 자바코딩을 하실 수 있습니다. 물론 결과는 String이라는 것만 유의하시면 될 것 같네요. 

 

JSP 표현식의 문법은 아래와 같습니다.

<%= expression %>

XML에서 사용하실 때는 아래처럼 사용하시면 됩니다.

<jsp:expression> expression </jsp:expression>

아래는 JSP 표현부 사용 예제입니다. 

<html> <head><title>A Comment Test</title></head> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html>

웹브라우저에서 보면 아래처럼 나올 것입니다.

Today's date: 11-Sep-2010 21:24:25

 

JSP 주석:

JSP 주석을 달기위한 문법은 아래와 같습니다.

<%-- This is JSP comment --%>

다음은 JSP 주석 예제입니다. 

<html> <head><title>A Comment Test</title></head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html>

웹브라우저에서 실행한 결과는 아래와 같습니다.

A Test of Comments

 

 

 

 

 

 

아래는 주석을 넣거나 특별한 경우 문자를 넣을 때 사용될 수 있는 문법입니다. 지금 당장은 그냥 이런게 있다라고 생각하시면 될 것 같네요. 

 

Syntax

Purpose

<%-- comment --%>

A JSP comment. Ignored by the JSP engine.

<!-- comment -->

An HTML comment. Ignored by the browser.

<\%

Represents static <% literal.

%\>

Represents static %> literal.

\'

A single quote in an attribute that uses single quotes.

\"

A double quote in an attribute that uses double quotes.

 

 

 

이상으로 JSP의 간단한 사용법을 공부해 보았습니다.

 

뭐 별거 없네요, 그죠? ^___^

 

 

 

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

'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )  (0) 2019.02.15
[JSP] Directives ( 디렉티브 )  (0) 2019.02.15
[JSP] JSP 생명 주기 ( life cycle )  (0) 2019.02.15
[JSP] 조건문, 반복문  (0) 2019.02.15
[JSP] JSP란?  (0) 2019.02.15

💻 Programming/JSP

[JSP] JSP란?

JSP란 무엇인가 ?

JSP는 Java Server Pages의 약자입니다. 자바 서버 페이지는 웹애플리케이션을 만들 때 HTML페이지 내에 자바 코드를 삽입하여 동적인 웹페이지를 구현할 수 있도록 도와주는 기술입니다. 보통 <% 자바코드 %> 이런식으로 사용이 되죠.

 

왜 JSP를 사용하는가 ?

자바 서버 페이지는 종종 예전의 CGI( Common Gateway Interface )처럼 사용되지만 CGI와 비교해서 좀 더 나은 점이 있습니다.

첫째, 성능이 굉장히 좋습니다. CGI파일처럼 별도의 파일이 필요한 것이 아니라 HTML페이지 내에 삽입되어 사용될 수 있기 때문입니다.

둘째, CGI / Perl 의 경우 페이지 요청시마다 서버쪽에서 interpreter와 대상 스크립트를 로드해야하지만 JSP는 처리되기전에 항상 컴파일이 됩니다.

셋째, JSP는 자바 서블릿 API위에 만들어진 것입니다. 따라서 서블릿처럼 JSP 또한 JDBC, JNDI, EJB, JAXP 등등 모든 엔터프라이즈 자바 API들을 사용할 수 있습니다.

넷째, JSP는 자바 서블릿 템플릿 엔진이 지원하는 비즈니스 로직을 처리하는 서블릿과 결합되서 함께 사용될 수 있습니다.


JSP 처리 과정

아래 과정은 웹서버가 JSP를 이용해서 어떻게 웹페이지를 생성하는지를 설명하고 있습니다.

1. 사용자가 웹페이지에서 요청을 합니다.

2. 웹서버가 요청을 받고 JSP페이지를 위한 요청이면 JSP 엔진으로 요청을 포워딩합니다. 이것은 URL이나 JSP페이지를 통해서 이루어집니다.

3. 요청을 받은 JSP 엔진이 JSP페이지를 로드하고 서블릿 컨텐트로 변환합니다. 이 변환은 매우 간단합니다. 템플릿 텍스트는 모두 println()문으로 변환되고 모든 JSP 요소들은 자바 코드로 변환되는 거죠.

4. JSP 엔진이 서블릿을 컴파일하여 실행가능한 클래스 파일로 변환시킵니다. 그리고 2번에서 받았던 요청을 서블릿 엔진으로 넘깁니다.

5. 요청을 받은 서블릿 엔진( 웹서버의 일부분 )은 클래스 파일을 읽어서 실행시킵니다. 그리고 실행되는 동안 서블릿 엔진은 HTML형태의 output을 웹서버( Http Response )로 반환합니다.

6. 웹서버가 Http Response를 웹브라우저로 보냅니다.

7. 브라우저는 HTML Response에 있는 동적으로 생성된 HTML 페이지를 해석하고 화면에 뿌려줍니다.



위 과정은 아래 그림을 보시면 이해가 더 쉬울겁니다.

 

 

자, 어느정도 이해가 되시나요?

다음 시간에는 JSP실습을 시작해보도록 하겠습니다.

JSP 환경구축은 단순히 웹서버를 설치하고, 자바를 설치하는 것 외에는 특별한 것이 없으므로 생략하겠습니다. 

 

 

 

 

 

 

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

💻 Programming

[C++] pipe() and fork() (파이프, 포크)

Pipes


  • Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process
  • It is possible to have a series of processes arranged in a a pipeline, with a pipe between each pair of processes in the series.
  • Implementation: A pipe can be implemented as a 10k buffer in main memory with 2 pointers, one for the FROM process and one for TO process
  • One process cannot read from the buffer until another has written to it
  • The UNIX command-line interpreter (e.g., csh) provide a pipe facility.
    • % prog | more
    • This command runs the prog1 program and send its output to the more program.

Pipe System Call

  • pipe() is a system call that facilitates inter-process communication. It opens a pipe, which is an area of main memory that is treated as a "virtual file". The pipe can be used by the creating process, as well as all its child processes, for reading and writing.
  • One process can write to this "virtual file" or pipe and another related process can read from it.
  • If a process tries to read before something is written to the pipe, the process is suspended until something is written.
  • The pipe system call finds the first two available positions in the process's open file table and allocates them for the read and write ends of the pipe. Recall that the open system call allocates only one position in the open file table.

Syntax in a C/C++ program:

 #include <unistd.h>
 int pip[2];
 (void) pipe(pip); 

With error checking:

 #include <unistd.h>
 int pip[2];
 int result;
 result = pipe(pip); 
 if (result == -1)
 {
  perror("pipe");
  exit(1);
 }

Programming notes:

  • The pipe() system call is passed a pointer to the beginning of an array of two integers.
  • It appears in C/C++ as if pipe() is passed the name of the array without any brackets.
  • The system call places two integers into this array. These integers are the file descriptors of the first two available locations in the open file table.
  • pip[0] - the read end of the pipe - is a file descriptor used to read from the pipe
  • pip[1] - the write end of the pipe - is a file descriptor used to write to the pipe

The buffer size for the pipe is fixed. Once it is full all further writes are blocked. Pipes work on a first in first out basis.



source from: http://www2.cs.uregina.ca/~hamilton/courses/330/notes/unix/pipes/pipes.html


( Tested on Linux/Cent OS 6.2 64 bit )

 

Let's say we have main function below....

 

int main(){
 First *fp = new First[10];          // creating array of First object
 delete [] fp;
return 0;
}

 

{If we have one of First classes below }// ??bytes of heap memory allocated


case 1:
class First{ double db; }// 8bytes * 10
class First{ int size;  }// 4bytes * 10
class First{ int *pt;  }// 8bytes * 10

 

case 2:
class First{ int size;
  int *pt;  }// 16 bytes * 10


class First{ int *pt;
  int size;  }// 16 bytes * 10

 

class First{ int size;
  double db; }// 16 bytes * 10


class First{ double db;
  int size;  }// 16 bytes * 10

 

case 3: 
class First{ int size;
  int size2;
  double db; }// 16 bytes * 10



 



 

class First{ double db;
  int size;
  int size2; }// 16 bytes * 10

 

 

 

class First{ int size;  
  double db;
  int size2; }// 24 bytes * 10

 

 

 

case 4:
class First{ int size;
  double db;
  int size2;
  char ch1; }// 24 bytes * 10

 





class First{ int size;
  double db;
  int size2;
  char ch1;
  char ch2;
  char ch3;
  char ch4; }// 24 bytes * 10

 





class First{ int size;
  double db;
  int size2;
  char ch1;
  char ch2;
  char ch3;
  char ch4; 
  char ch5; }// 32 bytes * 10


 

💻 Programming/Java

[Java] 랜덤 숫자 구하기

랜덤 숫자들, 출처 : https://openclipart.org/detail/254729/random-numbers-cloud

이번 포스팅에서는 Java로 랜덤한 숫자를 획득하는 방법에 대해서 소개합니다.

 

자바에는 Math 클래스가 존재합니다.

 

해당 클래스에는 다양한 수학적인 계산을 위해 기본적으로 제공해주는 static 메서드들이 여러개 있는데,

그 중에 하나가 random() 메서드입니다.

 

이 메서드는 0에서 1사이의 랜덤한 double 타입 숫자를 반환합니다.

 

javadoc 문서에는 아래와 같이 설명이 나와있습니다.

 

random

public static double random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

 

즉, 0.0보다 크거나 같고 1.0보다 작은 double(실수)형 숫자를 반환합니다. 

 

이게 0~1 사이의 수를 반환하면 이 메서드를 이용해서 어떻게 랜덤한 숫자를 얻을 수 있을까요?? 

 

예를 들어 0보다 크거나 같고 100보다 작은 수를 구하고자 한다면 아래와 같이 쓸 수 있습니다.

 

int max = 100;

int randomInt = (int) (Math.random() * max);

 

위 코드에서 (int) (Math.random() * max) 부분은 0 <= 결과값 < max (100) 의 범위 내의 값을 갖게 됩니다.

Math.random()의 최소값이 0이고 최대값이 1.0보다 작기 때문이죠. 

 

이번에는 100을 포함하도록 코드를 수정해 보겠습니다.

int max = 100;

int randomInt = (int) Math.round(Math.random() * max);

 

Math.round() 메서드를 이용하면 0<= 결과값 <= max (100) 범위 내의 값을 얻을 수 있습니다. 

 

하지만 이렇게 할 경우 0과 100이 나올 확률은 1~99가 나올 확률보다 50% 적게 됩니다.

 

0이 나오려면 Math.round()의 값이 0~0.004999...가 나와야 하고

100이 나오려면 0.95~0.9999...가 나와야 합니다.

 

이 경우 0.5%의 확률을 갖게 됩니다.

 

1이 나오려면 0.005~0.014999..가 나오면 되고, 2, 3, 4..., 99 까지는 모두 동일한 확률을 갖게 됩니다.

 

이 경우 1%의 확률을 갖게 되죠.

 

따라서 고르게 분포하는 0~100 사이의 값(경계포함)을 얻으려면 좀 더 고민을 해야합니다.

 

그럼 어떻게해야 0~100 사이의 숫자를 모두 동일한 확률로 얻을 수 있을까요??

 

int max = 100;
int randomInt = (int) (Math.random() * (max + 1));

간단합니다. max를 포함하고자 할 경우 max + 1을 곱해주면 만사OK입니다. 

 

자, 그럼 최소값의 범위를 정해주고 싶으면 어떻게 해야 할까요?

 

int min = 90, max = 100;
int randomInt = (int) (Math.random() * (max + 1 - min)) + min;

위 처럼 해주시면 됩니다.

 

즉, 랜덤하게 최대값에서 최소값을 뺀 만큼의 숫자를 만든 뒤에 최소값을 더해주는거죠. 

 

여기서는 최대값 100에서 1을 더하고 최소값 90을 빼서 최소 0~ 최대 10이 나오도록 만들었습니다. 

 

거기다가 min(90)값을 더해주면 0+90 ~ 10+90 사이의 수, 즉, 90~100 사이의 수를 얻을 수 있게되죠. 

 

하나하나 따라가니 어렵지 않죠?

 

오늘도 즐거운 코딩하시기 바랍니다~

 

💻 Programming/Java

[Java] 숫자 판별하기

 

자바에서 숫자 판별하기

 

Java의 스트링이 숫자(정수, int)인지 판단하기 위한 방법 두 가지를 소개합니다

 

 

1) 스트링의 각 문자를 하나하나 순회하면서 ascii 코드 값을 비교하는 방법

 

첫 번째로 소개해드릴 방법은 입력받은 문자열(스트링)의 각 문자가 0~9 ascii 코드값 사이에 있는 char인지를 판별하는 방법입니다.

 

0~9의 ascii 코드값은 십진수로 48~57 입니다.

 

따라서 String을 char[]로 변환한 다음 loop를 돌면서 각 char가 48~57사이의 값인지를 판단하여 숫자인지를 판별합니다.

 

코드는 아래와 같습니다.

String str = "not a number";

boolean isNumber = true;

for(char c : str.toCharArray()) {

  if(c >= 48 && c<= 57) {
        continue;
  } else {
        isNumber = false;
        break;
  }
}
System.out.println("Is string a number ? answer: " + isNumber);

 

2) Integer.parseInt 를 이용하는 방법

 

두 번째 방법은 Integer.parseInt 메서드를 이용하는 방법입니다.

 

parseInt 메서드에 대한 javadoc 문서에는 아래와 같이 설명이 나와있습니다.

public static int parseInt(String s)
                    throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to theparseInt(java.lang.String, int) method.

 

Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.

 

 

즉, 문자로 표현된 숫자를 입력받아 int로 return하는데요

입력받은 스트링이 숫자가 아닐 경우 NumberFormatException예외를 발생시킵니다.

 

따라서 위 메서드를 사용하여 NumberFormatException의 발생 여부에 따라 해당 스트링이 숫자인지 아닌지를 판별할 수 있습니다.

 

이 방식을 사용한 코드는 아래와 같습니다.

 

String str = "421303";

boolean isNumber = false;

try {

Integer.parseInt(str);

isNumber = true;

} catch (NumberFormatException e) {

// do nothing

}

System.out.println("Is string a number ? answer: " + isNumber);

 

Integer 뿐만 아니라 다른 wrapper 클래스들에도 Long.parseLong, Double.parseDouble 메서드들이 있으니 참고하시기 바랍니다.

 

 

위 두 가지 방법 외에 또 좋은 방법이 있으신 분들 제보받습니다 ㅎ

 

내용이 도움이 되셨다면 공감 누르고 가주세요~

 

 

 

 

💻 Programming/Java

AWS S3 Security Credentials 만들기

AWS 자격 증명 만들기



  Security Credentials 설정하기

AWS SDK를 이용하여 파일을 업로드 할 때 업로드 권한을 얻기 위해 Security Credentials을 만들어야 합니다.

전체적인 흐름은 사용자를 생성하고, 권한을 설정하고 Access key와  Secret key를 발급받도록 되어있습니다.



 1  내 보안 자격 증명(My Security Credentials) 을 눌러 Security Credentials 설정하는 부분으로 이동합니다.




 2  IAM 사용자 시작하기(Get Started with IAM Users) 버튼을 눌러 다음으로 이동합니다. 



 3  사용자 추가(Add User) 버튼을 클릭해서 유저를 생성합니다.



 4  사용자 이름(User name)을 지정하고 프로그래밍 방식 액세스(Programmatic access) 를 선택한 뒤 다음 버튼을 누르기 전에 아래쪽으로 화면을 스크롤하면 권한경계설정 항목이 나옵니다. 여기서 권한 경계없이 생성을 선택하고 다음 버튼을 클릭합니다.




 5  기존 정책 직접 연결을 선택하고 아래와 같이 S3라고 검색하면 관련 정책 목록이 출력되는데 여기서 우리는 AmazonS3FullAccess를 선택합니다. 그리고 다음으로 넘어갑니다.



 6  검토(Review)를 통해 올바른 설정을 했는지 확인하고 사용자 만들기(Create user)로 생성합니다.



 7  생성된 사용자의 액세스 키 ID(Access key ID)와 비밀 액세스 키(Secret access key)를 확인 할 수 있습니다. 비밀액세스 키는 "표시"를 클릭하면 보여집니다.



AWS S3에 파일을 업로드 할 때 여기에 보여지는 액세스 키 ID와 비밀 액세스 키를 사용해야합니다. 이렇게 생성된 사용자는 언제든지 "내 보안 자격 증명" 메뉴를 통해 확인이 가능합니다.



💻 Programming/Java

AWS S3 버킷에 파일 업로드하기 (자바)


  AWS SDK Java jar 파일 다운 받기

AWS-SDK for Java - https://aws.amazon.com/ko/sdk-for-java/

위 링크를 따라 들어가면 우측 상단에 SDK다운로드 또는 이클립스용 툴킷을 다운로드 받을 수 있는 버튼이 있습니다. 저는 메이븐을 사용할건데 직접 다운로드 받거나 툴킷을 써보고 싶으신 분들은 위 링크를 이용해주세요.


maven을 이용한다면 

1
2
3
4
5
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.386</version>
</dependency>


이 글이 포스팅 되는 시점에 최신버전은 1.11.388입니다. minor 버전이 하루가 다르게 증가하고있어요 ㅎ



  AWS s3 파일 업로드 하기(AWS S3 Upload for java )

실제로 S3에 업로드를 하기 위해서는 S3에 권한이 필요합니다. 이 권한을 얻기 위해서는 ACCESS_KEY, SECRET_KEY 를 생성해야 하는데 이는 아래 링크를 참고해주세요.

# Access Key, Secret Key 생성방법 - http://keichee.tistory.com/298



사용방법은 간단합니다.

아래처럼 파일을 전달받아 아마존 S3에 accesskey와  secretkey를 이용하여 권한을 얻고 파일을 업로드 하면됩니다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class AWSService {
    private static final String BUCKET_NAME = "bucket_name";
    private static final String ACCESS_KEY = "ACCESS_KEY";
    private static final String SECRET_KEY = "SECRET_KEY";
    private AmazonS3 amazonS3;
 
    public AWSService() {
        AWSCredentials awsCredentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        amazonS3 = new AmazonS3Client(awsCredentials);
    }
 
    public void uploadFile(File file) {
        if (amazonS3 != null) {
            try {
                PutObjectRequest putObjectRequest =
                        new PutObjectRequest(BUCKET_NAME + "/sub_dir_name"/*sub directory*/, file.getName(), file);
                putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); // file permission
                amazonS3.putObject(putObjectRequest); // upload file
 
            } catch (AmazonServiceException ase) {
                ase.printStackTrace();
            } finally {
                amazonS3 = null;
            }
        }
    }
}
 




자바로 개발을 하다가 OOM이 발생하는 경우가 발생하면 힙메모리가 어느 지점에서 증가하는지 파악을 해야한다. 확인하는 방법은 크게 두 가지 방법이 있다. 소스레벨 수정이 가능한 경우와 소스레벨 수정이 불가능한 경우로 나뉘는데, 소스레벨 수정이 불가능하면 자바 힙 덤프를 떠서 확인을 할 수 있다. 이번 포스팅에서는 소스레벨 수정이 가능한 경우, 즉, 개발 시점에서 확인하는 방법을 얘기해보려 한다.


자바는 개발자들에게 유용한 라이브러리들은 기본적으로 제공하고있으며, 메모리 사용량 관련하여 Runtime 클래스에서 메서드를 제공하고있다.


Java 8 API 문서를 보면 아래와 같이 설명이 되어있다.


Class Runtime



  • public class Runtime
    extends Object
    Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

    An application cannot create its own instance of this class.

즉, 모든 자바 프로그램들은 하나의 Runtime 인스턴스를 가지고 있는데, 이 Runtime인스턴스는 프로그램이 실행되고있는 환경과 인터페이스할 수 있도록 해준다. 즉, 자바프로그램이 실행되고있는 시스템의 정보를 가져올 수 있다는 것이다. (명령어 실행도 가능하다.)


그럼 Runtime 클래스에서 어떤 메서드들을 제공하는지 한번 보자.


Modifier and Type

Method and Description
voidaddShutdownHook(Thread hook)
Registers a new virtual-machine shutdown hook.
intavailableProcessors()
Returns the number of processors available to the Java virtual machine.
Processexec(String command)
Executes the specified string command in a separate process.
Processexec(String[] cmdarray)
Executes the specified command and arguments in a separate process.
Processexec(String[] cmdarray, String[] envp)
Executes the specified command and arguments in a separate process with the specified environment.
Processexec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
Processexec(String command, String[] envp)
Executes the specified string command in a separate process with the specified environment.
Processexec(String command, String[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
voidexit(int status)
Terminates the currently running Java virtual machine by initiating its shutdown sequence.
longfreeMemory()
Returns the amount of free memory in the Java Virtual Machine.
voidgc()
Runs the garbage collector.
InputStreamgetLocalizedInputStream(InputStream in)
Deprecated. 
As of JDK 1.1, the preferred way to translate a byte stream in the local encoding into a character stream in Unicode is via the InputStreamReader and BufferedReader classes.
OutputStreamgetLocalizedOutputStream(OutputStream out)
Deprecated. 
As of JDK 1.1, the preferred way to translate a Unicode character stream into a byte stream in the local encoding is via the OutputStreamWriterBufferedWriter, and PrintWriter classes.
static RuntimegetRuntime()
Returns the runtime object associated with the current Java application.
voidhalt(int status)
Forcibly terminates the currently running Java virtual machine.
voidload(String filename)
Loads the native library specified by the filename argument.
voidloadLibrary(String libname)
Loads the native library specified by the libname argument.
longmaxMemory()
Returns the maximum amount of memory that the Java virtual machine will attempt to use.
booleanremoveShutdownHook(Thread hook)
De-registers a previously-registered virtual-machine shutdown hook.
voidrunFinalization()
Runs the finalization methods of any objects pending finalization.
static voidrunFinalizersOnExit(boolean value)
Deprecated. 
This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.
longtotalMemory()
Returns the total amount of memory in the Java virtual machine.
voidtraceInstructions(boolean on)
Enables/Disables tracing of instructions.
voidtraceMethodCalls(boolean on)
Enables/Disables tracing of method calls.


위 메서드들이 Runtime 클래스에서 제공하고있는 메서드들이다.

이 중에서 메모리 관련 메서드들이 몇 개 보인다.

첫 번째로 freeMemory가 있는데, 이 메서드는 힙메모리 영역에서 free메모리를 바이트단위로 계산해서 반환해준다. 그리고 maxMemory와 totalMemory가 있는데 totalMemory는 현재 애플리케이션이 사용하고있는 총 힙 메모리를 의미하며, maxMemory는 OOM(OutOfMemory)예외가 발생하는 메모리 사이즈를 반환해준다. 역시 바이트 단위이며, 애플리케이션이 이 메모리 한계를 넘어서는 순간 OOM이 발생하면서 프로그램 실행이 중단된다.


사용예를 보면 아래와 같다.


// 현재 힙 메모리 사이즈를 바이트 단위로 반환

long heapSize = Runtime.getRuntime().totalMemory(); 


// 애플리케이션에 할당된 힙메모리 사이즈. 이 사이즈를 넘어서면 OOM 발생

long heapMaxSize = Runtime.getRuntime().maxMemory();


// 현재 남아있는 free메모리. 프로그램이 실행되는 동안 증감을 반복

long heapFreeSize = Runtime.getRuntime().freeMemory();


해당 사이즈를 반환받은 뒤 KB, MB단위로 변환해주는 메서드를 만들어서 콘솔에 출력해주면 읽기가 편하다.

[메이븐 프로젝트에 external jar 파일을 의존성으로 추가하는 방법]

 

maven 프로젝트의 웹앱을 커스터마이징 하던 중 형태소 분석기를 붙일 일이 있었다. 형태소 분석기는 코모란을 사용하였고, 두 개의 다른 라이브러리를 참조해야 하는 상황.

빌드 할 때 코모란 메인 라이브러리와 추가로 두 개의 라이브러리를 war 안에 묶어 주려고 했는데 아래와 같이 프로젝트 디렉토리 안에 별도의 lib 디렉토리를 만들고 그 안에 필요한 jar 파일들을 추가했다.

 

 

그리고 pom.xml 파일에 의존성을 아래와 같이 추가해준다.

 

각 라이브러리들의 groupId, artifactId, version 정보는 임의로 아무렇게나 넣어줘도 무관한것 같고, systemPath만 잘 잡아주면 된다. 

 

maven의 systemPath는 scope이 system일 때에만 설정이 가능하다.

 

MyBatis에서 전달받은 객체(MyObject)의 필드에 특정 값을 세팅할 때 selectKey 태그를 이용할 수 있다.


예를들어 MyObject가 아래 두 개의 필드를 가지고 있는 클래스라고 가정하자.

String id;

String name;


MyBatis를 이용하여 MyObject를 데이터베이스에 입력하고 싶을 때 이름값만 화면에서 전달받고 ID를 자동으로 sequence를 따서 입력 해줄 수 있으며, 이때  MyObject의 id필드에 값 세팅


<insert id="insert" parameterType="MyObject">

        <selectKey keyProperty="id" resultType="int" order="BEFORE">

            select nextval('sequence_id')

        </selectKey>

        <![CDATA[

        INSERT INTO person(id, name)

        VALUES (#{id}, #{name});

        ]]>

    </insert>


order="BEFORE" 옵션은 insert 쿼리를 실행하기전에 keyProperty에 값을 세팅하라는 의미이다.


자바 소스단에서 객체의 id에 값을 세팅하지 않고있는데 쿼리 실행 후에 id값이 세팅되어져서 나오는 케이스가 있었는데 이게 뭔가 싶어 찾아보다가 알게됨.


mybatis설정 파일에는 userGeneratedKeys 설정이 있어야 한다.

<configuration>

    <settings>

        <setting name="cacheEnabled" value="false"/>

        <setting name="useGeneratedKeys" value="true"/>

        <setting name="defaultExecutorType" value="REUSE"/>

    </settings>

</configuration>




위 처럼 사용할 수도 있으나 저렇게 사용하는 케이스가 많지 않다면 쿼리에 직접 옵션으로 줄 수도 있다.


<insert
  id="insertAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  keyProperty=""
  keyColumn=""
  useGeneratedKeys=""
  timeout="20">

속성에 대한 설명은 아래와 같다.

설명
id구문을 찾기 위해 사용될 수 있는 네임스페이스내 유일한 구분자
parameterType구문에 전달될 파라미터의 패키지 경로를 포함한 전체 클래스명이나 별칭
parameterMap외부 parameterMap 을 찾기 위한 비권장된 접근방법. 인라인 파라미터 매핑과 parameterType을 대신 사용하라.
flushCache이 값을 true 로 셋팅하면 구문이 호출될때마다 캐시가 지원질것이다(flush). 디폴트는 false 이다.
timeout예외가 던져지기 전에 데이터베이스의 요청 결과를 기다리는 최대시간을 설정한다. 디폴트는 셋팅하지 않는 것이고 드라이버에 따라 다소 지원되지 않을 수 있다.
statementTypeSTATEMENT, PREPARED 또는 CALLABLE중 하나를 선택할 수 있다. 마이바티스에게 Statement, PreparedStatement 또는 CallableStatement를 사용하게 한다. 디폴트는 PREPARED 이다.
useGeneratedKeys(입력(insert, update)에만 적용) 데이터베이스에서 내부적으로 생성한 키 (예를들어 MySQL또는 SQL Server와 같은 RDBMS의 자동 증가 필드)를 받는 JDBC getGeneratedKeys메소드를 사용하도록 설정하다. 디폴트는 false 이다.
keyProperty(입력(insert, update)에만 적용) getGeneratedKeys 메소드나 insert 구문의 selectKey 하위 엘리먼트에 의해 리턴된 키를 셋팅할 프로퍼티를 지정. 디폴트는 셋팅하지 않는 것이다. 여러개의 칼럼을 사용한다면 프로퍼티명에 콤마를 구분자로 나열할수 있다.
keyColumn(입력(insert, update)에만 적용) 생성키를 가진 테이블의 칼럼명을 셋팅. 키 칼럼이 테이블이 첫번째 칼럼이 아닌 데이터베이스(PostgreSQL 처럼)에서만 필요하다. 여러개의 칼럼을 사용한다면 프로퍼티명에 콤마를 구분자로 나열할수 있다.
databaseId설정된 databaseIdProvider가 있는 경우 마이바티스는 databaseId 속성이 없는 모든 구문을 로드하거나 일치하는 databaseId와 함께 로드될 것이다. 같은 구문에서 databaseId가 있거나 없는 경우 모두 있다면 뒤에 나온 것이 무시된다.


💻 Programming

[Git] 태그 삭제하기 (removing git tag)

Git에서  태그 삭제하기


git tag -d {name of tag}

git push origin :refs/tags/{name of tag}


git tag -d 12345
git push origin :refs/tags/12345