이안의 평일코딩

JSP 1일차 - 웹사이트 제작 본문

Back-end/JSP

JSP 1일차 - 웹사이트 제작

이안92 2020. 8. 24. 11:40
반응형

2020.08.24(월)

 

basic.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%--
	JSP : Java Server Page => 서버에서 실행되는 자바파일
	=====
	JSP의 구성요소
	  1. 지시자
	  	= page : JSP파일에 대한 정보 
	  	= tablib : 태그로 자바의 문법
	  				===> 제어문 <c:forEach> <c:if>
	  	     자바 + HTML (HTML기반 자바가 첨부)
	  	     
	  	     자바 영역 <% %>
	  	  <html>
	  	    <body>
	  	      <h1>게시판</h1>
	  	       <ul>
	  	       <%
	  	       for(BoardVO vo:list){
			   %>
	  	      	 <li>번호-제목-이름-작성일-조회수</li>
	  	       <%
	  	       }
	  	       %>
	  	       </ul>
	  	    </body>
	  	  </html>
	  	  
	  	  
	  	  tablib
	  	  
	  	  <html>
	  	    <body>
	  	      <h1>게시판</h1>
	  	       <ul>
	  	        <c:forEach items="list">
	  	      	 <li>번호-제목-이름-작성일-조회수</li>
	  	        </c:forEach>
	  	       </ul>
	  	    </body>
	  	  </html>
	  	  
	  	= include : 특정 JSP안에 JSP를 첨부
	  	
	 2. 자바 코딩 부분
	    = 스크립트릿 <% %> => 일반 자바 코딩
	    = 표현식       <%= %> => out.println() : 화면에 값을 출력
	    = 선언식       <%! %> => 전역변수, 메소드를 만들 경우 (사용빈도가 적다)
	 
	 3. 내장 객체 (8개 지원) : 미리 객체를 생성해 놓고 필요시마다 사용이 가능하게 만들어 준다
	    = request : 사용자의 요청값
	    = response : 서버=> 처리=> 응답
	    ==========================
	    = session 
	    = pageContext
	    = page
	    = config
	    = exception
	    = application
	 4. 표현식 (EL, JSTL)
	 5. MVC
--%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
  String name="홍길동";
  out.println(name);
%>
</body>
</html>

 

basic1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, java.text.*"
    errorPage="error.jsp" buffer="8kb"
    %>
<%-- <%@ page import="java.util.*" %>
<%@ page import="java.text.*" %> --%>
    <%--
    	** 지정된 속성에 값을 채운다
    	<%@ page 속성 = "값" 속성="값"...
    
     --%>
    <%--
    	JSP 시작점
    	지시자
    		1. page : JSP의 기본 정보
    		   = contentType="text/html; charset=UTF-8"
    		     ============
    		     브라우저에 HTML을 전송한다 (브라우저에서 HTML파싱준비)
    		     브라우저 실행 contentType = "text/html" => 화면에 출력
    		     		 contentType = "text/xml" => 문서저장
    		     		 charset=UTF-8 => charset=ISO-8859_1
    		     		 						  ==========
    		     		 						  ASC(영문)
    		   response.setContentType("text/html;charset=EUC-KR")
    		2. import : 이미 만들어진 클래스를 읽어 올 때 사용
    		            (라이브러리 로드)
     --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <%
  	int a=10/0;
  %>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<center>
	  <h1>시스템에서 오류가 발생하였습니다</h1>
	</center>
</body>
</html>

                         톰캣이 만들어줌

basic.jsp => basic_jsp.java => basic_jsp.class

======                           =========> servlet

doGet, doPost

 

 

basic2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, java.text.*" %>
    <%--
    	일반 자바코딩 : <% %>
    	화면 출력 : <%= %> (out.println())
     --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
 	// 자바영역 => 문법이 자바와 동일
 	// 변수 선언 (지역변수) => int i=0;
 	// 객체 메모리 할당 => Date date = new Date()
    // 제어문
    Date date = new Date();
 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 	String today = sdf.format(date);
 %>
 <%--
 	<%= today %> out.println(today);
 	%=안에는 세미콜론(;) 찍으면 안됨.
  --%>
 오늘 날짜는 <%=today %> 입니다
 오늘 날짜는 <% out.println(today); %>입니다
