브라우저와 서버 요청, 지시어(Deirective) - page, include, taglib, 스크립트릿(Scriptlet), 표현식(Expression), 선언식(Declaration), 주석, 쿼리스트링 방식

2019. 4. 25. 18:39웹(JSP)

--------------------------------------JSP----------------------------------------

JSP ( JavaServer Page )

Url 에는 프로토콜, 경로, 쿼리문자열로 구성되어있다.
            (쿼리문자열은 url의 뒤의 ?부터 시작이다.)

HTTP는 웹브라우저와 웹서버가 데이터를 주고받을때 사용하는 규칙(Protocol)이다.
            - 요청메시지 : 웹브라우저 -> 웹서버에 요청
            - 응답메시지 : 웹서버 -> 웹브라우저 전달


정적 자원(정적 컨텐츠)와 동적 자원(동적 컨텐츠)
            - 정적 자원 : 요청할 때마다 항상 같은 데이터를 주는것 (이미지, 동영상, 회사 소개 등...)
            - 동적 자원 : 데이터가 존재 여부에 따라 다른 페이지를 보여주는것



            요청
            ----->           web Server           ----->     WAS(Web Application Server)
브라우저                (정적 자원 제공)                            (동적자원 제공)
           <-----   (HTML파일, 그림, 동영상)   <-----             (서블릿, JSP)
             응답        프로그램:Apache                       프로그램 : tomcat, jboss




문법
            - 지시어(Directive)
                        <%@  %>  :  JSP페이지의 대한 설정을 지정하는 문법
                                 <%@ 디렉티브이름 속성1="값1" 속성2="값2"....%>
                                    
                                 <%@ page ~~ %>  : 페이지 디렉티브, JSP페이지에 대한 설정 정보를 지정
                                          속성 :   contentType
                                                     import
                                                     pageEncoding
                                                     .. 많으나 위세개 위주로 쓰임
                                <%@ include ~~ %>  : 인클루드 디렉티브, JSP가 포함할 다른 JSP페이지를 지정한다.
                                <%@ taglib ~~%>  : 태그라이브러리 디렉티브, JSP에서 사용할 태그라이브러리를 지정한다.
                                   
                           예시) <% page contentType = "text/html; charset=utf-8" %>

            
            - 스크립트릿(Scriptlet)
                        <% %>  : 자바코딩 영역을 만드는것, 동적컨텐츠 생성에 필요한 자바코드 구현
                                    1. 요청한 객체에서 클라이언트가 보낸 정보 획득하기
                                    2. 업무로직 호출 -> 데이터를 획득
                                    3. 획득된 데이터로 동적컨텐츠 생성

            - 표현식(Expression)
                        <%= %>  : 응답(출력) 결과에 값이 포함되게 한다.


            - 선언식(Declaration)
                        <%! %>  : 필드/메소드를 정의할때 사용한다.
                        ※. 일반적으로 a.jsp라는 파일을 만들면 a_jsp.java파일이 만들어지는데 거기의 
                            _jspService(req, res) 메소드에 만들어지는데 선언식(Declaration)을 이용하면
                            _jspService(req, res)가 아닌 (예로 a_jsp라는) 새로운 메소드 및 필드로 만들어 진다.


            - 주석(Comment)
                        <%-- --%>  : 주석이 된다.





예시) 스크립트릿 예시





예시) 선언식(Declaration) 예시

 




예시) 활용





HTTP 응답코드
            - 400 번대 : 클라이언트 오류
                        404 : 없는 자원을 요청할 때
            - 500 번대 : 서버에러



쿼리 스트림 방식
            - url을 만들어 동적 페이지를 만들때 아래와 같이한다.


            search.jsp는 페이지, ? 뒤에 지정한 값, 요청파라미터 이름 did, 요청파라미터 값, dept.getId() 을 적는다.
            값 줄때 :  a href="이동할경로?지정할url=전해줄값"

            - 값을 받을때는 아래와 같이 받아오려면
            값 받을때 : 받을타입 변수명 = request.getParameter("지정했던url")


                                                                   위에처럼 치면


위와같이 Console에 보인다.

위처럼 가능한 이유는 request가 빌트인 객체이기때문에 불러서 쓰기때문이다.





