package dto;
/*
CREATE TABLE school(
NAME VARCHAR2(15) NOT NULL, -- 이름
VALUE VARCHAR2(15), -- 학생 : 학번, 교수 : 과목명, 관리자 : 부서명
CODE NUMBER -- 관리 코드 : 1.학생 2. 교수 3. 관리자
);
*/
public class SchoolDTO {
private String name;
private String value;
private int code;
public SchoolDTO() {}
public SchoolDTO(String name, String value, int code) {
this.name = name;
this.value = value;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.SchoolDTO;
public class SchoolDAO {
private String url = "jdbc:oracle:thin:@localhost:1521:xe";
private String id = "dbtest";
private String pwd = "a1234";
public SchoolDAO() {
try {
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("로딩 성공");
} catch (Exception e) {
System.out.println("로딩 실패 ㅠㅠ");
e.printStackTrace();
}
}// SchoolDAO() end
public Connection getConnection() {
Connection con = null;
try {
// DB 연결 객체 생성
con = DriverManager.getConnection(url,id,pwd);
System.out.println("연결 성공!!");
} catch (Exception e) {
System.out.println("연결 실패~");
e.printStackTrace();
}
return con;
}// getConnection() end
// 추가
public boolean insert(SchoolDTO dto) {
Connection con = null;
PreparedStatement pstmt = null;
boolean check = false;
try {
String sql = "INSERT INTO school VALUES(?,?,?)";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1,dto.getName());
pstmt.setString(2,dto.getValue());
pstmt.setInt(3,dto.getCode());
int su = pstmt.executeUpdate(); // 추가 성공한 레코드 수 반환
if(su > 0) check = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(dto.getName()+"정보 추가");
return check;
}// insert() end
// 목록
public ArrayList<SchoolDTO> getList() {
ArrayList<SchoolDTO> list = new ArrayList<>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL";
con = this.getConnection();
pstmt = con.prepareStatement(sql);
res = pstmt.executeQuery();
while(res.next()) {
String name = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
list.add(new SchoolDTO(name, value, code));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(con != null) {
con.close();
}
if(res != null) {
res.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if(list.isEmpty()){
list = null;
}
return list;
}// getList() end
// 검색
public void search(String sname) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL WHERE NAME = ?";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, sname);
res = pstmt.executeQuery();
if(res == null) {
System.out.println(sname + "임마 없음");
} else {
while(res.next()) {
String name = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
System.out.println(name +" - "+ value +" - "+ code);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(res != null) res.close();
if(pstmt != null) pstmt.close();
if(con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// search() end
// 삭제
public String delete(String dname) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet resS =null;
int res = 0;
String resT="";
try {
String sqlsel = "SELECT * FROM MEMBER";
con = getConnection();
pstmt = con.prepareStatement(sqlsel);
resS = pstmt.executeQuery();
if(resS == null) {
System.out.println("조회된 데이터가 없습니다.");
} else {
String sql = "DELETE FROM SCHOOL WHERE NAME = ?";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, dname);
res = pstmt.executeUpdate();
resT = dname;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(res + "개 행 삭제");
return resT;
}
}
import java.util.List;
import java.util.Scanner;
import dao.SchoolDAO;
import dto.SchoolDTO;
public class SchoolController {
private Scanner sc = new Scanner(System.in);
private SchoolDAO dao = null;
public SchoolController() {
dao = new SchoolDAO();
menu();
}
public void menu() {
while(true) {
System.out.println("----- 메 뉴 -----");
System.out.print("1. 입력 2. 검색 3. 삭제 4. 목록 5. 종료 \n 선택 >>");
int select = sc.nextInt();
switch(select) {
case 1: // 입력
insert();
break;
case 2: // 검색
search();
break;
case 3: // 삭제
delete();
break;
case 4: // 목록
list();
break;
case 5: // 종료
System.exit(0);
break;
default:
System.out.println("선택 오류~");
}
System.out.println();
}
}// menu() end
// 코드 설정
public int codeInput() {
System.out.println("--- 코 드 선텍 ---");
System.out.println("1. 학생");
System.out.println("2. 교수");
System.out.println("3. 관리자");
System.out.println("4. 이전");
System.out.print("선택 > ");
int code = sc.nextInt();
return code;
}// codeInput() end
public String valueInput(int code) {
if(code == 1) {
System.out.print("학번 입력 > ");
} else if(code == 2) {
System.out.print("과목 입력 > ");
} else {
System.out.print("부서 입력 > ");
}
String value = sc.next();
return value;
}
// valueInput() end
// 추가
public void insert() {
System.out.println("----- 추 가 -----");
int code = codeInput();
if(code < 1 || code > 3) {
System.out.println("이전 메뉴로 이동합니다~");
return;
}
System.out.print("이름 입력 >> ");
String name = sc.next();
String value = valueInput(code);
SchoolDTO dto = new SchoolDTO(name, value, code);
boolean check = dao.insert(dto);
if(check) {
System.out.println(name + "님이 등록 되었습니다");
} else {
System.out.println("등록 실패~");
}
}// insert() end
public void list() {
List<SchoolDTO> list = dao.getList();
System.out.println("----- 목 록 -----");
for(SchoolDTO man : list) {
System.out.println(man.getName() +"\t");
if(man.getCode()==1) {
System.out.println("학번 : " + man.getValue());
}else if(man.getCode()==2) {
System.out.println("과목 : " + man.getValue());
}else{
System.out.println("부서 : " + man.getValue());
}
System.out.println("--------------------");
}
} // list() end
// 검색
public void search() {
System.out.println("----- 검 색 -----");
System.out.println("이름 입력 >> ");
String sname = sc.next();
dao.search(sname);
}
// 삭제
public void delete() {
System.out.println("----- 삭 제 -----");
System.out.println("이름 입력 >>> ");
String dname = sc.next();
System.out.println(dao.delete(dname) + "삭제");
}
}
public void search2() {
System.out.println("----- 검 색 -----");
System.out.println("1.이름 2.코드 3.전체 4.이전");
System.out.print("선택 > ");
int num = sc.nextInt();
if (num < 1 || num > 3) {
System.out.println("이전 메뉴로 이동합니다...");
return;
}
SchoolDTO dto = null;
if (num == 1) {
dto = new SchoolDTO();
System.out.print("검색 이름 입력 > ");
dto.setName(sc.next());
} else if (num == 2) {
int code = codeInput();
if (code < 1 || code > 3) {
System.out.println("없는 코드 입니다 ~");
return;
}
dto = new SchoolDTO();
dto.setCode(code);
}
dao.searchT(dto);
}ZX
public void search2(SchoolDTO dto) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL WHERE ";
con = getConnection();
if(dto.getName()!=null) {
pstmt = con.prepareStatement(sql + "NAME =?");
pstmt.setString(1, dto.getName());
} else if(dto.getCode()!=0) {
pstmt = con.prepareStatement(sql + "CODE =?");
pstmt.setInt(1, dto.getCode());
}
res = pstmt.executeQuery();
if(res==null) {
System.out.println("없음");
} else {
while(res.next()) {
String namea = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
System.out.println(namea + " - " + value + " - " + code);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(con!=null)con.close();
if(pstmt!=null)pstmt.close();
if(res!=null)res.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.SchoolDTO;
public class SchoolDAO {
private String url = "jdbc:oracle:thin:@localhost:1521:xe";
private String id = "dbtest";
private String pwd = "a1234";
public SchoolDAO() {
try {
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("로딩 성공");
} catch (Exception e) {
System.out.println("로딩 실패 ㅠㅠ");
e.printStackTrace();
}
}// SchoolDAO() end
public Connection getConnection() {
Connection con = null;
try {
// DB 연결 객체 생성
con = DriverManager.getConnection(url,id,pwd);
System.out.println("연결 성공!!");
} catch (Exception e) {
System.out.println("연결 실패~");
e.printStackTrace();
}
return con;
}// getConnection() end
// 추가
public boolean insert(SchoolDTO dto) {
Connection con = null;
PreparedStatement pstmt = null;
boolean check = false;
try {
String sql = "INSERT INTO school VALUES(?,?,?)";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1,dto.getName());
pstmt.setString(2,dto.getValue());
pstmt.setInt(3,dto.getCode());
int su = pstmt.executeUpdate(); // 추가 성공한 레코드 수 반환
if(su > 0) check = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(dto.getName()+"정보 추가");
return check;
}// insert() end
// 목록
public ArrayList<SchoolDTO> getList() {
ArrayList<SchoolDTO> list = new ArrayList<>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL";
con = this.getConnection();
pstmt = con.prepareStatement(sql);
res = pstmt.executeQuery();
while(res.next()) {
String name = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
list.add(new SchoolDTO(name, value, code));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(con != null) {
con.close();
}
if(res != null) {
res.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if(list.isEmpty()){
list = null;
}
return list;
}// getList() end
// 검색
public void search(String sname) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL WHERE NAME = ?";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, sname);
res = pstmt.executeQuery();
if(res == null) {
System.out.println(sname + "임마 없음");
} else {
while(res.next()) {
String name = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
System.out.println(name +" - "+ value +" - "+ code);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(res != null) res.close();
if(pstmt != null) pstmt.close();
if(con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// search() end
// 검색2
public void search2(SchoolDTO dto) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "SELECT * FROM SCHOOL WHERE ";
con = getConnection();
if(dto.getName()!=null) {
pstmt = con.prepareStatement(sql + "NAME =?");
pstmt.setString(1, dto.getName());
} else if(dto.getCode()!=0) {
pstmt = con.prepareStatement(sql + "CODE =?");
pstmt.setInt(1, dto.getCode());
}
res = pstmt.executeQuery();
if(res==null) {
System.out.println("없음");
} else {
while(res.next()) {
String namea = res.getString("name");
String value = res.getString("value");
int code = res.getInt("code");
System.out.println(namea + " - " + value + " - " + code);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(con!=null)con.close();
if(pstmt!=null)pstmt.close();
if(res!=null)res.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 검색T
public void searchT(SchoolDTO dto) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = null;
if(dto == null) {
sql = "select * from school";
} else if(dto.getName()!=null) {
sql = "select * from school where name like ?";
} else {
sql = "select * from school where code=?";
}
con = this.getConnection();
pstmt = con.prepareStatement(sql);
if(dto !=null) {
if(dto.getName()!=null) {
pstmt.setString(1, "%" + dto.getName() + "%");
}else {
pstmt.setInt(1, dto.getCode());
}
}
res = pstmt.executeQuery();
while(res.next()) {
String name = res.getString("name");
String value = res.getString("value");
int code= res.getInt("code");
System.out.print(name + "\t");
if(code == 1) {
System.out.println("학번 : " + value);
} else if(code ==2 ) {
System.out.println("과목 : " + value);
} else{
System.out.println("부서 : " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(con!= null)con.close();
if(res!= null)res.close();
if(pstmt!= null)pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 삭제
public String delete(String dname) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet resS =null;
int res = 0;
String resT="";
try {
String sqlsel = "SELECT * FROM MEMBER";
con = getConnection();
pstmt = con.prepareStatement(sqlsel);
resS = pstmt.executeQuery();
if(resS == null) {
System.out.println("조회된 데이터가 없습니다.");
} else {
String sql = "DELETE FROM SCHOOL WHERE NAME = ?";
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, dname);
res = pstmt.executeUpdate();
resT = dname;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(res + "개 행 삭제");
return resT;
}
}
import java.util.List;
import java.util.Scanner;
import dao.SchoolDAO;
import dto.SchoolDTO;
public class SchoolController {
private Scanner sc = new Scanner(System.in);
private SchoolDAO dao = null;
public SchoolController() {
dao = new SchoolDAO();
menu();
}
public void menu() {
while (true) {
System.out.println("----- 메 뉴 -----");
System.out.print("1. 입력 2. 검색 3. 삭제 4. 목록 5. 종료 \n 선택 >>");
int select = sc.nextInt();
switch (select) {
case 1: // 입력
insert();
break;
case 2: // 검색
search2();
break;
case 3: // 삭제
delete();
break;
case 4: // 목록
list();
break;
case 5: // 종료
System.exit(0);
break;
default:
System.out.println("선택 오류~");
}
System.out.println();
}
}// menu() end
// 코드 설정
public int codeInput() {
System.out.println("--- 코 드 선텍 ---");
System.out.println("1. 학생");
System.out.println("2. 교수");
System.out.println("3. 관리자");
System.out.println("4. 이전");
System.out.print("선택 > ");
int code = sc.nextInt();
return code;
}// codeInput() end
public String valueInput(int code) {
if (code == 1) {
System.out.print("학번 입력 > ");
} else if (code == 2) {
System.out.print("과목 입력 > ");
} else {
System.out.print("부서 입력 > ");
}
String value = sc.next();
return value;
}
// valueInput() end
// 추가
public void insert() {
System.out.println("----- 추 가 -----");
int code = codeInput();
if (code < 1 || code > 3) {
System.out.println("이전 메뉴로 이동합니다~");
return;
}
System.out.print("이름 입력 >> ");
String name = sc.next();
String value = valueInput(code);
SchoolDTO dto = new SchoolDTO(name, value, code);
boolean check = dao.insert(dto);
if (check) {
System.out.println(name + "님이 등록 되었습니다");
} else {
System.out.println("등록 실패~");
}
}// insert() end
public void list() {
List<SchoolDTO> list = dao.getList();
System.out.println("----- 목 록 -----");
for (SchoolDTO man : list) {
System.out.println(man.getName() + "\t");
if (man.getCode() == 1) {
System.out.println("학번 : " + man.getValue());
} else if (man.getCode() == 2) {
System.out.println("과목 : " + man.getValue());
} else {
System.out.println("부서 : " + man.getValue());
}
System.out.println("--------------------");
}
} // list() end
// 검색
public void search() {
System.out.println("----- 검 색 -----");
System.out.println("이름 입력 >> ");
String sname = sc.next();
dao.search(sname);
}
// 검색2
public void search2() {
System.out.println("----- 검 색 -----");
System.out.println("1.이름 2.코드 3.전체 4.이전");
System.out.print("선택 > ");
int num = sc.nextInt();
if (num < 1 || num > 3) {
System.out.println("이전 메뉴로 이동합니다...");
return;
}
SchoolDTO dto = null;
if (num == 1) {
dto = new SchoolDTO();
System.out.print("검색 이름 입력 > ");
dto.setName(sc.next());
} else if (num == 2) {
int code = codeInput();
if (code < 1 || code > 3) {
System.out.println("없는 코드 입니다 ~");
return;
}
dto = new SchoolDTO();
dto.setCode(code);
}
dao.searchT(dto);
}
// 삭제
public void delete() {
System.out.println("----- 삭 제 -----");
System.out.println("이름 입력 >>> ");
String dname = sc.next();
System.out.println(dao.delete(dname) + "삭제");
}
}
txt
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>03_Servlet</display-name>
<servlet>
<servlet-name>ex01</servlet-name>
<servlet-class>ex01.LifeCycle</servlet-class>
</servlet>
<servlet>
<servlet-name>ex02</servlet-name>
<servlet-class>ex02.HelloServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>param</servlet-name>
<servlet-class>ex03.ParamServlet</servlet-class>
</servlet>
<!-- <servlet>
<servlet-name>member</servlet-name>
<servlet-class>ex04.MemberServlet</servlet-class>
</servlet> -->
<servlet-mapping>
<servlet-name>ex01</servlet-name>
<url-pattern>/life</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ex02</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>param</servlet-name>
<url-pattern>/paramServlet</url-pattern>
</servlet-mapping>
<!-- <servlet-mapping>
<servlet-name>member</servlet-name>
<url-pattern>/memberServlet</url-pattern>
</servlet-mapping> -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
package ex01;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// import - class 사이 내용삭제
/*
* # HttpServlet class
* - GenericServlet 을 상속 받아 HTTP 프로토콜을 사용하는 웹 브라우저에서 서블릿 기능 수행
*
* # 서블릿 life cycle
* - 초기화 : init()
* > 서블릿 요청시 맨 처음 한 번만 호출 됨
*
* - 작업 수행 : doGet(), doPost()
* > 서블릿 요청시 매번 호출
* 실제로 클라이언트가 요청하는 작업을 수행
*
* - 종료 : destroy()
* > 서블릿이 기능을 수행하고 메모리에서 소멸될 때 수행
*
* # 서블릿 생성 과정
* - 1. 사용자 정의 서블릿 클래스 구현
* - 2. 서블릿 메서드 구현
* - 3. 서블릿 맵핑 작업
* - 4. 웹 브라우저에서 서블릿 맵핑 이름으로 요청
*
* # 서블릿 맵핑
* - web.xml 파일에서 설정
*/
public class LifeCycle extends HttpServlet {
// class - doGet 사이 삭제
// 최초 요청시 한 번만 실행
public void init(ServletConfig config) throws ServletException{
System.out.println("- init() run -");
}
// client 로부터 request 가 올 때마다 실행
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// doGet() 생성되어 있던 내용 삭제
System.out.println("- doGet() run -");
}
// doPost 삭제
//종료
public void destroy() {
System.out.println("- destory() run -");
}
}
package ex02;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
*
*/
public class HelloServlet extends HttpServlet {
// 404 뜨면 요청부터가 안되는 것 이므로 url 부터 잘 못 된 것이니까 잘해라 ㅇㅋ?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 이후의 문자열을 html 로 인식하라고 지정
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> HelloServlet </title>");
out.println("</head>");
out.println("<body>");
out.println("Hello Servlet<br/>");
out.println("안녕 서블릿 ^ㅋ^");
out.println("</body>");
out.println("</html>");
}
}
main - webapp - ex03 folder
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table, tr, td {
border: 1px solid gray;
border-collapse: collapse;
}
.title {
width: 100px ;
}
td {
padding: 10px;
font-size: 24px;
text-align: center
}
input[type=text] {
height: 26px;
font-size: 24px;
}
</style>
</head>
<body>
<h1>내용을 작성하세요</h1>
<form action="http://localhost:8080/03_Servlet/paramServlet" method="get">
<table>
<tr>
<td class="title"> 이름 </td>
<td><input type="text" id="user_name" name="userName"/></td>
</tr>
<tr>
<td class="title"> 나이 </td>
<td><input type="text" id="user_age" name="userAge"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="완료"/> <input type="reset" value="취소"/>
</td>
</tr>
</table>
</form>
</body>
</html>
package ex03;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParamServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 웹 브라우저에서 전송된 데이터 인코딩 설정
request.setCharacterEncoding("UTF-8");
// 전송 데이터
// - getParameter() 메서드르 사용해서
// <input> 태그의 name 속성값으로 전달된 value 를 가져옴
String name = request.getParameter("userName");
String stnAge = request.getParameter("userAge");
int age = Integer.parseInt(stnAge);
// 응답
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> 결 과 </title>");
out.println("</head>");
out.println("<body>");
out.println(name + "님의 나이 : " + age + "세<br/><br/>");
if(age > 19) out.println("성인");
else out.println("미성년자");
out.println("</body>");
out.println("</html>");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 정보</title>
</head>
<body>
<h1>정보 입력</h1>
<form method="get" action="http://localhost:8080/03_Servlet/memberServlet">
<table border="1">
<tr>
<td class="title">이 름</td>
<td><input type="text" id="user_name" name="userName" size="20"></td>
</tr>
<tr>
<td class="title">성 별</td>
<td>
<input type="radio" id="gender_m" name="gender" value="남자" checked> 남
<input type="radio" id="gender_f" name="gender" value="여자" > 여
</td>
</tr>
<tr>
<td class="title">취 미</td>
<td>
<input type="checkbox" id="hobby_1" name="hobby" value="독서"> 독서
<input type="checkbox" id="hobby_2" name="hobby" value="영화"> 영화
<input type="checkbox" id="hobby_3" name="hobby" value="음악"> 음악
<input type="checkbox" id="hobby_4" name="hobby" value="게임"> 게임
</td>
</tr>
<tr>
<td class="title">과 목</td>
<td>
<select id="subject" name="subject" size="5" multiple>
<option value="java"> JAVA </option>
<option value="jsp"> JSP </option>
<option value="spring"> Spring </option>
<option value="jquery"> jQuery</option>
<option value="servlet"> Servlet </option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="완료"> <input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
package ex04;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* # annotation
* - 컴파일러에게 코드 문법 에러를 체크하도록 정보를 제공
* - 실행시(런타임시) 특정 기능을 실행하도록 정보를 제공
*/
@WebServlet("/memberServlet") // 지금은 annotation 을 주로 사용 함
public class MemberServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("userName");
String gender = request.getParameter("gender");
// 체크박스, 과목(멀티) 여러 개 가능하므로 배열로 처리
String[] arrHobby = request.getParameterValues("hobby");
String[] arrSubject = request.getParameterValues("subject");
String hobby="";
if(arrHobby != null) {
for(int i=0; i<arrHobby.length; i++) {
if(arrHobby[i] != null) {
hobby += arrHobby[i] + " ";
}
}
}
String subject ="";
if(arrSubject != null) {
for(int i=0; i<arrSubject.length; i++) {
if(arrSubject[i] != null) {
subject += arrSubject[i] + " ";
}
}
}
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> 입력 내용</title>");
out.println("<style type=text/css>");
out.println("li {color: gray; font-size: 24px; font-weight:bold;margin-bottom:20px}");
out.println("a {color: green; font-size: 20px; font-weight:bold;text-decoration:none;}");
out.println("a:hover {color: green; font-size: 20px; font-weight:bold;text-decoration:none;}");
out.println("body {background:url(https://avatar.maplestory.nexon.com/Character/BAOBKLKMMDLKOEGHHGFPBOLAPJJAHHPEIJAGFBGMNJKADGCJKFNBGFGAHPDKHGFLCGLICMLPDFEELIEFDCCEJBLMJBEMIBMDJKEBEMCJGMJGGNKGDPKDBIBIEENJJJDNMNOFNLCDKFLIJBCJJIHDNFKGOKLFOHMPHMIKFPABGBKPKNLCHHKDIDPPIFKOCMKJLKJNHOMJMGHMKBGDBGPIGGACEAIOLKPMHLPMNBJFFJFJJFFFIDCOLIHDCLBFJCKH.png) no-repeat;"
+ "background-size: 500px auto;}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println("<h2> 입력 내용 </h2>");
out.println("<ul>");
out.println("<li>" + name + "</li>");
out.println("<li>" + gender + "</li>");
out.println("<li>" + hobby + "</li>");
out.println("<li>" + subject + "</li>");
out.println("</ul>");
out.println("<br/>");
out.println("<br/>");
out.println("<a href='javascript:history.back()'> 이전페이지</a>");
out.println("</body>");
out.println("</html>");
}
}
<!-- ex01.jsp -->
<%--
# JSP ( Java Server Page )
- 서블릿은 웹 응용프로그램을 효과적으로 개발할 수 있지만, 프로그램 작성이 불편한 단점이 있다.
JSP 는 서블릿 기술을 바탕으로, 빠르게 원하는 웹 응용프로그램을 작성할 수 있다.
- 실행 과정
.jsp -> .java -> .class -> server 실행
servlet compile
1. 사용자의 웹 브라우저에서 http://serverURL/xxx.jsp 형태로 해당 페이지 요청
2. 웹 서버는 요청한 페이지를 처리하기 위해 JSP 컨테이너에 페이지 처리 요청
3. 서블릿으로 변환해서 java class 파일로 컴파일
# JSP 지시자 : <%@ %>
- 페이지가 실행될 때 필요한 정보 또는 설정을 정의하는 역할
- 종류
> page : 해당 페이지에 대한 정보 및 설정을 하는 역할의 지시자
include : JSP 파일 내부에 다른 파일을 삽입하기 위한 지시자
taglib : JSP 페이지 내에서 사용되는 별도의 표현 언어들을 사용하기 위해서 쓰이는 지시자
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex01.jsp</title>
</head>
<body>
<%--
# 스크립트 요소
- JSP 프로그래밍에서 사용되는 문법의 표현 형태이다
- <%! %> : 선언문
-> JSP 에서 사용되는 변수나 메서드를 선언하는 영역
- <% %> : 스크립트릿
-> 일반적인 코드를 작성하는 영역(java code)
- <%= %> : 표현식
-> 데이터를 표현하는 영역
--%>
<h1>JSP 시작</h1>
<hr/>
<%-- 웹페이지 - 개발자도구에서 코드를 보면 jsp주석은 안보임 --%>
<%="JSP 시작 잘 나오는구만" %>
</body>
</html>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String today = sdf.format(date);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex02.jsp</title>
</head>
<body>
<h1>오늘 날짜</h1>
<br>
<h2>오늘은 <%= today %> 입니다.</h2>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex03.jsp</title>
<style type="text/css">
input[type=text]{
width: 100px;
height: 24px;
font-size: 22px;
}
</style>
</head>
<body>
<h1>숫자를 입력하세요</h1>
<br>
<form action="ex03Pro.jsp" method="get">
<input type="text" name="v1"> + <input type="text" name="v2">
<br><br>
<input type="submit" value="완료"> <input type="reset" value="취소">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/* String v1 = request.getParameter("v1");
int data1 = Integer.parseInt(v1); */
int data1 = Integer.parseInt(request.getParameter("v1"));
int data2 = Integer.parseInt(request.getParameter("v2"));
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex03Pro</title>
<style type="text/css">
p {
font-size: 24px;
}
</style>
</head>
<body>
<h1>계산 결과</h1>
<br>
<p><%=data1 %> + <%=data2 %> = <%=data1 + data2 %></p>
</body>
</html>
<%@ 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>
<style type="text/css">
</style>
</head>
<body>
<h1>이름, 나이를 입력하세요</h1>
<br>
<form action="ex04Pro.jsp" method="post">
<label>이 름 : </label>
<input type="text" name="name">
<br><br>
<label>나 이 : </label>
<input type="text" name="age">
<br><br>
<input type="submit" value="완료">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// get 방식은 한글이 깨지지 않음
// post 방식은 한글이 깨짐
// >> 해결 방법 : request.setCharacterEncoding("UTF-8"); 구문으로 깨짐 방지
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String adult ="";
if(age > 19) {
adult += "성인입니다.";
} else {
adult += "미성년자냐?";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex04Pro</title>
<style type="text/css">
p {
font-size: 24px;
}
</style>
</head>
<body>
<h1>결 과</h1>
<p>이름 : <%=name %>, 나이 : <%=age %>세, <%= adult%></p>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex05.jsp</title>
<style type="text/css">
</style>
</head>
<body>
<h1>성적 입력</h1>
<br>
<form action="ex05Pro.jsp" method="post">
이 름 : <input type="text" name="name"><br><br>
국 어 : <input type="text" name="kor"><br><br>
영 어 : <input type="text" name="eng"><br><br>
수 학 : <input type="text" name="math"><br><br>
<input type="submit" value="확인">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8"); // 포스트 방식 한글 깨짐 방지
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex05Pro</title>
<style type="text/css">
</style>
</head>
<body>
<h1> 성 적</h1>
<div>
수 : 90점 이상<br>
우 : 90점 미만, 80점 이상<br>
미 : 80점 미만, 70점 이상<br>
양 : 70점 미만, 60점 이상<br>
가 : 60점 미만
</div>
<hr>
<p>
<%
String name = request.getParameter("name");
float kor = Float.parseFloat(request.getParameter("kor"));
float eng = Float.parseFloat(request.getParameter("eng"));
float math = Float.parseFloat(request.getParameter("math"));
float tot = kor + eng + math;
float avg = tot/3;
String grade = "가";
if(avg >=90) grade ="수";
else if(avg >=80) grade ="우";
else if(avg >=70) grade ="미";
else if(avg >=60) grade ="양";
out.println(name + "님의 성적 : " + grade);
%>
</p>
</body>
</html>