JSP

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
    
    <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
              username="java" password="1111" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
              
             
</Context>

 

 

SQL


create table book(
     id number not null,
     title varchar2(50),
     author varchar2(20),
     price number default 0,
     qty number default  0,
     primary key(id)
);


-- nvl(A, B)  A 가 null 이면 B

insert INTO BOOK (ID, TITLE, AUTHOR, PRICE, QTY) 
values ( (select nvl(max(id)+1,1) from book), 'os', 'wiley', 30700, 50 ) ;

insert INTO BOOK (ID, TITLE, AUTHOR, PRICE, QTY) 
values ( (select nvl(max(id)+1,1) from book), '자바', '영진', 30000, 30 ) ;


insert INTO BOOK (ID, TITLE, AUTHOR, PRICE, QTY) 
values ( (select nvl(max(id)+1,1) from book), 'jsp', '한빛', 20700, 20 ) ;


insert INTO BOOK (ID, TITLE, AUTHOR, PRICE, QTY) 
values ( (select nvl(max(id)+1,1) from book), '스프링', '영진', 10700, 10 ) ;


insert INTO BOOK (ID, TITLE, AUTHOR, PRICE, QTY) 
values ( (select nvl(max(id)+1,1) from book), '안드로이드', '한빛',40700, 60 ) ;


select * from book;

commit;


 

 

 

class DB