예제 활용)-----------------------------------------

 

 

home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인사관리</title>
</head>
<body>
	<h1>인사관리 시스템 홈 페이지</h1>
	
	<h3>메뉴</h3>
	<ul>
		<li><a href="depts.jsp">부서조회</a></li>
		<li><a href="employees.jsp">사원조회</a></li>
		<li><a href="jobs.jsp">직종조회</a></li>
	</ul>
</body>
</html>

 

 

EmployeeDao.java

package kr.co.hta.hr.dao;

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

import kr.co.hta.hr.vo.Employee;
import kr.co.hta.util.ConnectionUtils;

public class EmployeeDao {

	public ArrayList<Employee> selectAllEmployees() throws Exception{
		ArrayList<Employee> employee = new ArrayList<Employee>();
		String sql = "select * from employees order by 1";
		Connection conn = ConnectionUtils.hrConnection();
		PreparedStatement ptmt = conn.prepareStatement(sql);
		ResultSet rs = ptmt.executeQuery();
		
		while(rs.next()) {
			Employee emp = new Employee();
			emp.setId(rs.getInt("employee_id"));
			emp.setFirstName(rs.getString("first_name"));
			emp.setLastName(rs.getString("last_name"));
			emp.setJobId(rs.getString("job_id"));
			emp.setDepartmentId(rs.getInt("department_id"));
			emp.setEmail(rs.getString("email"));
			emp.setPhoneNumber(rs.getString("phone_number"));
			emp.setSalary(rs.getDouble("salary"));
			emp.setCommissionPct(rs.getDouble("commission_pct"));
			emp.setManagerId(rs.getInt("manager_id"));
			emp.setHireDate(rs.getDate("hire_date"));
			
			employee.add(emp);
		}
		
		return employee;
	}
	
	public ArrayList<Employee> selectEmployeesByDeptId(int departmentId) throws Exception{
		ArrayList<Employee> employee = new ArrayList<Employee>();
		String sql ="select * from employees where department_id = ? order by 1 ";
		Connection conn = ConnectionUtils.hrConnection();
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setInt(1, departmentId);
		
		ResultSet rs = ptmt.executeQuery();
		
		while(rs.next()) {
			Employee emp = new Employee();
			emp.setId(rs.getInt("employee_id"));
			emp.setFirstName(rs.getString("first_name"));
			emp.setLastName(rs.getString("last_name"));
			emp.setJobId(rs.getString("job_id"));
			emp.setDepartmentId(rs.getInt("department_id"));
			emp.setEmail(rs.getString("email"));
			emp.setPhoneNumber(rs.getString("phone_number"));
			emp.setSalary(rs.getDouble("salary"));
			emp.setCommissionPct(rs.getDouble("commission_pct"));
			emp.setManagerId(rs.getInt("manager_id"));
			emp.setHireDate(rs.getDate("hire_date"));
			
			employee.add(emp);
		}
		
		return employee;
	}
	
	public ArrayList<Employee> selectEmployeesByJobId(String jobId) throws Exception{
		ArrayList<Employee> employee = new ArrayList<Employee>();
		String sql ="select * from employees where job_id = ? order by 1 ";
		Connection conn = ConnectionUtils.hrConnection();
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setString(1, jobId);
		
		ResultSet rs = ptmt.executeQuery();
		
		while(rs.next()) {
			Employee emp = new Employee();
			emp.setId(rs.getInt("employee_id"));
			emp.setFirstName(rs.getString("first_name"));
			emp.setLastName(rs.getString("last_name"));
			emp.setJobId(rs.getString("job_id"));
			emp.setDepartmentId(rs.getInt("department_id"));
			emp.setEmail(rs.getString("email"));
			emp.setPhoneNumber(rs.getString("phone_number"));
			emp.setSalary(rs.getDouble("salary"));
			emp.setCommissionPct(rs.getDouble("commission_pct"));
			emp.setManagerId(rs.getInt("manager_id"));
			emp.setHireDate(rs.getDate("hire_date"));
			
			employee.add(emp);
		}
		
		return employee;
	}
}

 

 

 

DepartmentDao.java

 

package kr.co.hta.hr.dao;

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