</body>
</html>

 

 

 

gugudan.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<center>
		<h1>구구단</h1>
		<table width=560 border="1">
			<tr>
			<%
				for(int i=2; i<=9; i++){
			%>
				<th>
					<%= i+"단" %>
				</th>
			<%
				}
			%>
			</tr>
			<%
				for(int i=1; i<=9; i++){ //줄수
			%>
				<tr>
			<%
				for(int j=2; j<=9; j++){ //데이터 출력
			%>
				<td><%= j+"*"+i+"="+j*i %></td>
			<%	
					}
			%>
				</tr>
			<%
				}
			%>
		</table>
	</center>
</body>
</html>
<%--
	 <c:forEach var=i begin=1 end=9
		<tr>
		 <c:forEach var=j begin=2 end=9>
		 	<td></td>
		 </c:forEach>
		</tr>
	 </c:forEach>
 --%>

 

MusicVO

package com.sist.dao;
/*
MNO          NUMBER(3)      
TITLE        VARCHAR2(300)  
SINGER       VARCHAR2(100)  
ALBUM        VARCHAR2(200)  
POSTER       VARCHAR2(1000) 
STATE        CHAR(6)        
IDCREMENT    NUMBER(3)      
KEY          VARCHAR2(50)
 */

public class MusicVO {
	private int mno;
	private String title;
	private String singer;
	private String album;
	private String poster;
	private String state;
	private int idcrement;
	private String key;
	public int getMno() {
		return mno;
	}
	public void setMno(int mno) {
		this.mno = mno;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSinger() {
		return singer;
	}
	public void setSinger(String singer) {
		this.singer = singer;
	}
	public String getAlbum() {
		return album;
	}
	public void setAlbum(String album) {
		this.album = album;
	}
	public String getPoster() {
		return poster;
	}
	public void setPoster(String poster) {
		this.poster = poster;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public int getIdcrement() {
		return idcrement;
	}
	public void setIdcrement(int idcrement) {
		this.idcrement = idcrement;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	
}

MusicDAO

package com.sist.dao;
/*
 * 제어문(출력), 변수(데이터 모으기), 예외처리(오라클 연결)
 * 오라클 연결 => ArrayList => add(), get(), size()
 * => 출력 => for-each
 */

import java.sql.*; // Connection, PreparedStatement, ResultSet
import java.util.*; // ArrayList

public class MusicDAO {
	// 연결
	private Connection conn;
	// SQL 전송
	private PreparedStatement ps;
	// 오라클 주소
	private final String URL="jdbc:oracle:thin:@localhost:1521:XE";
	// 1. 실제 오라클 연결해주는 드라이버 oracle.jdbc.driver.OracleDriver
	public MusicDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			// 드라이버를 이용해서 연결 => thin드라이버
		}catch(Exception ex) {}
	}
	// 2. 연결 메소드
	public void getConnection() {
		try {
			conn=DriverManager.getConnection(URL,"hr","happy");
			//conn hr/happy
		}catch(Exception ex) {}
	}
	// 3. 닫는 메소드
	public void disConnection() {
		try {
			if(ps!=null) ps.close();
			if(conn!=null) conn.close();
			// exit
		}catch(Exception ex) {}
	}
	// DAO(JDBC => 기본 셋팅)
	// 기능 => MusicTop200
	public ArrayList<MusicVO> musicAllData(){
		ArrayList<MusicVO> list = new ArrayList<MusicVO>();
		try {
			getConnection(); // 연결
			// SQL문장 전송
			String sql = "SELECT mno, title, singer, album, poster "
					+"FROM genie_music ORDER BY mno";
			ps = conn.prepareStatement(sql);
			// 결과값 받기
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				MusicVO vo = new MusicVO();
				vo.setMno(rs.getInt(1));
				vo.setTitle(rs.getString(2));
				vo.setSinger(rs.getString(3));
				vo.setAlbum(rs.getString(4));
				vo.setPoster(rs.getString(5));
				
				list.add(vo);
			}
			rs.close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			disConnection();
		}
		return list;
	}
	
