전체 글 (356)

스트링 거꾸로 뒤집기

 

자바에서 스트링을 거꾸로 뒤집는 간단한 방법을 소개해드립니다.

 

자바에는 각종 array로부터 String을 쉽게 만들 수 있도록 해주는 StringBuilder가 있습니다.

 

생성자에 String을 그대로 넣어서 새로운 스트링을 만들 수도 있을 뿐만 아니라 기본적으로 구현되어있는 reverse 메서드가 있습니다.

 

이 메서드를 이용하면 아래와 같이 단 한 줄로 스트링을 거꾸로 배열할 수 있습니다.

String a = "abcdefg";

String b = new StringBuilder(a).reverse().toString();

System.out.println(a);
System.out.println(b);

출력 결과 

abcdefg

gfedcba

 

아주 간단합니다.

 

💻 Programming/JSP

[JSP] Security ( 보안 )

JSP와 servlets 은 Web 개발자들을 위해서 보안(인증)을 처리할 수 있는 다양한 방법을 제공합니다.  

오늘은 그 중 두가지에 대해서만 알아보도록 하겠습니다. 

 

역할 기반 인증

servlet 에서 제공하는 역할 기반 인증은 사용자 레벨에서 리소스를 제한하는 것이 아니라 사용자에게 역할을 부여하고 특정 역할을 가진 모든 사용자에 대해서 리소스를 제한하는 방법입니다.  

톰캣 홈 디렉토리의 conf디렉토리에 tomcat-users.xml 파일을 만들고 아래코드를 넣어주세요.

<?xml version='1.0' encoding='utf-8'?> 
<tomcat-users> 
	<role rolename="tomcat"/> 
	<role rolename="role1"/> 
	<role rolename="manager"/> 
	<role rolename="admin"/> 
	<user username="tomcat" password="tomcat" roles="tomcat"/> 
	<user username="role1" password="tomcat" roles="role1"/> 
	<user username="both" password="tomcat" roles="tomcat,role1"/> 
	<user username="admin" password="secret" roles="admin,manager"/> 
</tomcat-users>

위 코드가 뭘 하고있는지는 대충 봐도 아시겠죠? 역할을 생성하고 사용자를 만들때 역할을 부여하고 있습니다.

 

이제  web.xml파일에 <security-constraint> 태그를 추가하고 아래처럼 넣어보세요. 물론 url-pattern은 여러분이 가지고 있는 웹애플리케이션에 실제로 존재하는 url이어야게죠? 그래야 테스트가 가능합니다~ 

 