import kr.co.hta.hr.vo.Department;
import kr.co.hta.util.ConnectionUtils;

public class DepartmentDao {

	// 모든 부서정보를 조회 기능
	public ArrayList<Department> selectAllDepartments () throws Exception{
		ArrayList<Department> department = new ArrayList<Department>();
		
		String sql = "select * from departments";
		Connection conn = ConnectionUtils.hrConnection();
		PreparedStatement ptmt = conn.prepareStatement(sql);
		ResultSet rs = ptmt.executeQuery();
		
		while(rs.next()) {
			Department dep = new Department();
			
			dep.setId(rs.getInt("department_id"));
			dep.setName(rs.getString("department_name"));
			dep.setManagerId(rs.getInt("manager_id"));
			dep.setLocationId(rs.getInt("location_id"));
			
			department.add(dep);
		}
		rs.close();
		ptmt.close();
		conn.close();
		
		return department;
	}
}

 

 

 

JobDao.java

 

package kr.co.hta.hr.dao;

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

import kr.co.hta.hr.vo.Job;
import kr.co.hta.util.ConnectionUtils;

public class JobDao {

	public ArrayList<Job> selectAllJobs()throws Exception {
		ArrayList<Job> jobs = new ArrayList<Job>();
		String sql = "select * from jobs order by 1 ";
		Connection conn = ConnectionUtils.hrConnection();
		PreparedStatement ptmt = conn.prepareStatement(sql);
		ResultSet rs = ptmt.executeQuery();
		
		while(rs.next()) {
			Job job = new Job();
			job.setId(rs.getString("job_id"));
			job.setTitle(rs.getString("job_title"));
			job.setMinSalary(rs.getDouble("min_salary"));
			job.setMaxSalary(rs.getDouble("max_salary"));
			
			jobs.add(job);
		}
		rs.close();
		ptmt.close();
		conn.close();
		
		return jobs;
	}
	
	
}

 

 

 

depts.jsp

 

<%@page import="kr.co.hta.hr.vo.Department"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.hta.hr.dao.DepartmentDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인사관리</title>
</head>
<body>
	<h1>전체 부서 목록</h1>
	<a href="home.jsp">홈으로</a>
	<%
		DepartmentDao deptDao = new DepartmentDao();
		ArrayList<Department> departments = deptDao.selectAllDepartments();
	%>
	<table border="1" style="width: 100%">
		<thead>
			<tr>
				<th>아이디</th>
				<th>부서명</th>
				<th>담당자 아이디</th>
				<th>소재지 아이디</th>
			</tr>
		</thead>
		<tbody>
			<%
				for (Department dept : departments) {
			%>
			<tr>
				<td><%=dept.getId()%></td>
				<td><a href="search.jsp?did=<%=dept.getId()%>"><%=dept.getName()%></a></td>
				<td><%=dept.getManagerId()%></td>
				<td><%=dept.getLocationId()%></td>
			</tr>
			<%
				}
			%>
		</tbody>
	</table>
</body>
</html>

 

 

 

search.jsp

 

<%@page import="kr.co.hta.hr.vo.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.hta.hr.dao.EmployeeDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인사관리</title>
</head>
<body>
	<h1>부서별 사원목록</h1>
	<%
		// 요청 파라미터값 조회
		int departmentId = Integer.parseInt(request.getParameter("did"));

		EmployeeDao employeeDao = new EmployeeDao();
		ArrayList<Employee> emp = employeeDao.selectEmployeesByDeptId(departmentId);
	%>
	<table border="1" style="width: 100%">
		<thead>
			<tr>
				<th>사원번호</th>
				<th>이름</th>
				<th>이메일</th>
				<th>연락처</th>
				<th>직종</th>
				<th>입사일</th>
			</tr>
		</thead>
		<tbody>
			<%
				for (Employee employees : emp) {
			%>
			<tr>
				<td><%=employees.getId()%></td>
				<td><%=employees.getFirstName()%> <%=employees.getLastName()%></td>
				<td><%=employees.getEmail()%></td>
				<td><%=employees.getPhoneNumber()%></td>
				<td><%=employees.getJobId()%></td>
				<td><%=employees.getHireDate()%></td>
			</tr>
			<%
				}
			%>
		</tbody>
	</table>