	public ArrayList<MovieVO> movieAllData(){
		ArrayList<MovieVO> list = new ArrayList<MovieVO>();
		try {
			getConnection(); // 연결
			// SQL문장 전송
			String sql = "SELECT no, title, poster, regdate, genre, grade, actor, score, director "
					+"FROM daum_movie WHERE cateno=1 ORDER BY no";
			ps = conn.prepareStatement(sql);
			// 결과값 받기
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				MovieVO vo = new MovieVO();
				vo.setNo(rs.getInt(1));
				vo.setTitle(rs.getString(2));
				vo.setPoster(rs.getString(3));
				vo.setRegdate(rs.getString(4));
				vo.setGenre(rs.getString(5));
				vo.setGrade(rs.getString(6));
				vo.setActor(rs.getString(7));
				vo.setScore(rs.getString(8));
				vo.setDirector(rs.getString(9));
				list.add(vo);
			}
			rs.close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			disConnection();
		}
		return list;
	}
	// 영화 => 출력 
}

music.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,com.sist.dao.*"%>
    <%
    	MusicDAO dao = new MusicDAO();
    	// 데이터 받기
    	ArrayList<MusicVO> list = dao.musicAllData();
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Genie Music</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function(){
	$('#keyword').keyup(function(){
		var k=$(this).val();
		$('#user-table > tbody > tr').hide();
		var temp=$('#user-table > tbody > tr > td:nth-child(5n+3):contains("'+k+'")');
		$(temp).parent().show();
	});
});
</script>
</head>
<body>
	<center>
		<h1>Music Top200</h1>
		<table width=800>
			<tr>
			  <td>
			    <input type=text id=keyword size=25>
			  </td>
			</tr>
		</table>
		<table border=1 width=800 id="user-table">
			<tr>
				<th>순위</th>
				<th></th>
				<th>제목</th>
				<th>가수명</th>
				<th>앨범</th>
			</tr>
			<tbody>
			<%
				for(MusicVO vo:list){
			%>
				<tr>
					<td><%= vo.getMno()%></td></td>
					<td><img src=<%=vo.getPoster() %> width=30 height=30></td>
					<td><%= vo.getTitle()%></td>
					<td><%= vo.getSinger()%></td>
					<td><%= vo.getAlbum()%></td>
				</tr>
			<%
				}
			%>
			</tbody>
		</table>
	</center>
</body>
</html>

MovieVO

package com.sist.dao;
/*
 * NO       NOT NULL NUMBER        
CATENO            NUMBER        
TITLE    NOT NULL VARCHAR2(200) 
POSTER   NOT NULL VARCHAR2(300) 
REGDATE           VARCHAR2(200) 
GENRE    NOT NULL VARCHAR2(100) 
GRADE    NOT NULL VARCHAR2(100) 
ACTOR             VARCHAR2(100) 
SCORE             VARCHAR2(20)  
DIRECTOR NOT NULL VARCHAR2(100) 
STORY             CLOB          
KEY               VARCHAR2(50)  
 */
