jsp (22)

이클립스에서 스프링부트 기반으로 JSP개발하기

안녕하세요, 오늘은 스프링부트 기반으로 JSP개발을 할 수 있는 환경을 세팅하는 과정을 알려드리겠습니다.

최근에 대규모의 웹 개발은 백엔드와 프론트엔드를 구분해서 별도의 프로젝트로 구성하거나 모듈로 나누어 개발을 진행하고 있습니다.

어떻게 개발을 하던지 결국 백엔드와 프론트엔드를 완전히 분리하여 개발하게되죠. 하지만 그렇게까지 할 필요가 없는 작은 프로젝트들은 굳이 그렇게 나누어 개발을 할 필요가 없습니다. 그렇게 구분을 하는 것이 오히려 유지보수를 힘들게 하는 원인이 되기도 하죠.

오늘은 하나의 스프링부트 프로젝트를 만들고 JSP를 사용할 수 있도록 세팅하는 부분까지 알려드립니다.

개발에 필요한 준비물은 아래와 같습니다.

 

1. Eclipse (2020년 7월 기준 최신버전 다운로드)

Version: 2020-09 M1 (4.17.0 M1)

 

2. Spring Tools plugin (설치방법)

 

이렇게만 있으면 일단 준비는 완료입니다.

 

이제 새로운 프로젝트를 생성합니다. 현재 이클립스를 처음 설치하신 분이라면 패키지 탐색기(Project Explorer)에 아래와 같이 나오는데 여기서 밑에서 두 번째에 있는 Create a project...를 선택합니다. 만약 이미 프로젝트를 만들어 놓은게 있는 분들이라면 그냥 탐색기 창에서 우클릭해서 New > Project 를 선택하시면 됩니다.

아래와 같이 새 프로젝트 생성 마법사가 뜨면 spring 으로 검색을 해서 Spring Starter Project를 선택합니다.

 

이제 만들 프로젝트의 이름을 Name 항목에 적어줍니다. 그리고 Java Version 은 11로 선택해줍니다. (8로 해도 무방합니다)

 

Spring Boot의 버전을 선택할 수 있는데 이 부분은 그대로 놔두고 Available 검색창에서 web이라고 검색하여 Spring Web을 선택해줍니다. (이외에도 lombok이나 데이터 베이스 드라이버, MyBatis 등 유용한 기능들을 선택하여 사전설치가 가능합니다만 여기서는 선택하지 않습니다.)

 

Finish 버튼을 누르면 아래와 같은 구조를 갖는 프로젝트를 생성해줍니다.

이제 MyDemoApplication.java 파일을 열어 아래와 같이 수정해줍니다.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MyDemoApplication extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(MyDemoApplication.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(MyDemoApplication.class, args);
	}

}

SpringBootServletInitializer를 상속하고 configure 메서드를 오버라이드하였습니다.

 

그리고 pom.xml 파일에 아래 의존성을 추가해줍니다. jasper는 JSP 파일을 컴파일 해주는 기능을 합니다.

<!-- Need this to compile JSP -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

 

이제 프로젝트명에서 우클릭하고 "src/main/webapp" 새 폴더를 하나 만듭니다. 이렇게 폴더를 만들면 아래와 같이 생성됩니다.

 

이제 다시 우클릭하여 build path 설정(Configure Buildpath...)화면으로 들어갑니다.

 

Add Folder... 를 클릭하고 webapp 디렉토리를 찾아 체크해줍니다.

OK 버튼을 누르고 Apply하면 프로젝트 구조가 아래와 같이 바뀐것을 확인할 수 있습니다.

이제 webapp 아래에 WEB-INF디렉토리를 생성하고 하위에 또 views 라는 디렉토리를 생성합니다. 그리고 test.jsp 파일을 만들어 아래와 같이 작성해줍니다.

<%@ page import="java.util.*" %>

<!DOCTYPE html>
<html>
<body>
	<h1>Test Page</h1>
	Today's date: <%= new Date() %>
</body>
</html>

 

application.properties 파일에는 다음과 같이 두 라인을 추가해줍니다.

spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp

 

자, 이제 마지막으로 해당 페이지와 연결할 API를 작성합니다. root package에서 controller 라는 패키지를 하나 만들고 그 아래에 DemoController.java를 아래와 같이 작성합니다.

package com.example.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;


@Controller
public class DemoController {
	