</body>
</html>

 

 

 

jobs.jsp

 

<%@page import="kr.co.hta.hr.vo.Job"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.hta.hr.dao.JobDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직종 검색</title>
</head>
<body>
	<h1>직종 출력</h1>
	<%
		JobDao jobDao = new JobDao();
		ArrayList<Job> job = jobDao.selectAllJobs();
	%>
	<table border="1" style="width: 100%">
		<thead>
			<tr>
				<th>직종 아이디</th>
				<th>직종 이름</th>
				<th>최저 급여</th>
				<th>최고 급여</th>
			</tr>
		</thead>
		<tbody>
			<%
				for (Job jobs : job) {
			%>
			<tr>
				<td><%=jobs.getId() %></td>
				<td><a href="searchJobs.jsp?jid=<%=jobs.getId() %>"><%=jobs.getTitle() %></a></td>
				<td><%=jobs.getMinSalary() %></td>
				<td><%=jobs.getMaxSalary() %></td>
			<tr>
				<%
					}
				%>
			
		</tbody>
	</table>
</body>
</html>

 

 

 

searchJobs.jsp

 

<%@page import="kr.co.hta.hr.vo.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.hta.hr.dao.EmployeeDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직종별 조회</title>
</head>
<body>
	<h1>직종별 사원 조회</h1>
	<%
		String jid = request.getParameter("jid");
		EmployeeDao empDao = new EmployeeDao();
		ArrayList<Employee> employee = empDao.selectEmployeesByJobId(jid);
	%>
	<table border="1" style="width: 100%">
		<thead>
			<tr>
				<th>아이디</th>
				<th>이름</th>
				<th>직종아이디</th>
				<th>부서아이디</th>
				<th>이메일</th>
				<th>연락처</th>
				<th>급여</th>
				<th>커미션</th>
				<th>상사아이디</th>
				<th>입사일</th>
			</tr>
		</thead>
		<tbody>
			<%
				for (Employee emp : employee) {
			%>
			<tr>
				<td><%=emp.getId() %></td>
				<td><%=emp.getFirstName() %>  <%=emp.getLastName() %></td>
				<td><%=emp.getJobId() %></td>
				<td><%=emp.getDepartmentId() %></td>
				<td><%=emp.getEmail() %></td>
				<td><%=emp.getPhoneNumber() %></td>
				<td><%=emp.getSalary() %></td>
				<td><%=emp.getCommissionPct() %></td>
				<td><%=emp.getManagerId() %></td>
				<td><%=emp.getHireDate() %></td>
			</tr>
			<%
				}
			%>
		</tbody>
	</table>
</body>
</html>

 

 

 

 

employees.jsp

 

<%@page import="kr.co.hta.hr.vo.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.hta.hr.dao.EmployeeDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인사관리</title>
</head>
<body>
	<h1>전체 직원 목록</h1>
	<a href="home.jsp">홈으로</a>
	<%
		EmployeeDao employeeDao = new EmployeeDao();
		ArrayList<Employee> employees = employeeDao.selectAllEmployees();
	%>
	<table id="head" border="1" style="width: 100%">
		<thead>
			<tr>
				<th>아이디</th>
				<th>이름</th>
				<th>직종아이디</th>
				<th>부서아이디</th>
				<th>이메일</th>
				<th>연락처</th>
				<th>급여</th>
				<th>커미션</th>
				<th>상사아이디</th>
				<th>입사일</th>
			</tr>
		</thead>
		<tbody>
			<%
				for (Employee emp : employees) {
			%>
			<tr>
				<td><%=emp.getId() %></td>
				<td><%=emp.getFirstName() %> <%=emp.getLastName() %></td>
				<td><%=emp.getJobId() %></td>
				<td><%=emp.getDepartmentId() %></td>
				<td><%=emp.getEmail() %></td>
				<td><%=emp.getPhoneNumber() %></td>
				<td><%=emp.getSalary() %></td>
				<td><%=emp.getCommissionPct() %></td>
				<td><%=emp.getManagerId() %></td>
				<td><%=emp.getHireDate() %></td>
			</tr>
			<%
				}
			%>
		</tbody>
		
		</table>
			<a href="#head">위로</a>
</body>
</html>