public class MovieVO {
	private int no;
	private int cateno;
	private String title;
	private String poster;
	private String regdate;
	private String genre;
	private String grade;
	private String actor;
	private String score;
	private String director;
	private String story;
	private String key;
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public int getCateno() {
		return cateno;
	}
	public void setCateno(int cateno) {
		this.cateno = cateno;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getPoster() {
		return poster;
	}
	public void setPoster(String poster) {
		this.poster = poster;
	}
	public String getRegdate() {
		return regdate;
	}
	public void setRegdate(String regdate) {
		this.regdate = regdate;
	}
	public String getGenre() {
		return genre;
	}
	public void setGenre(String genre) {
		this.genre = genre;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getActor() {
		return actor;
	}
	public void setActor(String actor) {
		this.actor = actor;
	}
	public String getScore() {
		return score;
	}
	public void setScore(String score) {
		this.score = score;
	}
	public String getDirector() {
		return director;
	}
	public void setDirector(String director) {
		this.director = director;
	}
	public String getStory() {
		return story;
	}
	public void setStory(String story) {
		this.story = story;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	
}

movie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,com.sist.dao.*"%>
    <%
    	MusicDAO dao = new MusicDAO();
    	ArrayList<MovieVO> list = dao.movieAllData();
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Daum Movie</title>
</head>
<body>
<center>
		<h1>현재상영영화</h1>
		<table border=1 width=1600 id="user-table">
			<tr>
				<th>순위</th>
				<th></th>
				<th>제목</th>
				<th>감독</th>
				<th>배우</th>
				<th>장르</th>
				<th>등급</th>
				<th>개봉일</th>
				<th>평점</th>
			</tr>
			<tbody>
			<%
				for(MovieVO vo:list){
			%>
				<tr>
					<td><%= vo.getNo()%></td>
					<td><img src=<%=vo.getPoster() %> width=30 height=30></td>
					<td><%= vo.getTitle()%></td>
					<td><%= vo.getDirector()%></td>
					<td><%= vo.getActor()%></td>
					<td><%= vo.getGenre()%></td>
					<td><%= vo.getGrade()%></td>
					<td><%= vo.getRegdate()%></td>
					<td><%= vo.getScore()%></td>
				</tr>
			<%
				}
			%>
			</tbody>
		</table>
	</center>
</body>
</html>

 

페이지 나누기

MusicDAO.java

package com.sist.dao;
/*
 * 제어문(출력), 변수(데이터 모으기), 예외처리(오라클 연결)
 * 오라클 연결 => ArrayList => add(), get(), size()
 * => 출력 => for-each
 */

import java.sql.*; // Connection, PreparedStatement, ResultSet
import java.util.*; // ArrayList

public class MusicDAO {
	// 연결
	private Connection conn;
	// SQL 전송
	private PreparedStatement ps;
	// 오라클 주소
	private final String URL="jdbc:oracle:thin:@localhost:1521:XE";
	// 1. 실제 오라클 연결해주는 드라이버 oracle.jdbc.driver.OracleDriver
	public MusicDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			// 드라이버를 이용해서 연결 => thin드라이버
		}catch(Exception ex) {}
	}
	// 2. 연결 메소드
	public void getConnection() {
		try {
			conn=DriverManager.getConnection(URL,"hr","happy");
			//conn hr/happy
		}catch(Exception ex) {}
	}
	// 3. 닫는 메소드
	public void disConnection() {
		try {
			if(ps!=null) ps.close();
			if(conn!=null) conn.close();
			// exit
		}catch(Exception ex) {}
	}
	// DAO(JDBC => 기본 셋팅)
	// 기능 => MusicTop200
	public ArrayList<MusicVO> musicAllData(){
		ArrayList<MusicVO> list = new ArrayList<MusicVO>();
		try {
			getConnection(); // 연결
			// SQL문장 전송
			String sql = "SELECT mno, title, singer, album, poster "
					+"FROM genie_music ORDER BY mno";
			ps = conn.prepareStatement(sql);
			// 결과값 받기
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				MusicVO vo = new MusicVO();
				vo.setMno(rs.getInt(1));
				vo.setTitle(rs.getString(2));
				vo.setSinger(rs.getString(3));
				vo.setAlbum(rs.getString(4));
				vo.setPoster(rs.getString(5));
				
				list.add(vo);
			}
			rs.close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			disConnection();
		}
		return list;
	}
	
