본문 바로가기
푸닥거리

웹 개발을 위한 JSP_Sevlet 기본

by [김경민]™ ┌(  ̄∇ ̄)┘™ 2021. 10. 9.
728x90

2021-10-09

 

 

Servlet <- Java HTML

JSP <- html Java

 

 

WebServer <-> Servlet Container

.html          <-> index.java -> web.xml

                <-> .jsp => webapp폴더 / jsp Container

 

 

C:\java\Chap08_JSP\src\main\webapp\part01

C:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Chap08_JSP\org\apache\jsp\part01



<%
// application => ServletContext 객체
String name = application.getRealPath("index.jsp");
out.println(name);
%>

<!-- 지정한 파일이 컴파일이 되어 이 페이지에 추가 -->
<jsp:include page="header.jsp"></jsp:include>

<!-- 지정한 파일 자체가 이 페이지에 포함되고 함께 컴파일 -->
<%@ include file="nav.jsp" %>

 

 

 

<%!

public int cnt = 1;

 

public String onAdd(int x, int y){

return x + " + " + y + " = " + (x + y);

}

%>

 

 

 


<%

// Post로 넘어오면 넘기는 페이지의 인코딩 값으로 넘어오는 값의 반환해서 받을 필요가 있다.
request.setCharacterEncoding("UTF-8");

 

String name = request.getParameter("name");
String id = request.getParameter("id");
String password = request.getParameter("password");
String address = request.getParameter("address");

//String qty = request.getParameter("qty");
//int qtyInt = Integer.parseInt(qty);
//Integer qtyInt = Integer.parseInt(qty);
//int i = new Integer(100);
//Integer j = 10;
//double qtyInt = Double.parseDouble(qty);

int qty = Integer.parseInt(request.getParameter("qty"));
%>

 


  <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
// Post로 넘어오면 넘기는 페이지의 인코딩 값으로 넘어오는 값의 반환해서 받을 필요가 있다.
request.setCharacterEncoding("UTF-8");

String id = request.getParameter("id");
String password = request.getParameter("password");

// DB조회를 해서 그 결과를 받아온다.
//select * from users where id = id and password = password;
if(id.equals("abc") && password.equals("abc123")){
//성공
}else{
//실패
response.sendRedirect("../html/login.html");
}
    %>

 

프로젝트 전체에서 공유

1. ServletContext => application  

2. HttpSession => session ( 브라우저 ) 

3. HttpServletRequest => request, forward로 지정한 페이지만

4. ServletConfig => page

 

모든 값은 Object Type

객체.setAttribute("변수명", values)

객체.getAttribute("변수명")

객체.removeAttribute("변수명")

 

setAttribute, getAttribute

-> sendRedirect => 페이지 데이터 공유가 안됨

-> forward(req, res) => 페이지 데이터 공유가 됨

 

 


     //response.sendRedirect("./A07Result.jsp");
    
     // 현재 사용하고 있는 페이지의 req, res를 전달한 페이지를 지정한다.
     RequestDispatcher view = request.getRequestDispatcher("./A07Result.jsp");
     // 지정한 페이지에 지금 사용하고 있는 request, response 객체를 전달한다.
     // request에는 위에서 계산한 변수 값 등이 포함되어 있다.
     view.forward(request, response);

 

 

 

 

 

2021-10-10

 

브라우저

session

 

Servlet

jsp , forward

 

PageContext

스코프: 현재 페이지 안에서만

 

// 소스가 포함 됨, 동적 페이지에 사용 용이

<%@include file="A08IncludeFile.jsp" %> 

 

// 컴파일 된 결과가 포함 됨 ( text 파일 ), 정적 html 파일인 경우 사용 용이

<jsp:include page="A08IncludeFile.jsp"></jsp:include> 

 

 

 

 

지역변수 vs 멤버변수 선언문

 

 

jsp errorpage

 

 

서블릿 에러처리 필터

 

 

 

 

 

 

 

오라클 연결

 

 

 

 