<web-app> 
    ... 
    <security-constraint> 
    	<web-resource-collection> 
        	<web-resource-name> SecuredBookSite </web-resource-name> 
            <url-pattern>/secured/*</url-pattern> 
            <http-method>GET</http-method> 
            <http-method>POST</http-method> 
        </web-resource-collection> 
        <auth-constraint> 
        	<description> Let only managers use this app </description> 
            <role-name>manager</role-name> 
        </auth-constraint> 
    </security-constraint> 
    <security-role> 
    	<role-name>manager</role-name> 
    </security-role> 
    <login-config> 
    	<auth-method>BASIC</auth-method> 
    </login-config> 
    ... 
</web-app>

위 소스코드가 의미하는 것이 무언인가 하면 다음과 같습니다. 

  • HTTP GET 이나 POST 방식의 요청에 대해서 /secured/* URL에 대한 요청이 들어오면 보안설정의 제약을 받게됩니다.

  • 매니저 역할을 가지고 있는 사용자에 대해서만 /secured/* 리소스에 접근이 가능합니다.

  • 마지막으로 login-config 태그가 기본형태의 인증을 위해서 사용되었습니다. 

이제 /security내부의 페이지로 접근을 하려면 사용자명과 비밀번호를 입력하라는 창이 뜨게됩니다. 접속할 수 있는 역할을 가지고 있지 않거나 인증에 실패하면 접속이 불가능하나 페이지가 되는 것이죠. 

 

Form을 이용한 인증

FORM 인증을 사용하려면 사용자에게 로그인 폼을 제공해주어야 합니다.  

<html>

<body bgcolor="#ffffff">
    <form method="POST" action="j_security_check">
        <table border="0">
            <tr>
                <td>Login</td>
                <td><input type="text" name="j_username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="j_password"></td>
            </tr>
        </table> <input type="submit" value="Login!"> </center>
    </form>
</body>

</html>

위 코드를 login.jsp에 넣어주세요. <form> 태그 안에있는 action의 값은  j_security_check 여야 합니다. POST 방식이 사용되어야 한다는 것은 알고 계시겠죠? 자 이제 web.xml의 <login-config> 태그를 FORM을 이용하도록 수정해야합니다.

<web-app> 
    ... 
    <security-constraint>
        <web-resource-collection>
            <web-resource-name> SecuredBookSite </web-resource-name>
            <url-pattern>/secured/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description> Let only managers use this app </description>
            <role-name>manager</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
        <role-name>manager</role-name>
    </security-role>
    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/error.jsp</form-error-page>
        </form-login-config>
    </login-config> 
    ...
</web-app>

이제  /secured/* 주소로 접속을 시도해 보세요. 사용자 ID와 패스워드를 입력하라고 할겁니다. 컨테이너가  "j_security_check" 액션을 만나면요청을 인증하기위한 내부 메카니즘을 실행합니다.

로그인이 성공하고 리소스를 조회할 수 있는 역할을 가지고 있다면 컨테이너는 사용자를 확인하기위해서 session-id 를 비교합니다. 컨테이너는 세션아이디를 가지고있는 쿠키와 함께 세션을 유지하게됩니다. 서버가 이 쿠키를 클라이언트로 되돌려보내고 이후 요청때마다 이 쿠키를 서버로 전송하게되면 컨테이너는 요청하는 클라이언트를 식별할 수 있습니다.

로그인이 실패하면 서버는 에러페이지를 전송하게 됩니다.  

 

j_security_check 가 톰캣 컨테이너에서 어떻게 동작하는지에 대해서 더 자세한 정보를 보시려면 Standard Realm Implementations 이곳에 가보세요. 

 

Servlet/JSP의 코드로 보안적용하기

HttpServletRequest 객체가 보안관련해서 제공하는 메소드들은 다음과 같습니다.

 

SN Method and Description
1 String getAuthType()
The getAuthType() method returns a String object that represents the name of the authentication scheme used to protect the Servlet.
2 boolean isUserInRole(java.lang.String role)
The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not.
3 String getProtocol()
The getProtocol() method returns a String object representing the protocol that was used to send the request. This value can be checked to determine if a secure protocol was used.
4 boolean isSecure()
The isSecure() method returns a boolean value representing if the request was made using HTTPS. A value of true means it was and the connection is secure. A value of false means the request was not.
5 Principle getUserPrinciple()
The getUserPrinciple() method returns a java.security.Principle object that contains the name of the current authenticated user.

 

예를들어 매니저 권한을 갖고있는 사용자들을 위한 링크를 제공하는 JavaServer Page 를 만들려면 아래 코드를 삽입해주시면 되는거죠 

<% if (request.isUserInRole("manager")) { %> 
    <a href="managers/mgrreport.jsp">Manager Report</a> 
    <a href="managers/personnel.jsp">Personnel Records</a> 
<% } %>

그러면 사용자 역할을 검사한 뒤 매니저역할을 가지고 있는 사용자에게만 링크를 보여주게 됩니다. 만약 로그인 폼에서 입력한 사용자명이 필요한 경우에는 getRemoteUser 메소드를 호출하면 됩니다.

 

 

 

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

 

 

 

 

 

 

💻 Programming/JSP

[JSP] Database CRUD (데이터베이스 연동)

오늘은 JSP를 이용하여 데이타베이스에 접속하고  SELECT, INSERT, DELETE, 그리고 UPDATE 하는 방법에 대해서 알아보도록 하겠습니다.

우선 데이타베이스를 설치가되어있고 emp계정이 만들어져 있으며 Employees테이블이 id, first, last, age 컬럼으로 이루어져 있다고 가정을 했습니다. 

 

SELECT Operation:

JTSL을 이용하여 JSP 페이지를 작성합니다.

<%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>

<head>
    <title>SELECT Operation</title>
</head>

<body>
    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="emp"
        password="emp" />
    <sql:query dataSource="${snapshot}" var="result"> SELECT * from Employees; </sql:query>
    <table border="1" width="100%">
        <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <c:forEach var="row" items="${result.rows}">
            <tr>
                <td>
                    <c:out value="${row.id}" />
                </td>
                <td>
                    <c:out value="${row.first}" />
                </td>
                <td>
                    <c:out value="${row.last}" />
                </td>
                <td>
                    <c:out value="${row.age}" />
                </td>
            </tr>
        </c:forEach>
    </table>
</body>

</html>

위 JSP페이지에 접속하면 아래와 같은 결과가 나오겠죠? 

Emp ID

First Name

Last Name

Age

100

Zara

Ali

18

101

Mahnaz

Fatma

25

102

Zaid

Khan

30

103

Sumit

Mittal

28

 

INSERT Operation:

역시나 JSTL을 이용한 JSP 페이지입니다. 

<%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>

<head>
    <title>JINSERT Operation</title>
</head>

<body>
    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="emp"
        password="emp" />
    <sql:update dataSource="${snapshot}" var="result"> INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
    </sql:update>
    <sql:query dataSource="${snapshot}" var="result"> SELECT * from Employees; </sql:query>
    <table border="1" width="100%">
        <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <c:forEach var="row" items="${result.rows}">
            <tr>
                <td>
                    <c:out value="${row.id}" />
                </td>
                <td>
                    <c:out value="${row.first}" />
                </td>
                <td>
                    <c:out value="${row.last}" />
                </td>
                <td>
                    <c:out value="${row.age}" />
                </td>
            </tr>
        </c:forEach>
    </table>
</body>

</html>

결과는 아래처럼 한줄이 추가가 되어 나오겠죠.

Emp ID

First Name

Last Name

Age

100

Zara

Ali

18

101

Mahnaz

Fatma

25

102

Zaid

Khan

30

103

Sumit

Mittal

28

104

Nuha

Ali

2

 

DELETE Operation:

<%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>

<head>
    <title>DELETE Operation</title>
</head>

<body>
    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="emp"
        password="emp" />
    <c:set var="empId" value="103" />
    <sql:update dataSource="${snapshot}" var="count"> DELETE FROM Employees WHERE Id = ?
        <sql:param value="${empId}" />
    </sql:update>
    <sql:query dataSource="${snapshot}" var="result"> SELECT * from Employees; </sql:query>
    <table border="1" width="100%">
        <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <c:forEach var="row" items="${result.rows}">
            <tr>
                <td>
                    <c:out value="${row.id}" />
                </td>
                <td>
                    <c:out value="${row.first}" />
                </td>
                <td>
                    <c:out value="${row.last}" />
                </td>
                <td>
                    <c:out value="${row.age}" />
                </td>
            </tr>
        </c:forEach>
    </table>
</body>

</html>

결과는 아래와 같습니다. 

Emp ID

First Name

Last Name

Age

100

Zara

Ali

18

101

Mahnaz

Fatma

25

102

Zaid

Khan

30

104

Nuha

Ali

2

 

UPDATE Operation:

<%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>

<head>
    <title>DELETE Operation</title>
</head>

<body>
    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="emp"
        password="emp" />
    <c:set var="empId" value="102" />
    <sql:update dataSource="${snapshot}" var="count"> UPDATE Employees SET last = 'Ali'
        <sql:param value="${empId}" />
    </sql:update>
    <sql:query dataSource="${snapshot}" var="result"> SELECT * from Employees; </sql:query>
    <table border="1" width="100%">
        <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <c:forEach var="row" items="${result.rows}">
            <tr>
                <td>
                    <c:out value="${row.id}" />
                </td>
                <td>
                    <c:out value="${row.first}" />
                </td>
                <td>
                    <c:out value="${row.last}" />
                </td>
                <td>
                    <c:out value="${row.age}" />
                </td>
            </tr>
        </c:forEach>
    </table>
</body>

</html>

결과는 아래처럼 나오겠죠?

 

Emp ID

First Name

Last Name

Age

100

Zara

Ali

18

101

Mahnaz

Fatma

25

102

Zaid

Ali

30

104

Nuha

Ali

2

 

 

 

💻 Programming/JSP

[JSP] JSTL ( JSP Standard Tag Library )

JSTL 는 유용한 JSP 태그들을 모아놓은 라이브러리입니다. 커스텀 태그를 JSTL tags와 통합할 수 있는 프레임워크도 제공하므로 알아두시면 좋을거에요. 

JSTL태그는 기능별로 분류가 됩니다.  

  • Core Tags

  • Formatting tags

  • SQL tags

  • XML tags

  • JSTL Functions


JSTL 설치하기

Apache Tomcat container 를 사용중이면 아래 두가지 스텝으로 설치가 완료됩니다.

  • Apache Standard Taglib 이곳에서 라이브러리를 다운로드하고 압축을 풀어주세요.

  • 압축이 풀린 디렉토리내의 lib디렉토리의 JAR 파일들을 여러분이 사용하려는 애플리케이션의 webapps\ROOT\WEB-INF\lib 디렉토리안에 넣어주세요. ( 이거는 이클립스에서 직접 하실 수 있는건 아시죠? )  

태그라이브러리를 사용하려면 <taglib> 디렉티브를 JSP 페이지 제일 위쪽에 선언해주셔야 합니다.  


Core Tags:

JSTL 태그 중에서 가장 많이 사용되는 태그입니다.  

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 

TagDescription
<c:out >Like <%= ... >, but for expressions.
<c:set >Sets the result of an expression evaluation in a 'scope'
<c:remove >Removes a scoped variable (from a particular scope, if specified).
<c:catch>Catches any Throwable that occurs in its body and optionally exposes it.
<c:if>Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose>Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>
<c:when>Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise >Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.
<c:import>Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.
<c:forEach >The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .
<c:forTokens>Iterates over tokens, separated by the supplied delimeters.
<c:param>Adds a parameter to a containing 'import' tag's URL.
<c:redirect >Redirects to a new URL.
<c:url>Creates a URL with optional query parameters


Formatting tags:

포매팅 관련 태그들입니다.다국적 Web 사이트를 만들때 유용하다고 하네요.

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 

TagDescription
<fmt:formatNumber>To render numerical value with specific precision or format.
<fmt:parseNumber>Parses the string representation of a number, currency, or percentage.
<fmt:formatDate>Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate>Parses the string representation of a date and/or time
<fmt:bundle>Loads a resource bundle to be used by its tag body.
<fmt:setLocale>Stores the given locale in the locale configuration variable.
<fmt:setBundle>Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable.
<fmt:timeZone>Specifies the time zone for any time formatting or parsing actions nested in its body.
<fmt:setTimeZone>Stores the given time zone in the time zone configuration variable
<fmt:message>To display an internationalized message.
<fmt:requestEncoding>Sets the request character encoding


SQL tags:

JSTL SQL 태그는 관계형 데이타베이스 시스템을 핸들링할 수 있습니다. ( Oracle, MySQL, Microsoft SQL Server )

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

 

TagDescription
<sql:setDataSource>Creates a simple DataSource suitable only for prototyping
<sql:query>Executes the SQL query defined in its body or through the sql attribute.
<sql:update>Executes the SQL update defined in its body or through the sql attribute.
<sql:param>Sets a parameter in an SQL statement to the specified value.
<sql:dateParam>Sets a parameter in an SQL statement to the specified java.util.Date value.
<sql:transaction >Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.


XML tags:

JSTL XML 태그는 JSP에서 XML 문서를 생성 및 조작할 수 있도록 해줍니다. 하지만 XML을 파싱하거나 데이타를 변환하거나 XPath 표현식을 사용하려면 추가적인 커스텀 태그가 필요합니다.  

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

아래의 두 jar파일도 <Tomcat Installation Directory>\lib 에 추가해주셔야 합니다. 

 

TagDescription
<x:out>Like <%= ... >, but for XPath expressions.
<x:parse>Use to parse XML data specified either via an attribute or in the tag body.
<x:set >Sets a variable to the value of an XPath expression.
<x:if >Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.
<x:forEach>To loop over nodes in an XML document.
<x:choose>Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>
<x:when >Subtag of <choose> that includes its body if its expression evalutes to 'true'
<x:otherwise >Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'
<x:transform >Applies an XSL transformation on a XML document
<x:param >Use along with the transform tag to set a parameter in the XSLT stylesheet


JSTL Functions:

JSTL 은 표준 함수들을 제공하고 있습니다. 대부분 스트링관련 함수들이죠.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

FunctionDescription
fn:contains()Tests if an input string contains the specified substring.
fn:containsIgnoreCase()Tests if an input string contains the specified substring in a case insensitive way.
fn:endsWith()Tests if an input string ends with the specified suffix.
fn:escapeXml()Escapes characters that could be interpreted as XML markup.
fn:indexOf()Returns the index withing a string of the first occurrence of a specified substring.
fn:join()Joins all elements of an array into a string.
fn:length()Returns the number of items in a collection, or the number of characters in a string.
fn:replace()Returns a string resulting from replacing in an input string all occurrences with a given string.
fn:split()Splits a string into an array of substrings.
fn:startsWith()Tests if an input string starts with the specified prefix.
fn:substring()Returns a subset of a string.
fn:substringAfter()Returns a subset of a string following a specific substring.
fn:substringBefore()Returns a subset of a string before a specific substring.
fn:toLowerCase()Converts all of the characters of a string to lower case.
fn:toUpperCase()Converts all of the characters of a string to upper case.
fn:trim()Removes white spaces from both ends of a string.

 

 

 

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

 

💻 Programming/JSP

[JSP] Page Redirection ( 페이지 리디렉션 )

페이지 리디렉션을 하는 가장 간단한 방법은 response 객체의 sendRedirect() 메소드를 이용하는 것이랍니다. 

public void response.sendRedirect(String location) throws IOException

이 메소드는 상태코드와 새로운 페이지 주소를 함께 response객체에 담아서 브라우저로 전송합니다.  setStatus() 와 setHeader() 를 이용하여 세팅을 해주면 됩니다. 아래처럼 말이죠. 

.... String site = "http://www.newpage.com" ; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); ....

예제

JSP 로 어떻게 페이지 리디렉션을 하는지 예제를 통해 알아볼까요? 

<%@ page import="java.io.*,java.util.*" %> <html> <head> <title>Page Redirection</title> </head> <body> <center> <h1>Page Redirection</h1> </center> <% // New location to be redirected String site = new String("http://www.naver.com"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); %> </body> </html>

위 코드를 PageRedirect.jsp 에 넣고 http://localhost:8080/PageRedirect.jsp 를 웹브라우저에서 요청해보세요.   

 

http://www.naver.com 사이트로 리디렉션이 되나요?? ^____^ 

 

 

 

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

 

 

💻 Programming/JSP

[JSP] File Upload ( 파일 업로드 )

파일 업로드 폼 만들기

 

다음에 볼 HTML 코드가 바로 파일 업로드 폼입니다. 여기서 중요한 점을 몇가지 짚고 넘어가겠습니다.

  • <form>의 method 속성은 POST 입니다. 

  • <form>의 enctype 속성은 multipart/form-data 입니다. 

  • <form>의 action 속성은 백엔드 쪽에서 파일 업로드를 핸들링할 JSP 파일입니다. 아래 예제는 UploadFile.jsp를 사용했습니다.

  • 한개의 파일만 업로드 할 때는  <input .../> 태그를 type="file" 속성고 함께 사용합니다. 멀티플 파일업로딩을 구현하려면 하나 이상의 input태그를 각기 다른 name으로 설정해줘야 합니다.  

<html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload File" /> </form> </body> </html>

위 소스를 UploadFile.htm에 넣어주세요. 위 페이지를 출력해보면 아래처럼 나올거에요. 파일을 업로드 해보세요 ^___^ 참고로 위 코드는 그냥 dummy코드라서 실제로 파일을 어딘가로 업로드 하지는 않습니다. 

 
 

백엔드 JSP 스크립트 만들기

 

우선 파일들이 업로드되었을 때 어디에 저장될지 경로를 지정해볼게요. 경로를 지정하는 방법은 소스에 하드코딩하는 방법도 있고 web.xml파일에 context-param 태그내에 지정해주는 방법도 있습니다.

<web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data\ </param-value> </context-param> .... </web-app>

아래는 한번에 여러개의 파일을 업로드 할 수 있는 UploadFile.jsp의 소스코드에요. 소스부터 보기전에 점검해야할 것들이 있습니다. 

  • 아래 예제는 FileUpload 클래스를 사용하기 때문에 최신버전의 commons-fileupload.x.x.jar 파일을 클래스패스에 넣어주셔야 합니다. 여기서 http://commons.apache.org/fileupload/ 다운로드 받으실 수 있어요. 

  • 또한 Commons IO 라이브러리도 필요합니다.  commons-io-x.x.jar 파일 역시 클래스 패스에 설정을 해주셔야 되요. 다운로드는 http://commons.apache.org/io/.

  • 아래 예제를 테스트할 때에는 maxFileSize 에 설정된 파일크기보다 작은 파일들만 업로드가 가능하답니다.

  • c:\temp 와 c:\apache-tomcat-5.5.29\webapps\data 디렉토리가 있는지 확인하시고 없으면 생성해주세요. 
     

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %> <%@ page import="javax.servlet.http.*" %> <%@ page import="org.apache.commons.fileupload.*" %> <%@ page import="org.apache.commons.fileupload.disk.*" %> <%@ page import="org.apache.commons.fileupload.servlet.*" %> <%@ page import="org.apache.commons.io.output.*" %> <% File file ; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = pageContext.getServletContext(); String filePath = context.getInitParameter("file-upload"); // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try{ // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf("\\") >= 0 ){ file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; }else{ file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; } fi.write( file ) ; out.println("Uploaded Filename: " + filePath + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); }catch(Exception ex) { System.out.println(ex); } }else{ out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } %>

이제 http://localhost:8080/UploadFile.htm 에 접속해서 테스트 해볼까요? 

 

제대로 작동한다면  c:\apache-tomcat-5.5.29\webapps\data\ 디렉토리에 파일이 업로드 되어있을 거에요~ 

 

 

 

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

 

 

💻 Programming/JSP

[JSP] Session ( 세션 )

이번에는 JSP로 세션을 다루는 법에 대해서 배워보도록 하겠습니다. HTTP는 "stateless" 프로토콜입니다.  무슨 말이냐하면 말이죠, 클아이언트(웹브라우저)가 웹페이지를 불러올때마다 클라이언트는 웹서버로 별도의 커넥션을 맺습니다. 그리고 이전 클라이언트의 접속에 대한 어떠한 정보도 자동으로 기록하지는 않습니다. 

어쨌든 세션이라는 것은 바로 웹브라우저가 웹서버와 연결이 될때 생기는 것인데, 이 세션을 유지하는 방법에는 여러가지가 있답니다.  

1. Cookies

쿠키에 세션ID를 저장하는 식으로 세션을 관리할 수는 있겠지만 브라우저에서 쿠키사용 제한 설정이 있을 수 있기때문에 세션을 쿠키를 이용해서 관리한다는 것은 좋은방법이 아닙니다.

 

 

2. Hidden Form Fields

 

웹서버는 hidden HTML form field에 unique session ID를 넣어서 아래처럼 전송할 수 있습니다.

<input type="hidden" name="sessionid" value="12345">

form이 전송될 때 세션ID와 값을 넘겨주는거죠. 브라우저에서 이 정보를 웹서버에 보내면 이 정보를 가지고 웹서버에서는 다른 브라우저에서 접속한 것인지를 판단할 수 있게 됩니다. 하지만 이 역시 좋은 방법은 아니죠. <a> 태그를 이용해서 링크를 타고 들어오는 경우에는 저 form데이타를 전송하지 않거든요.

3. URL Rewriting

URL 끝에 세션에 대한 정보를 추가할 수도 있습니다. 그리고 서버는 그 정보를 가지고 세션을 비교할 수 있겠죠.

예를들면, http://tutorialspoint.com/file.htm;sessionid=12345 이렇게 요청을 보내면 서버에서 sessionid=12345부분에 대한 정보를 가지고 웹서버의 세션정보와 비교를 하는거죠.

URL rewriting 은 세션을 관리하기위한 방법들 중에서는 그나마 좋은 방법이긴 합니다. 브라우저가 쿠키사용을 안할때도 사용가능한 방법이니까요. 하지만 역시 결점이 있습니다. 세션ID를 동적으로 매번 생성해줘야 하기 때문입니다. 정적인 HTML페이지라도 말이죠.  


The session Object:

위 세가지 방법 이외에도 JSP는 HttpSession 인터페이스를 사용할 수 있습니다. 기본적으로 JSPs는 세션을 추적하게 되어있으며 새로운 HttpSession 객체가 새로운 클라이언트들이 접속할 때마다 자동으로 생성됩니다. 세션 추적 기능을 끄려면 page directive의 세션 속성을 false로 세팅해줘야 합니다. 아래 처럼 말이죠.

<%@ page session="false" %>

JSP engine은 JSP개발자들에게 HttpSession 객체를 통해서 session에 접근할 수 있도록 해줍니다. session 객체가 기본적으로 제공이 되기 때문에 개발자들은 궂이 세션객체를 생성하거나 getSession() 메소드를 이용해서 얻어올 필요가 없습니다.

웹애플리케이션을 작성하고 있다면 그냥 세션을 파라미터로 받아서 쓰면 되는 겁니다. 

 

다음은 세션 객체가 가지고 메소드 목록입니다. 어떤 메소드들이 있는지 한번 살펴볼까요~

 

S.N.Method & Description
1public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
2public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
3public long getCreationTime()
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
4public String getId()
This method returns a string containing the unique identifier assigned to this session.
5public long getLastAccessedTime()
This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
6public int getMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
7public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
8public boolean isNew(
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
9public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
10public void setAttribute(String name, Object value) 
This method binds an object to this session, using the name specified.
11public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.


Session Tracking Example:

다음 예제는 HttpSession 객체를 이용하여 세션의 생성시간과 마지막 접근시간 정보를 가져오는 방법에 대해서 설명해주고 있습니다.  

<%@ page import="java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // 처음 접속한 방문자라면 세션을 생성합니다. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <html> <head> <title>Session Tracking</title> </head> <body> <center> <h1>Session Tracking</h1> </center> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Number of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>

 main.jsp​에 위 코드를 넣고 http://localhost:8080/main.jsp 를 호출해보세요. 서버 실행시키는 것 잊어먹지 마시구요~ ^___^ 

Welcome to my website

Session Infomation

Session infovalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits0

 

 

위와같은 페이지가 나오나요??

 

다시한번 호출 해 볼까요??

 

Welcome Back to my website

Session Infomation

info typevalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits1


위와 같은 결과가 나오나요? Welcome 메시지가 Welcome Back 메시지로 바뀌었네요. ^__^ 

 

 

이제 세션 데이타를 삭제하는 방법을 알아볼까요??​​

 

Deleting Session Data:

사용자의 세션 데이타로 해야되는 작업을 모두 완료하였다면 아래와 같은 작업을 마지막으로 해줄 수 있습니다.

  • 특정 속성 삭제 : removeAttribute(String name) 메소드를 이용해서 세션의 특정 속성값만 삭제할 수 있습니다. 

  • 세션 삭제 : invalidate() 메소드를 호출하여 세션 전체를 무효화 시킬 수 있습니다. 세션을 끊는다고 표현하죠. 

  • 세션 타임아웃 설정 : setMaxInactiveInterval(int interval) 메소드를 이용하여 세션별로 타임아웃을 설정할 수 있습니다.

  • 사용자 로그아웃 : servlets 2.4를 지원하는 서버라면 logout 을 호출하여 사용자를 로그아웃시키고 모든 세션을 무효화 시킬 수 있습니다.  

  • web.xml 설정 : Tomcat을 사용중이라면 web.xml 파일에서 아래처럼 타임아웃 시간을 설정할 수도 있습니다.

<session-config> <session-timeout>15</session-timeout> </session-config>

여기서 타임아웃 시간의 단위는 분 단위이며 톰캣의 기본 타임아웃인 30 분을 오버라이드하여 적용됩니다.

서블릿의 getMaxInactiveInterval( )메소드는 초단위로 타임아웃 시간을 가져옵니다. 따라서 web.xml 파일에 15 분으로 설정되어있다면  getMaxInactiveInterval( ) 메소드는 900 ( 15분 * 60초 )를 반환하게 됩니다 .

 

 

 

 

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

 

💻 Programming/JSP

[JSP] Cookies ( 쿠키 세팅, 읽기, 삭제하기)

Cookies 는 그냥 일반 text files 이죠. 아마 JSP를 공부하시는 분들이라면 이정도는 알고 계시겠죠? 

JSP로 HTTP cookies 를 다루는 법에 대해서 한번 알아볼텐데 그 전에 하나만 짚고 넘어갈까요?

사용자가 특정 사이트에 재접속 했다는 것을 웹사이트에서 어떻게 알까요?

3초만에 답이 안나온다면 아래를 읽어봅시다.

 

재접속하는 사용자를 판단하는 과정은 세 단계로 나뉩니다.

  • 서버쪽에서 쿠키를 브라우저로 보냅니다.  

  • Browser는 서버에서 보낸 쿠키를 로컬에 저장을 하겠죠.

  • 이제 사용자가 이 브라우저를 이용해서 특정사이트에 접속할 때 저장되어있는 쿠키의 정보가 서버쪽으로 전달되고 서버쪽에서는 이 정보를 이용해서 사용자를 판별할 수 있는 것이죠.  

쿠키는 다른 정보로도 사용될 수 있으니 쿠키를 다루는 법을 한번 알아보도록 하겠습니다. 여기서는 쿠키 세팅, 리셋, 읽기, 삭제하기에 대해서 알아보도록 하겠습니다.  


Cookie 해부하기

 쿠키는 보통 HTTP header 안에 세팅되어있습니다. ( JavaScript 는 직접 브라우저에 쿠키를 설정할 수 있다네요 ). 쿠키를 세팅하는 JSP 는 아래와 같은 헤더를 보낼거에요. 

HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html

이미 request 객체시간에 한번 본적이 있던 내용이죠? 그런데 추가된게 하나 있네요. Set-Cookie header 입니다. 보아하니 이름, 만료일시, 경로, 그리고 도메인정보를 가지고 있네요.  

브라우저에서 쿠키를 저장하도록 설정이 되어있으면 브라우저는 이런 정보들을 만료일 전까지 저장하게 됩니다.만약 사용자가 쿠키에 설정된 경로로 접속을 하게되면 브라우저는 서버로 그 쿠키를 재전송합니다. 그 브라우저의 헤더는 다음과 같은 정보를 갖고 있을 겁니다. 

GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz

이제 JSP script 는 request method중 하나인 request.getCookies() 를 통해서 쿠키에 접근할 수 있습니다. 

 

Servlet Cookies 메소드

아래 메소드들은 JSP에서 쿠키를 다룰때 사용될 수 있는 메소드목록 및 기능입니다.

 

S.N.Method & Description
1public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.
2public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.
3public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.
6public void setValue(String newValue)
This method sets the value associated with the cookie.
7public String getValue()
This method gets the value associated with the cookie.
8public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9public String getPath()
This method gets the path to which this cookie applies.
10public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.


 JSP로 쿠키 설정하기

JSP로 쿠키를 설정하려면 아래와 같은 단계를 거칩니다.

 

(1) Cookie 객체 생성 : You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

자바에서 쿠키 생성하는거랑 똑같습니다. 그런데 여기서 name과 value ( "key"가 name인거고 "value"가 value가 되겠죠)에는 절대로 스페이스(빈칸)이나 아래에 나열된 특수문자가 사용될 수 없습니다.  

[ ] ( ) = , " / ? @ : ;

(2) Max age 설정 : 초 단위로 max age를 설정합니다. 이 쿠키가 살아있을 수 있는 시간을 설정하는거죠. 아래는 24 시간동안 존재할 수 있는 쿠키를 설정하는 예제입니다.

cookie.setMaxAge(60*60*24);

(3) Cookie를 HTTP response header에 추가하기 : response.addCookie 메소드를 이용하면 추가하 수 있습니다.  

response.addCookie(cookie);

예제

<% // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>

 main.jsp 파일에 위 코드를 넣어주세요. 그리고 다음 코드는 hello.jsp파일에 넣어주세요. 

<html> <body> <form action="main.jsp" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>

두 jsp파일을 <Tomcat-installation-directory>/webapps/ROOT 디렉토리에 넣어주세요.

이제 http://localhost:8080/hello.jsp 에 접속을 해보세요.

 

 

 

이런게 나오나요? 이제 이름을 넣고 submit버튼을 눌러보세요. 

그럼 예전에 봤던 것처럼 퍼스트 네임과 래스트 네임이 출력이 될겁니다. 그런데 여기서 이녀석이 몰래하는 작업이 또 있습니다. 눈에는 보이지 않았지만 first_name과 last_name이라는 쿠키를 생성한것입니다. 그리고 submit버튼이 또 눌리게 될 경우 방금 만들어진 쿠키들이 서버쪽으로 전송되게 되겠죠. 

자, 그럼 이제 서버쪽으로 전송되는 쿠키정보를 JSP에서 읽어오는 것을 한번 해보겠습니다. 


JSP를 이용하여 쿠키정보 읽어오기

쿠키를 읽으려면 HttpServletRequest 의 getCookies( ) 메소드를 호출하기만 하면 됩니다. 이 메소드는 Cookie[]를 반환합니다. 한번에 여러개의 쿠키가 전송될 수 있다는 것이죠. 그럼 루프를 돌면서 전송된 쿠키의 정보를 출력하는 예제를 한번 보도록 하겠습니다.  


예제

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println("<h2>No cookies founds</h2>"); } %> </body> </html>

위 코드를 main.jsp 파일에 넣고 접속해보세요. 쿠키에 설정한 값들이 나오겠죠? 아래처럼 말이죠.


Found Cookies Name and Value

Name : first_name, Value: 홍길동은
Name : last_name, Value: 플레이보이


JSP를 이용한 쿠키 삭제

이번에는 쿠키를 삭제해보도록 하겠습니다. 뭐 쿠키삭제는 브라우저에서도 할 수 있는 기능이긴 하지만 그래도 한번 읽어나 보세요. 웹개발자라면 쿠키 다루는 법은 잘 알고 있어야 할 테니까요. 

  • 쿠키를 읽어와서 쿠키객체에 저장합니다.

  • 쿠키의 나이를 0으로 만들어버리세요. setMaxAge() 메소드를 사용하면 되는건 아시죠?

  • 이 쿠키를 다시 response에 넣어 되돌려보내세요.


예제

아래 예제는 "first_name" 쿠키를 삭제하는 main.jsp 소스입니다. 삭제된 후에 이 쿠키를 다시 읽어오려고하면 null이 나올겁니다.

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie: " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } %> </body> </html>

이제 main.jsp를 요청해보세요. http://localhost:8080/main.jsp 주소로 요청하면 되겠죠? 그럼 아래처럼 결과가 나올 거에요.


Cookies Name and Value

Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

 

 http://localhost:8080/main.jsp 를 다시한번 요청하면 아래와 같은 결과를 보게 될 거에요.

 

Found Cookies Name and Value

Name : last_name, Value: Player

 

first_name 쿠키는 삭제되어서 안나오네요.

 

어때요? 쉽죠잉?  

 




 

 

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

 

💻 Programming/JSP

[JSP] Filters ( 필터 사용하기 )

Servlet과 JSP 필터는 서블릿과 JSP프로그래밍에서 아래와 같은 목적으로 사용될 수 있는 Java 클래스입니다.

  • 클라이언트로부터의 요청이 백엔드로 가기 전에 가로채기 위해서

  • 서버로부터의 응답이 클라이언트로 보내지기 전에 조작하기 위해서

아래는 많이 사용되는 필터들의 종류입니다.

  • Authentication Filters.

  • Data compression Filters

  • Encryption Filters .

  • Filters that trigger resource access events.

  • Image Conversion Filters .

  • Logging and Auditing Filters.

  • MIME-TYPE Chain Filters.

  • Tokenizing Filters .

  • XSL/T Filters That Transform XML Content.

Filter는 deployment descriptor 파일인 web.xml을 통해서 디플로이 되고 servlet 이나 JSP에 매핑이 됩니다. web.xml 파일은 <Tomcat-installation-directory>\conf 디렉토리에서 찾으실 수 있습니다.

JSP 컨테이너가 웹애플리케이션을 시작할 때, 컨테이너는 각 필터의 인스턴스를 생성합니다. 당신이 deployment descriptor에 선언한 필터들을 말이죠. 그 필터들은 정의된 순서대로 실행이 됩니다. 


Servlet Filter Methods:

필터는 간단히 말해서 그냥 Java 클래스입니다.  javax.servlet.Filter 인터페이스를 구현한 클래스라고 할 수 있죠. The javax.servlet.Filter interface 는 아래의 세가지 메소드를 선언하고있습니다.

S.N.Method & Description
1public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
2public void init(FilterConfig filterConfig)
This method is called by the web container to indicate to a filter that it is being placed into service.
3public void destroy()
This method is called by the web container to indicate to a filter that it is being taken out of service.


JSP Filter 예제

아래는 JSP Filter 예제입니다. 무엇을 하는고 하니, 요청이 들어올 때마다 클라이언트의 IP주소를 프린트하고 현재 시간을 뿌려줍니다. 이 예제를 통해서 JSP Filter의 기본적인 사용법을 익힐 수 있을거에요.  

// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time " + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ){ /* Called before the Filter instance is removed from service by the web container*/ } }