package config;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DB {

	public static Connection getConn(){
		
		DataSource ds =null;//javax.sql.DataSource
		Connection conn=null;
		try{
			//context.xml 파일을 분석하는 객체
			Context context = new InitialContext();
// context.xml 파일의 Resource 태그의 name 속성 검색	
// java:comp/env/리소스태그의name			
			ds=(DataSource)context.lookup("java:comp/env/jdbc/myoracle");
// 커넥션풀에서 커넥션을 리턴받음			
			conn=ds.getConnection(); 
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}
	
	
}

 

class Constants 

package config;

public class Constants {
	public static final int MAX=100;
}

 

class BookDAO

package book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import config.DB;

public class BookDAO {

	//single ton 으로 객체
	public static BookDAO dao;
	public static BookDAO getDao(){
		if(dao==null){
			dao=new BookDAO();
		}
		return dao;
	}
	private BookDAO(){}//private 생성자
	
	public ArrayList<BookDTO> bookList(){
		ArrayList<BookDTO> items =new ArrayList<>();
		Connection conn=null;
		PreparedStatement pstmt =null;
		ResultSet rs=null;
		try{
			conn=DB.getConn();
			String sql="select * from book";
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next()){
				BookDTO dto =new BookDTO();
				dto.setAuthor(rs.getString("author"));
				dto.setId(rs.getInt("id"));
				dto.setPrice(rs.getInt("price"));
				dto.setQty(rs.getInt("qty"));
				dto.setTitle(rs.getString("title"));
				items.add(dto);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(rs!=null)rs.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			try{
				if(pstmt!=null)rs.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			try{
				if(conn!=null)rs.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}
	
	
	
	
	
	
	
}

 

class BookDTO

package book;

public class BookDTO {

	private int id;
	private String title;
	private String author;
	private int price;
	private int qty;
	
	public BookDTO() {
	
	}

	public BookDTO(int id, String title, String author, int price, int qty) {
		super();
		this.id = id;
		this.title = title;
		this.author = author;
		this.price = price;
		this.qty = qty;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public int getQty() {
		return qty;
	}

	public void setQty(int qty) {
		this.qty = qty;
	}

	@Override
	public String toString() {
		return "BookDTO [id=" + id + ", title=" + title + ", author=" + author + ","
				+ " price=" + price + ", qty=" + qty
				+ "]";
	}
	
	

	
	
	
	 
}

 

 

 

date.jsp


<!--  page directive(페이지 지시어) : jsp 페이지의 정보 -->
<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.Date"%>

    
<!-- date.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>
<body>
<%
//scriptlet(스크립틀릿, jsp 코드 조각)
	Date nowDate=new Date(); //날짜 객체 생성
	//out 객체 : jsp 의 내장객체
	//(웹브라우저에 html 로 출력시기크는 역할)
	out.println(nowDate+ "<br>");
//yyyy연도, MM 월 dd 날짜 a 오전/ 오후 HH 시간
	SimpleDateFormat dateFormat =
	new SimpleDateFormat("yyyy년 MM월 dd일 a HH:mm:ss ");
//날짜형식.format(날짜객체) 날짜출력형식에 맞는 스트링변환
	String formatDate=dateFormat.format(nowDate);	
%>
<%-- <%= 출력문 %>, 표현식(expression) --%>
현재 날짜는 <%= formatDate %> 입니다. <br>
<!-- 서블릿의 정보 -->
<%= getServletInfo() %><br>
<!-- jsp가 실제 서비스되는 경로 확인
application 내장객체, 웹서버의 정보 -->
<%= application.getRealPath("/") %>
</body>
</html>

 

=>출력

Fri May 19 17:56:26 KST 2017
현재 날짜는 2017년 05월 19일 오후 17:56:26 입니다. 
Jasper JSP 2.3 Engine
D:\dev\jsp_hms(2017-05-19)\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\web03_jsp\

 

 

 

 

color.jspf

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  <!-- color.jspf , fragment 코드조각 -->

<%
	String bodyback_c ="#e0ffff";
	String back_c="#8fbc8f";
	String title_c="#5f9ea0";
	String value_c="#b0e0e6";
	String bar="#778899";

%>

  

 

test.jsp

<%@page import="config.DB"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
 String str="hello jsp";
%>



<%=

	DB.getConn()
%>


출력=>

705313167, URL=jdbc:oracle:thin:@127.0.0.1:1521:xe, UserName=JAVA, Oracle JDBC driver

 

 

 

declarationTest.jsp

<%@page import="config.DB"%>
<%@page import="book.BookDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>


<%
//jspService() method의 지역변수
String str1 ="java";
%>
<%=str1 %>

<%!//선언분
String str2="hello"; //전역변수(멤버변수)
String getStr2(){//method
	return str2;
}

%>
<%=str2 %>
<%=getStr2() %>


</body>
</html>

 

 

=>출력

 

java hello hello

 

 

 

 

 

includeDirective.jsp

<%@page import="book.BookDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="book.BookDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!-- color.jsf 파일을 현재 페이지에 포함시킴 -->
<%@ include file="color.jspf" %>    
<%@ page import="config.Constants" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
body{
	background:<%= bodyback_c %>;
}
</style>
</head>
<body>
<h2>페이지 모듈화</h2>
최대값 : <%=Constants.MAX %>

<!-- jsp action tag(액션태그) -->
<!-- 2개의 파일로 각각 컴파일됨 (변수 공유 안됨) -->
<%-- <jsp:include page="test.jsp"></jsp:include> --%>
<!-- 에러가 발생함 -->

<%@ include file="test.jsp" %>
<h2><%=str %></h2>

<!-- 이클립스의 개발 디렉토리가 아닌 실제 서비스 -->
<%=application.getRealPath("/") %>

<p>
<%

	BookDAO dao =BookDAO.getDao();
	ArrayList<BookDTO> items=dao.bookList();
	out.println("<ul>");
	for(BookDTO dto : items){
		out.println("<li>"+dto.getTitle()+"</li>");
	}
	out.println("</ul>");
%>


</body>
</html>



 

=>출력

 

 

페이지 모듈화

최대값 : 100 1799333991, URL=jdbc:oracle:thin:@127.0.0.1:1521:xe, UserName=JAVA, Oracle JDBC driver

hello jsp

D:\dev\jsp_hms(2017-05-19)\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\web03_jsp\

 

  • os
  • 자바
  • jsp
  • 스프링
  • 안드로이드
  • 안드로이드

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

아무 것도 없는 것 속에 무진장하게 들어 있는 것이 우주이다. -화엄경

댓글 ( 4)

댓글 남기기

작성