conn system/manager
alter user hr account unlock;
alter user hr identified by hr;
conn hr/hr
select * from employees;

 

 

 

서버

 

 

프로젝트생성

 

 

create table emp
as
select 
 employee_id emp_id,
 first_name name,
 salary,
 commission_pct pct,
 hire_date hire,
 manager_id manager,
 department_id dept_id
from employees;

 

 

자바의 다형성

 

interface Animal { public abstract void cry(); }
 
class Cat implements Animal { 
    public void cry() { 
        System.out.println("냐옹냐옹!"); 
    } 
}
 
class Dog implements Animal { 
    public void cry() { 
        System.out.println("멍멍!"); 
    } 
}
 
public class Polymorphism03 { 
    public static void main(String[] args) { 
        Cat c = new Cat(); 
        Dog d = new Dog(); 
        c.cry(); 
        d.cry(); 
    } 
}

 

실행 결과


냐옹냐옹!
멍멍!

 

 

// 1. Class Load. DB마다 고유의 이름을 가지고 있음
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("로드 완료");

// 2. 연결을 맺고 연결 객체를 받아온다.
String url = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = DriverManager.getConnection(url, "hr", "hr");
System.out.println("연결 완료");

// 3. 연결 객체를 대상으로 실행할 Query문을 준비한다. query뒤에 ;를 붙이면 에러 발생
// Query에 관련된 명령들을 모아 놓은 객체는 createStatement, prepareStatement
// 사용되나 요즘은 prepareStatement만 사용
String sql = "select * from emp";
PreparedStatement stmt = conn.prepareStatement(sql);

 

 

ResultSet

-------- <- cursor , next() - 다음 row 로 다음 row 가 없으면 false 리턴 

| | | | | |

--------

| | | | | |

--------

 

package com.company.jdbc;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.sql.Connection;

public class Employee {

public static void main(String[] args) throws SQLException {

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;

try {

// 1. Class Load. DB마다 고유의 이름을 가지고 있음
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("로드 완료");

// 2. 연결을 맺고 연결 객체를 받아온다.
String url = "jdbc:oracle:thin:@localhost:1521:xe";
conn = DriverManager.getConnection(url, "hr", "hr");
System.out.println("연결 완료");

// 3. 연결 객체를 대상으로 실행할 Query문을 준비한다. query뒤에 ;를 붙이면 에러 발생
// Query에 관련된 명령들을 모아 놓은 객체는 createStatement, prepareStatement
// 사용되나 요즘은 prepareStatement만 사용
String sql = "select * from emp";
//String sql = "select * from emp where emp_id = ? and name = ?";
stmt = conn.prepareStatement(sql);

// 4. Query구문의 변수 값 등을 셋팅 - 여기서는 없음
//stmt.setInt(1, 100);
//stmt.setString(2, "nolBu");

// 5. Query 실행 - 쿼리 준비하고 엔터
// select => executeQuery. 리턴타입이 ResultSet
// insert, update, delete => executeUpdate. 리턴타입이 int(실행 갯수)
rs = stmt.executeQuery();

// 6. 그 결과에 대한 처리 
while(rs.next()) {
int emp_id = rs.getInt("emp_id");
String name = rs.getString("name");
double pct = rs.getDouble("pct");
Date hire = rs.getDate("hire");
int salary = rs.getInt("salary");
int manager = rs.getInt("manager");
int dept_id = rs.getInt("dept_id");

System.out.println(emp_id + "\t" + name + "\t" + pct + "\t" + hire + "\t" + salary + "\t" + manager + "\t" + dept_id); 
}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

// 7. 사용했던 자원을 닫아야 한다. ResultSet, PreparedStatement, Connection
// 닫는것은 나중에 사용한 자원부터 닫는다.
// null check
if(rs != null) {
try {
rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
}

if(stmt != null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}

if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}

}

}
}

 

 

 

 

 

 

 

java를 jsp로

 

Ctrl+space

 

 

 

 

 

728x90

댓글