이제 LogFilter.java를 컴파일하고 LogFilter.class 파일을 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes 디렉토리에 넣어주세요. 그리고 아래에서 매핑시켜주는 작업을 더 해야합니다. 


JSP Filter Mapping in Web.xml:

web.xml 에서 필터를 매핑할 때는 아래처럼 사용하시면 됩니다.

<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

위 소스처럼 매핑하면 모든 서블릿과 JSP에 적용이 됩니다.  url pattern에서 /* 이 의미하는 것이 모든 것이기 때문입니다. 즉, 이곳에 특정 servlet 이나 JSP를 넣어 줄 수도 있다는 말이죠.

이제 JSP페이지를 요청하면 웹서버 로그에서 생성된 로그를 보실 수 있습니다.  Log4J 로거를 사용해서 다른 파일에 로그를 기록할 수도 있다는점도 참고하시기 바랍니다.


Filter 여러개 사용하기

여러개의 필터를 사용해야 한다면 아래처럼 사용하시면 됩니다. 각각의 필터를 정의하고 각각 매핑을 하는거죠. 

<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Filters Application Order:

필터의 적용 순서를 바꿀 수도 있습니다. 먼저 정의된 필터가 먼저 적용이 되는거죠. 위 예제에서는 LogFilter가 AuthenFilter보다 우선 적용이 되는거고 아래 예제에서는 AuthenFilter가 LogFilter보다 우선 적용됩니다.

<filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

 

 

 

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

 

💻 Programming/JSP

[JSP] Form 데이타 처리

웹브라우저에서 웹서버로 요청을 보내는 일반적인 방법은 두가지가 있습니다. GET방식과 POST방식이 그것이죠.  

RESTFUL에서는 더 많은 방식이 있지만 여기서는 GET 과 POST에 대해서만 JSP로 핸들링 하는 방법에 대해 알아보도록 하겠습니다.

 

JSP를 이용한 FORM 데이터 읽기

웹브라우저에서 form데이타를 이용해서 요청을 보내면 JSP에서 그 form 데이터를 읽을 수 있습니다. 이때 사용할 수 있는 메소드들은 아래와 같습니다. 

  • getParameter(): You call request.getParameter() method to get the value of a form parameter.

  • getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.

  • getParameterNames(): Call this method if you want a complete list of all parameters in the current request.

  • getInputStream(): Call this method to read binary data stream coming from the client.


URL을 이용한 GET방식 예제

아래 URL은 get방식으로 데이터를 웹서버로 넘겨주고 있습니다. first_name이라는 변수에 "길동"라는 값이 들어있고 "홍"이라는 변수에 ALI라는 값이 들어있다고 생각하시면 됩니다. 

http://localhost:8080/main.jsp?first_name=길동&last_name=홍

 

그리고 아래는 main.jsp 의 소스입니다.  getParameter() 메소드를 이용해서 브라우저에서 넘겨준 데이터를 받아오는 기능입니다.

<html> <head> <title>Using GET Method to Read Form Data</title> </head> <body> <center> <h1>Using GET Method to Read Form Data</h1> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>

이제 웹브라우저에서 http://localhost:8080/main.jsp?first_name=길동&last_name=홍 을 타이핑해서 웹서버로 요청을 해보세요. 아래와 같은 결과가 나올 것입니다. 

 

Using GET Method to Read Form Data

  • First Name: 길동

  • Last Name: 홍


Form을 이용한 GET 방식 예제

아래는 HTML 태그 중에서 form태그를 이용한 get방식 요청 예제입니다. 

<html> <body> <form action="main.jsp" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>

위 소스를 Hello.htm파일에 작성하고 <Tomcat-installation-directory>/webapps/ROOT 디렉토리에 넣어주세요. 

http://localhost:8080/Hello.htm 를 웹브라우저에서 요청하면 아래처럼 화면에 보여집니다.  


 

이제 빈박스에 이름을 입력하고 submit버튼을 눌러보세요. 버튼을 누르면 main.jsp에 데이터를 보내고 그 데이터를 main.jsp에서 처리합니다 

처리된 결과는 위에서 실행한 결과와 동일하게 나올 것입니다.

 

 

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