	@GetMapping("/test")
	public String login() {
		return "/test";
	}
}

 

여기까지 완료되었으면 이제 Run As > Java Application 또는 Run As > Spring Boot App 으로 기동시켜줍니다.

그리고 localhost:8080/test 에 접속하면 아래와 같이 jsp 페이지가 뜨는 것을 확인할 수 있습니다.

 

JSP 페이지에 javascript 및 css 파일 연동

이제 JSP 페이지에 javascript 파일 및 css 파일을 연결시켜보겠습니다.

javascript와 css 파일은 src/main/resources 하위의 static 폴더 안쪽에 몰아넣어주면 됩니다.

우선 static 폴더 하위에 script 폴더를 만들어 test.js파일을 생성하고 아래 내용을 작성합니다.

$(document).ready(function() { printCurrentDatetime(); });

function printCurrentDatetime() {
	let date = new Date();
	$('#currentTime').html(date);
	setTimeout(printCurrentDatetime, 1000);
}

 

그리고 static 폴더 하위에 style 폴더를 만들어 test.css 파일을 생성하고 아래와 같이 작성합니다.

@charset "UTF-8";

body {background-color:cornflowerblue;}

 

자, 더이상 파일을 만들 필요는 없습니다. 마지막으로 JSP 파일에 위에서 작성한 두 파일을 연결시켜주겠습니다.

test.jsp 파일을 열어 아래와 같이 수정해줍니다.

<%@ page import="java.util.*"%>

<!DOCTYPE html>
<html>
<head>

<!-- JS link -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script/test.js"></script>

<!-- CSS link -->
<link href="style/test.css" rel="stylesheet">

</head>
<body>
	<h1>Test Page</h1>
	Today's date: <span id='currentTime'></span>
</body>
</html>

 

변경한 내용은 다음과 같습니다.

1. html의 body 안에 있던 스크립트 코드를 test.js로 옮기면서 refresh 기능을 추가

2. test.js파일에서 jquery를 사용하기 때문에 html페이지(jsp파일)에 jQuery 라이브러리 링크 추가

3. css 링크를 추가하고 body의 백그라운드 색상을 cornflowerblue 로 설정

 

여기까지 작업이 완료되면 최종적으로 아래와 같은 패키지 구조를 갖게됩니다.

SpringBoot + JSP 연동 최종 프로젝트 구조

 

여기까지 잘 따라오셨다면 실행시켰을 때 아래와 같이 현재시간이 계속 업데이트되는 파란 화면을 볼 수 있습니다. 😊

 

최종 완료 화면

 

이상으로 Eclipse에서 SpringBoot와 JSP를 연동하여 웹프로젝트를 구성하는 방법을 알아보았습니다.

 

JSP와 Javascript의 차이가 뭘까요? 라는 질문을 받은 적이 있습니다.

초보자 분들이 충분히 할만한 질문이죠. JSP도 자바스크립트도 제대로 사용해보기 전에는 두 가지가 뭐가 다른지 잘 모를 수 있습니다.

 

초보자 분들이 이해할 정도로 간략하고 쉽게 요점만 설명드리겠습니다.

 

Javascript웹브라우저(사용자의 컴퓨터)에서 실행이되는 스크립트 언어입니다.

자바스크립트 파일은 .js 확장자를 가지며, 자바스크립트 문법에 따라 작성을 해야합니다.

프로그래밍 언어 중 하나라고 생각하시면 됩니다.

반면, JSP는 Java Server Page의 약자로 .jsp 확장자를 가지며, 언어의 종류를 나타내는 것은 아닙니다.

.jsp 파일에는 html태그와 javascript 함수도 사용이 가능하며, 추가로 아래와 같이 <% java code %> 형태로 자바문법을 사용할 수 있습니다.

 

<html>

<head><title>Hello World</title></head>

<body> Hello World!<br/>

<% out.println("Your IP address is " + request.getRemoteAddr()); %>  <!-- 여기가 JSP 문법 -->

</body>

</html>

 

JSP에 작성된 내용은 서버에서 실행되고, 그 결과가 웹브라우저(사용자 컴퓨터)로 전송됩니다.

 

이제 JSP와 자바스크립트의 차이점이 뭔지 아시겠죠?

 

가시기 전에 공감 꾸~~~~욱 눌러주고 가세요 ^-^

💻 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 

 

💻 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