	public ArrayList<MovieVO> movieAllData(int page){
		ArrayList<MovieVO> list = new ArrayList<MovieVO>();
		try {
			getConnection(); // 연결
			int rowSize = 10;
			int start = (page*rowSize)-(rowSize-1);
			int end = page*rowSize;
			
			String sql = "SELECT no, poster, title, director, actor, genre, grade "
					+"FROM (SELECT no, poster, title, director, actor, genre, grade, rownum as num "
					+"FROM (SELECT no, poster, title, director, actor, genre, grade "
					+"FROM daum_movie ORDER BY no)) "
					+"WHERE num BETWEEN ? and ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, start);
			ps.setInt(2, end);
//			
//			sql = "SELECT no, poster, title, director, actor, genre, grade "
//					+"FROM daum_movie WHERE cateno=1 ORDER BY no";
//			ps = conn.prepareStatement(sql);

			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				MovieVO vo = new MovieVO();
				vo.setNo(rs.getInt(1));
				vo.setPoster(rs.getString(2));
				vo.setTitle(rs.getString(3));
				vo.setDirector(rs.getString(4));
				vo.setActor(rs.getString(5));
				vo.setGenre(rs.getString(6));
				vo.setGrade(rs.getString(7));
				
				list.add(vo);
			}
			rs.close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			disConnection();
		}
		return list;
	}
	public int movieTotalpage() {
		int total=0;
		try {
			getConnection();
			String sql = "SELECT CEIL(COUNT(*)/10.0) FROM daum_movie";
			ps=conn.prepareStatement(sql);
			ResultSet rs=ps.executeQuery();
			rs.next();
			total=rs.getInt(1);
			rs.close();
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}finally {
			disConnection();
		}
		return total;
	}
}

 

movie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,com.sist.dao.*,java.text.*"%>
    <%
    	String strPage=request.getParameter("page");
		if(strPage==null)
		strPage="1";
    	MusicDAO dao = new MusicDAO();
    	int curpage=Integer.parseInt(strPage);
    	int totalpage=dao.movieTotalpage();
    	ArrayList<MovieVO> list = dao.movieAllData(curpage);
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Daum Movie</title>
</head>
<body>
<center>
		<h1>현재상영영화</h1>
		<table border=1 width=1200 id="user-table">
			<tr>
				<th>순위</th>
				<th></th>
				<th>제목</th>
				<th>감독</th>
				<th>배우</th>
				<th>장르</th>
				<th>등급</th>
			</tr>
			<tbody>
			<%
				for(MovieVO vo:list){
			%>
				<tr>
					<td><%= vo.getNo()%></td>
					<td><img src=<%=vo.getPoster() %> width=30 height=30></td>
					<td><%= vo.getTitle()%></td>
					<td><%= vo.getDirector()%></td>
					<td><%= vo.getActor()%></td>
					<td><%= vo.getGenre()%></td>
					<td><%= vo.getGrade()%></td>
				</tr>
			<%
				}
			%>
			</tbody>
		</table>
		<table class="table_content" width=700>
		  <tr>
			<td align=Left></td>
			<td align="right">        <%-- 3항연산자, 참이면 왼쪽 : 거짓이면 오른쪽 --%>
				<a href="movie.jsp?page=<%= curpage>1?curpage-1:curpage%>">이전</a>
				<%=curpage %> page / <%=totalpage %> pages
				<a href="movie.jsp?page=<%= curpage<totalpage?curpage+1:curpage%>">다음</a>
			</td>
		  </tr>
		</table>
	</center>
</body>
</html>

 

request VS response 
     1) request (내장 객체 => 미리 생성된 객체) 
= HttpServletRequest request 
= 주요 기능 
1. 브라우저 정보 (사용자의 정보) 
= 사용자의 IP 
= 사용자 PORT 
2. 사용자 요청정보 (사용자 보낸 모든값을 받을 수 있는 기능) 
= 단일값 : getParameter("보낸변수명");

              list.jsp?page=1 => getParameter("page"); 
              <input type=text name=no> 
              => getParameter("no"); 
= 다중값 : checkbox, select 
              => getParameterValues() 
= 한글처리 : 한글 => 인코딩 => 디코딩 (한글이 정상적으로 들어온다) 
             setCharacterEncoding("UTF-8")

반응형
Comments