ajax: 비동기적 처리 방식. jquery에 있는 ajax

 

html(): html태그를 이용하고 싶을때

text(): document 글자들을 가져오거나 바꿀때

val(): form의 값을 가져오거나 값을 설정할때

 


  • exam02.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>
<script src="../js/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
	$("#postBtn").click(function(){
		$.post("process.jsp", //ajax 기술(비동기적 처리)로 콜백한다는 뜻. action, window.open과 비슷.
				{"id" : document.getElementById("id").value, //dom방식
				 //"id" : $("#id").val(), //id와 pwd 값을 들고 콜백함수로 간다.
				 "pwd" : $("#pwd").val(),
				 "method" : "post"},
				 function(data){	//콜백함수. 결과값을 data라는 변수에 담고 result영역에 뿌린다.
					$("#postResult").html(data);	 
				 }
		); //post
	});//postBtn
	$("#getBtn").click(function(){
		$.get("process.jsp",{
								"id" : $("#id").val(),					
								"pwd" : $("#pwd").val(),
								"method" : "get"
			  				},
			  				function(ret){
				  				$("#getResult").html(ret);
			  				}
		);//get
	});//getBtn
	$("#loadBtn").click(function(){
		$("#loadResult").load("process.jsp", {
											"id" : $("#id").val(),	
											"pwd" : $("#pwd").val(),
											"method" : "load"
										}
		); //load
	});//loadBtn
	$("#ajaxBtn").click(function(){
		$.ajax({
			type : "post",
			url : "process.jsp",
			data : {
				"id" : $("#id").val(),
				"pwd" : $("#pwd").val(),
				"method" : "ajax"
			},
			success : function(d){ //성공
				$("#ajaxResult").html(d);
			}, 
			error : function(e){ //실패
				alert("에러: "+e);
			}
		});
	});//ajaxBtn
});//document
</script>
</head>
<body>
id: <input type="text" id="id" name="id"><br>
pwd: <input type="password" id="pwd" name="pwd"><br>
<input type="button" id="postBtn" value="post전송">
<input type="button" id="getBtn" value="get전송">
<input type="button" id="loadBtn" value="load전송">
<input type="button" id="ajaxBtn" value="ajax전송">
<br>
<div id="postResult"></div>
<div id="getResult"></div>
<div id="loadResult"></div>
<div id="ajaxResult"></div>
</body>
</html>

 


 

 

  • process.jsp: exam02.jsp의 콜백함수에 담길 데이터 값

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

    request.setCharacterEncoding("utf-8");

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

    String pwd=request.getParameter("pwd");

    String str="처리결과 <br>";

    str+="아이디: "+id+"<br>";

    str+="비번: "+pwd+"<br>";

    out.println(str);

%>

 


 

 

'Learning > JSP' 카테고리의 다른 글

주소록 생성하기2  (0) 2020.07.16
JSON 형식의 데이터값 읽어오기  (0) 2020.07.15
자바스크립트, DB 이용하여 주소록 생성하기  (0) 2020.07.13
jQuery 이용  (0) 2020.07.10
JSP액션 태그, 객체와 getter setter이용  (0) 2020.07.09
  • <form>태그: 폼을 만드는 기본 태그. 

    • method: 사용자가 입력한 내용들을 서버 프로그램으로 어떻게 넘겨줄지 지정

      • get: 사용자가 입력한 내용이 그대로 표시

      • post: 입력 내용의 길이에 제한 X, 입력한 내용 표시 X

    • name: 폼의 이름 지정

    • action: 폼 내용들을 처리해줄 서버 상의 프로그램 지정

    • target: 현재 창이 아닌 다른 위치에 열도록 지정

 

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>label 태그 사용</title>

        <style>

            ul {

                list-style:none;

            }

            li {

                margin:20px;

            }

        </style>

</head>

<body>

    <form>

        <h3>수강분야(다수 선택가능)</h3>

        <ul>

            <li><input type="checkbox" value="grm">문법</li>

            <li><input type="checkbox" value="wr">작문</li>

            <li><input type="checkbox" value="rd">독해</li>

        </ul>

        <h3>수강과목(1과목만 선택가능)</h3>

        <ul>

            <li><input type="radio" name="subject" value="eng">영어회화</li>

            <li><input type="radio" name="subject" value="chn">중국어회화</li>

            <li><input type="radio" name="subject" value="jap">일어회화</li>

        </ul>

    </form>

</body>

</html>


  • <fieldset>: 폼 요소를 그룹으로 묶는 태그

  • <legend>: 필드셋의 제목을 붙이는 태그

 

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>filedset과 legend 태그</title>

        <style>

            ul {

                list-style:none;

            }

            li {

                margin:20px;

            }

            li label {

                width:80px;

                float:left;

            }

            fieldset {

                margin:15px;

            }

        </style>

</head>

<body>

    <form>

    <fieldset>

        <legend>개인정보</legend>

        <ul>

            <li>

                <label for="name">이름</label>

                <input type="text" id="name">

            </li>

            <li>

                <label for="mail">메일주소</label>

                <input type="text" id="mail">

            </li>

        </ul>

    </fieldset>

    <fieldset>

        <legend>로그인 정보</legend>

        <ul>

            <li>

                <label for="id">아이디</label>

                <input type="text" id="id">

            </li>

            <li>

                <label for="pw">비밀번호</label>

                <input type="text" id="pw">

            </li>

        </ul>

    </fieldset>

    </form>

</body>

</html>


  • <input> 태그: 입력하는 부분. 내용의 종류는 type속성을 통해 지정

    • hidden: 사용자에게 보이지 않고 서버로 넘겨짐

    • text: 텍스트필드

    • search: 검색 상자

    • email: 메일 주소 입력

    • password: 비밀번호 입력

    • tel: 전화번호 입력 필드

    • checkbox: 체크박스

    • submit: 서버 전송 버튼

    • image: submit 버튼 대신 사용할 이미지 삽입

    • reset: 리셋 버튼

    • button: 버튼

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>filedset과 legend 태그</title>

        <style>

            ul {

                list-style:none;

            }

            li {

                margin:10px;

            }

            li label {

                width:120px;

                float:left;

                text-align: right;

                padding-right: 8px;

            }

            fieldset {

                margin:15px;

            }

            input{

                width:200px;

            }

            input[type="submit"]{ 

                text-align: center;

                width: 100%;

                height: 30px;

                margin-top: 15px;

            }

        </style>

</head>

<body>

    <form>

    <fieldset>

        <legend>로그인 정보</legend>

        <ul>

            <li> 

                <label for="id">아이디</label>

                <input type="text" id="id">

            </li>

            <li>

                <label for="pw1">비밀번호</label>

                <input type="password" id="pw1">

            </li>

            <li>

                <label for="pw2">비밀번호 확인</label>

                <input type="password" id="pw2">

            </li>

        </ul>

    </fieldset>

    <fieldset>

        <legend>개인정보</legend>

        <ul>

            <li>

                <label for="name">이름</label>

                <input type="text" id="name">

            </li>

            <li>

                <label for="mail">메일주소</label>

                <input type="email" id="mail">

            </li>

            <li>

                <label for="phone">연락처</label>

                <input type="tel" id="phone">

            </li>

            <li>

                <label for="homep">블로그/홈페이지</label>

                <input type="url" id="homep"> <!--정확한 홈페이지 주소를 입력받기 위함-->

            </li>

        </ul>

    </fieldset>

    <input type="submit" value="가입하기">

    </form>

</body>

</html>

 

 


<!doctype html>

<html lang="ko">

  <head>

        <meta charset="utf-8">

     <title> 웹 폼</title>

     <style>

     body {

        background-color:#fff; 

     }

     form fieldset{

        margin-bottom:25px; 

     }   

     form legend{

        font-size:15px;

        font-weight:600; 

     }

     form label.reg {

        font-size:14px;

        color:#390;

        font-weight:bold;

        width:110px;

        float:left;

        text-align:right;

        margin-right:10px;

     }

     form ul li{

        list-style:none; 

        margin: 15px 0; 

        font-size:14px; 

     }

     

     #member, #stuffs {

        width:50px; 

     }

     

     #pre {

        margin-left:15px;

     }

     </style>

  </head>

  <body>

    <form>

        <fieldset>

            <legend>신청 과목</legend>

            <p>이 달에 신청할 과목을 선택하세요(1과목만 가능)</p>

            <label><input type="radio" name="subject" value="spk">회화</label>

            <label><input type="radio" name="subject" value="grm">문법</label>

            <label><input type="radio" name="subject" value="wr">작문</label>

        </fieldset>

        <fieldset>

            <legend>메일링</legend>

            <p>메일로 받고 싶은 뉴스 주제를 선택하세요 (복수 선택 가능)</p>

            <label><input type="checkbox" name="mailing1" value="news">해외 단신</label>

            <label><input type="checkbox" name="mailing2" value="dialog">5분 회화</label>

            <label><input type="checkbox" name="mailing3" value="pops">모닝팝스</label>

        </fieldset>

    </form>

  </body>

</html>

 

 

 


 

<!doctype html>

<html lang="ko">

  <head>

     <meta charset="utf-8">

     <title> 웹 폼</title>

  </head>

  <body>

    <form>

      <fieldset>

        <legend>과 티셔츠 설문</legend>

        <p>올해 과 티(T)를 만들려고 합니다. 원하는 색상을 추천해주세요</p>

        <label>선호색상<input type="color" value="#00FF00"></label>

      </fieldset>

    </form>

  </body>

</html>

 

 

 


 

 

 

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>date</title>

</head>

<body>

    <form>

        <fieldset>

            <legend><h3>조회기간 선택</h3></legend>

            <label>시작: <input type="date" id="start" value="2020-07-01"></label>

            <label>끝: <input type="date" id="end" value="2020-12-31"></label>

        </fieldset>

        <fieldset>

            <legend><h3>대관시간 선택(오늘)</h3></legend>

            <label>시작 시간 <input type="time" value="09:00" id="start"></label>

            <label>종료 시간 <input type="time" value="18:00" id="end"></label>

        </fieldset>

        <fieldset>

            <legend><h3>대관시간 선택(다른날짜)</h3></legend>

            <label>시작 시간<input type="datetime-local" value="2020-07-01T09:00"></label>

            <label>종료 시간<input type="datetime-local" value="2020-12-31T09:00"></label>

        </fieldset>

    </form>

</body>

</html>

 


 

 

  • input 타입 중 submit: 제출

  • input 타입 중 reset: 취소 (쓴 내용을 지움)

 

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>전송 - 리셋 </title>

    <style>

        body {

            padding:20px;

        }

    </style>

</head>

<body>

    <form action="register.asp" method="post">

        <fieldset>

            <h3>메일링 리스트 등록</h3>

            <label> 메일 주소 <input type="email"></label>

            <input type="submit" value="제출">

            <input type="reset" value="다시입력">

        </fieldset>

    </form>

</body>

</html>

 

 


  • input 타입 중 image: 버튼 대신 이미지 삽입

 

<!DOCTYPE html>



<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>이미지 버튼 </title>

    <style>

        table {

            border:0;

        }

        td {

            padding:5px 10px;

            border:0;

            vertical-align: middle;

        }

    </style>

</head>

<body>

    <table>

        <tr>

            <td>

                <label>아이디 <input type="text" size="15"></label>

            </td>

            <td>

                <label>비밀번호 <input type="password" size="15"></label>

            </td>

            <td>

                <input type="image" id="button" src="images/login.jpg" alt="login">

            </td>

        </tr>

    </table>

</body>

</html>

 

 


  • button 타입 중 onclick 속성: 함수 연결

 

<!DOCTYPE html>

<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>폼 버튼 </title>

    <style>

        li{

            list-style: none;

            padding: 10px;

        }

    </style>

</head>

<body>

    <form>

        <ul>

            <li><input type="button" value="새 탭 열기" onclick="window.open()"></li>

            <li><input type="button" value="탭 닫기" onclick="window.close()"></li>

        </ul>

    </form>

</body>

</html>

 

 

 


 

<이미지와 하이퍼링크>

  • <img src>: 이미지 삽입 태그

  • width, height: 이미지 크기 조절

 

<!DOCTYPE html>

<html lang="ko">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>이미지 삽입하기</title>

</head>

<body>

  <h1>이미지 크기 조절</h1>

  <img src="images/gugudan.jpg" alt="바빠 구구단">

  <img src="images/gugudan.jpg" width="250" height="250">

</body>

</html>

 

 

 


 

  • <figure><figcaption>: 이미지 설명

 

<!DOCTYPE html>

<html lang="ko">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>이미지 삽입하기</title>

  <style>

    img {

      border:1px solid #ccc;    

    }

    figure {

      display:inline-block;

    }

  </style>

</head>

<body>

  <figure>

    <img src="images/prod.jpg" alt="모카 마타리">

    <figcaption>예맨 모카 마타리</figcaption>

  </figure>

</body>

</html>


 

  • <a>태그: 하이퍼링크. <a>태그의 속성들

    • href : 링크한 문서나 사이트의 주소 입력

    • target: 링크한 내용이 표시될 위치를 지정

    • download: 링크한 내용을 다운로드

 

  • target 속성들

    • _blank: 링크 내용이 새 창이나 새 탭에서 열림

 

<!DOCTYPE html>

<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>링크 만들기</title>

    <style>

        a{

            text-decoration: none;

            color:black;

        }

    </style>

    </head>

<body>

    <h1>텍스트 링크 만들기</h1>

    <a href="http://www.google.com" target="_blank">구글사이트 이동</a>

    <h1>이미지 링크 만들기</h1>

    <a href="http://www.google.com">

        <img src="images/google.jpg">

    </a>

</body>

</html>


 

  • 한 페이지 안에서 이동하기

  • <a href="#"> 이용. 이동하고자 하는 단락에 id를 부여하고 하이퍼링크 주소에는 id를 뜻하는 #을 앞에 붙여줌

 

<!DOCTYPE html>

<html lang="ko">

<head>

    <meta charset="utf-8">

    <title>링크 만들기</title>

</head>

<body>

    <h1>앵커 만들기</h1>

    <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

    <ul id="menu">

        <li><a href="#content1"> 메뉴 1</a></li>

        <li><a href="#content2"> 메뉴 2</a></li>

        <li><a href="#content3"> 메뉴 3</a></li>

    </ul>

    <h2 id="content1">내용1</h2>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p><a href="#menu">[홈으로]</a></p>

    <h2 id="content2">내용2</h2>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p><a href="#menu">[홈으로]</a></p>

    <h2 id="content3">내용3</h2>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p>웹 문서가 너무 길 경우 필요한 곳마다 문서 안에 이름을 붙여놓고 그 위치로 한번에 이동하는 링크를 만들 수 있는데, 이 기능을 앵커(anchor)라고 합니다. </p>

        <p><a href="#menu">[홈으로]</a></p>

</body>

</html>

 

 


 

  • <area>태그, usemap 속성: 한 이미지 상에 여러 다른 링크를 만드는 것

 

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>이미지맵</title>

    <style>

        a {

            text-decoration:none

        }

    </style>

</head>



<body>

    <img src="images/kids.jpg" alt="어린이이미지" usemap="#favorite">

    <map name="favorite">

        <area shape="rect" coords="10,10,160,200" href="http://www.daum.net" target="_blank" alt="다음페이지이동">

        <area shape="rect" coords="220,10,380,200" href="http://www.google.com" target="_blank" alt="구글페이지이동">

    </map>

</body>

</html>

 

 

 


 

  • svg 파일: 이미지를 확대하거나 축소하더라도 테두리가 원래의 깨끗한 상태로 유지되는 벡터 이미지

 

 

 

list.jsp 실행시 인터넷 화면

 

이름을 눌렀을때 수정, 삭제 할 수 있는 선택지가 주어짐 (detail.jsp)

 

우편번호 검색 버튼을 눌렀을 경우 (detail.jsp에서 zipCheck.jsp로 넘어감)

 

동이름 검색
클릭시 자동으로 입력

 

삭제 글자를 누르면 팝업창이 뜨고 삭제 가능

 

  • Address.java : 게터 세터, 생성자

 

 

 

package com.address;

public class Address {

    private long num;

    private String name;

    private String zipcode;

    private String tel;

    private String addr;

    

    public long getNum() {

        return num;

    }

    public void setNum(long num) {

        this.num = num;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getZipcode() {

        return zipcode;

    }

    public void setZipcode(String zipcode) {

        this.zipcode = zipcode;

    }

    public String getTel() {

        return tel;

    }

    public void setTel(String tel) {

        this.tel = tel;

    }

    public String getAddr() {

        return addr;

    }

    public void setAddr(String addr) {

        this.addr = addr;

    }

}

 

 

  • AddressDAO.java : 입력 수정 삭제 등 DB와 연결

 

package com.address;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.sql.DataSource;

public class AddressDAO {

    //싱글톤 패턴. 최초 한번만 메모리 할당 (static)

    //AddressDAO클래스에 인스턴스를 만들어 사용

    private static AddressDAO instance = new AddressDAO();

    public static AddressDAO getInstance() {

        return instance;

    }

    //디비연결 (scott의 address 테이블)

    private Connection getConnection() throws Exception{

        Context initCtx=new InitialContext();

        Context envCtx=(Context)initCtx.lookup("java:comp/env");

        DataSource ds=(DataSource)envCtx.lookup("jdbc/jsp");

        //톰캣에서 jdbc/jsp라는 이름을 찾아서 커넥션 시킨다.

        return ds.getConnection();

    }

    

    //추가

    public void addrInsert(Address ad) {

        Connection con=null;

        PreparedStatement ps=null;

        try {

            con=getConnection();

            String sql="INSERT INTO address "

                    + "VALUES (address_seq.nextval,?,?,?,?)";

            ps=con.prepareStatement(sql);

            ps.setString(1, ad.getName());

            ps.setString(2, ad.getZipcode());

            ps.setString(3, ad.getAddr());

            ps.setString(4, ad.getTel());

            ps.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con,ps);

        }

    }

    

    //수정

    public void addrUpdate(Address ad) {

        Connection con=null;

        PreparedStatement ps=null;

        try {

            con=getConnection();

            String sql="UPDATE address SET name=?, zipcode=?, "

                    + "addr=?, tel=? WHERE num=?";

            ps=con.prepareStatement(sql);

            ps.setString(1, ad.getName());

            ps.setString(2, ad.getZipcode());

            ps.setString(3, ad.getAddr());

            ps.setString(4, ad.getTel());

            ps.setLong(5, ad.getNum());

            ps.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, ps);

        }

    }

    

    //전체보기

    public ArrayList<Address> addrList(String field, String word){

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        String sql="";

        ArrayList<Address> arr=new ArrayList<Address>();

        try {

            con=getConnection();

            if(word.equals("")) { //검색이 아닐떄

                sql="SELECT * FROM address";

            }else { //검색일때

                sql="SELECT * FROM address WHERE "+field+" LIKE '%"+word+"%'";

                //sql="select * from address where tel like '%010%'";

            }

            st=con.createStatement();

            rs=st.executeQuery(sql);

            while(rs.next()) {

                Address ad=new Address();

                ad.setNum(rs.getInt("num"));

                ad.setName(rs.getString("name"));

                ad.setAddr(rs.getString("addr"));

                ad.setZipcode(rs.getString("zipcode"));

                ad.setTel(rs.getString("tel"));

                arr.add(ad);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con,st,rs);

        }

        return arr;

    }

    

    //개수출력

    public int getCount(String field, String word) {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        String sql="";

        int count=0;

        try {

            con=getConnection();

            if(word.equals("")) { //검색아니고 전체

                sql="SELECT COUNT(*) FROM address";

            }else { //검색일때

                sql="SELECT COUNT(*) FROM address WHERE "+field+" LIKE '%"+word+"%'";

            }

            st=con.createStatement();

            rs=st.executeQuery(sql);

            if(rs.next()) {

                count=rs.getInt(1); //address테이블의 첫번째 컬럼의 개수

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return count;

    }

    

    //상세보기

    public Address addrDetail(int num) {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        Address ad=null;

        try {

            con=getConnection();

            String sql="SELECT * FROM address where num="+num;

            st=con.createStatement();

            rs=st.executeQuery(sql);

            if(rs.next()) {

                ad=new Address();

                ad.setAddr(rs.getString("addr"));

                ad.setName(rs.getString("name"));

                ad.setNum(rs.getLong("num"));

                ad.setTel(rs.getString("tel"));

                ad.setZipcode(rs.getString("zipcode"));

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con,st,rs);

        }

        return ad;

    }

    

    //삭제

    public void addrDelete(int num) {

        Connection con=null;

        Statement st=null;

        try {

            con=getConnection();

            String sql="DELETE FROM address WHERE num="+num;

            st=con.createStatement();

            st.executeUpdate(sql);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, null);

        }

    }

    

    

    //우편번호 검색

    public ArrayList<ZipCodeBean> zipcodeRead(String dong) {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        ArrayList<ZipCodeBean> zipArr=new ArrayList<>();

        //결과값이 여러개라서 ArrayList사용

        

        try {

            con=getConnection();

            //select * from zipcode where dong like '%서면%';

            String sql="SELECT * FROM zipcode WHERE dong like '%"+dong+"%'";

            st=con.createStatement();

            rs=st.executeQuery(sql);

            while(rs.next()) {

                ZipCodeBean zip=new ZipCodeBean();

                zip.setBunji(rs.getString("bunji"));

                zip.setDong(rs.getString("dong"));

                zip.setGugun(rs.getString("gugun"));

                zip.setSeq(rs.getInt("seq"));

                zip.setSido(rs.getString("sido"));

                zip.setZipcode(rs.getString("zipcode"));

                zipArr.add(zip);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return zipArr;

    }

    

    

    //closeConnection

    private void closeConnection(Connection con, PreparedStatement ps) {

        try {

            if(ps!=null) ps.close();

            if(con!=null) con.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

    private void closeConnection(Connection con, Statement st, ResultSet rs) {

        try {

            if(st!=null) st.close();

            if(con!=null) con.close();

            if(rs!=null) rs.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

  • list : 주소록 목록을 보여주는 jsp

 

<%@page import="com.address.Address"%>

<%@page import="com.address.AddressDAO"%>

<%@page import="java.util.ArrayList"%>

<%@ 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>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<style>

div.divCss{

    text-align: right;

    background-color: darkgray;

    padding-right: 20px;

}

a:hover{text-decoration: none;}

a:link{text-decoration: none;}

a:visited{text-decoration: none;}

</style>

</head>

<script src="../js/jquery-3.5.1.min.js"></script>

<script>

    function searchCheck(){

        if($("#word").val()==""){

            alert("검색어를 입력하세요");

            $("#word").focus();

            return false;

        }

        $("#searchFrm").submit();

    }

    

    function delFunc(no){

        if(confirm("정말 삭제할까요?")){

            location.href="deletePro.jsp?num="+no;

        }

    }

</script>

<%

    request.setCharacterEncoding("utf-8");

    String word ="";

    String field="";

    if(request.getParameter("word")!=null){

        field=request.getParameter("field");

        word=request.getParameter("word");

    }

    AddressDAO dao=AddressDAO.getInstance();

    ArrayList<Address> arr=dao.addrList(field, word);

    int count=dao.getCount(field, word); //전체 개수 혹은 검색한 개수 출력

%>

<body>

<div class="divCss"> <!-- 문단태그 -->

    주소록 갯수: <%=count %><br>

    <a href="insert.jsp">추가하기 /</a>

    <a href="list.jsp">전체보기</a>

</div>

<table class="table">

        <thead class="thead-dark">              <!-- 이미 정의되어 있는 테이블 스타일 -->

          <tr>

            <th scope="col">번호</th>

            <th scope="col">이름</th>

            <th scope="col">우편번호</th>

            <th scope="col">주소</th>

            <th scope="col">전화번호</th>

            <th scope="col">삭제</th>

          </tr>

        </thead>

    <tbody>

    <%

        for(int i=0;i<arr.size();i++){

    %> <!-- 태그는 스크립틀릿안에 들어가면 안되므로 따로 빼줌 -->

        <tr>

            <th scope="row"><%=arr.get(i).getNum() %></th>

            <td>

            <a href="detail.jsp?num=<%=arr.get(i).getNum() %>">

            <%=arr.get(i).getName() %></a></td>

            <td><%=arr.get(i).getZipcode() %></td>

            <td><%=arr.get(i).getAddr() %></td>

            <td><%=arr.get(i).getTel() %></td>

            <td onclick="delFunc(<%=arr.get(i).getNum()%>)">삭제</td>

        </tr>

    <%} //end for문

    %>

    </tbody>

</table>

<form action="list.jsp" name="searchFrm" id="searchFrm">

    <select name="field">

        <option value="name">이름</option>

        <option value="tel">전화번호</option>

    </select>

    <input type="text" name="word" id="word">

    <input type="button" value="검색" class="btn btn-primary" onclick="searchCheck()">

</form>

</body>

</html>

 

 

  • detail.jsp: 주소록 수정 및 삭제 jsp

 

<%@page import="com.address.Address"%>

<%@page import="com.address.AddressDAO"%>

<%@ 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>

<script src="../js/jquery-3.5.1.min.js"> </script> <!-- cdn방식 -->

<%

    request.setCharacterEncoding("utf-8");

    int num=Integer.parseInt(request.getParameter("num"));

    AddressDAO dao=AddressDAO.getInstance();

    Address address=dao.addrDetail(num);

%>

<script>

//query 이용

$(document).ready(function(){ //document.ready를 통해 메소드를 로드해야함.

    $("#deleteBtn").click(function(){

        if(confirm("정말 삭제할까요?")){

            //location.href="deletePro.jsp?num=<%=num%>";

            $(location).attr("href","deletePro.jsp?num=<%=num%>");

        }

    });

})

function del(){

    if(confirm("정말 삭제할까요?")){

        location.href="deletePro.jsp?num=<%=num%>";

    }

}

//매개변수 있는 함수

function dels(no){

    if(confirm("정말 삭제할까요?")){

        location.href="deletePro.jsp?num="+no;

    }

}

</script>

</head>

<body>

<form action="updatePro.jsp" method="post">

<input type="hidden" name="num" value=<%=num %>> <!-- hidden: 사용자에겐 보이지 않지만 서버한테 전달됨 -->>

<table>

    <tr>

        <td colspan="2">주소록 수정하기</td>

    </tr>

    <tr>

        <td>이름</td>

        <td><input type="text" name="name"

        value="<%=address.getName()%>"></td>

    </tr>

    <tr>

        <td>우편번호 </td>

        <td><input type="text" name="zipcode" size=10

        value="<%=address.getZipcode()%>">

        <input type="button" name="search" value="검색"></td>

    <tr>

        <td>주소

        <td><input type="text" name="addr" size=30

        value="<%=address.getAddr()%>"></td>

    </tr>

    </tr>

        <td>전화번호</td>

        <td><input type="text" name="tel"

        value="<%=address.getTel()%>"></td>

    <tr>

        <td colspan="2">

        <input type="submit" value="수정">

        <input type="button" value="삭제" onclick="del()"> <!-- del()이라는 함수를 부른다. -->

        <input type="button" value="매개변수삭제" onclick="dels(<%=num%>)"> <!-- 인자가 있는 함수를 부른다.파라미터값이 하나-->

        <input type="button" value="jquery삭제" id="deleteBtn"> <!-- deleteBtn이라는 아이디 값을 하나 준다. -->

        <input type="reset" value="취소">

        </td>

    </tr>

</table>

</form>

</body>

</html>

 

 

  • insert.jsp : 주소록 입력 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>

<script src="../js/jquery-3.5.1.min.js"></script>

<script>

$(function(){

    $("#btn").on("click",function(){

        if($("#name").val()==""){

            alert("이름을 입력하세요");

            return false;

        }

        if($("#zipcode").val()==""){

            alert("우편번호을 입력하세요");

            return false;

        }

        if($("#addr").val()==""){

            alert("주소를 입력하세요");

            return false;

        }

        if($("#tel").val()==""){

            alert("전화번호를 입력하세요");

            return false;

        }

        frm.submit();

    });

})

function zipfinder(){

    window.open("zipCheck.jsp","","width=700 height=400");   

}

</script>

</head>

<body>

<a href="list.jsp">전체보기</a> <br>

<form action="insertPro.jsp" method="post" name="frm" id="frm">

<table>

    <tr>

        <td colspan="2">주소록 등록하기</td>

    </tr>

    <tr>

        <td>이름</td>

        <td><input type="text" name="name" id="name" size=15></td>

    </tr>

    <tr>

        <td>우편번호 </td>

        <td><input type="text" name="zipcode" id="zipcode" size=10>

        <input type="button" name="search" value="검색" onclick="zipfinder()"></td>

    <tr>

        <td>주소

        <td colspan="2"><input type="text" name="addr" id="addr" size=30>

        </td>

    </tr>

    </tr>

        <td>전화번호</td>

        <td colspan="2"><input type="text" name="tel" id="tel" size=15></td>

    <tr>

        <td colspan="2">

        <input type="submit" value="등록">

        <input type="reset" value="취소"></td>

    </tr>

</table>

</form>

</body>

</html>

 

 

  • insertPro.jsp: java class를 부르는 자바빈 액션태그들로 구성되어 있음. list.jsp로 가게함

 

<%@page import="com.address.AddressDAO"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!-- 화면에 보여줄 내용이 없음 -->

<%

    request.setCharacterEncoding("utf-8"); //한글처리

%>

<jsp:useBean id="ad" class="com.address.Address"/>

<jsp:setProperty property="*" name="ad"/>

<%

    AddressDAO dao=AddressDAO.getInstance(); //생성된 객체를 반환하기 위해 getInstance()메소드 이용

    dao.addrInsert(ad);

    response.sendRedirect("list.jsp"); //화면의 내용을 받아넣고 list.jsp로 가라는 뜻

%>

 

  • deletePro.jsp: java class를 부르는 자바빈 액션태그들로 구성. 데이터를 삭제하기 위한 jsp. list.jsp로 가게함

 

<%@page import="com.address.AddressDAO"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

    request.setCharacterEncoding("utf-8");

%>

<jsp:useBean id="ad" class="com.address.Address"/>

<jsp:setProperty property="*" name="ad"/>

<%

    int num=Integer.parseInt(request.getParameter("num"));

    AddressDAO dao=AddressDAO.getInstance();

    dao.addrDelete(num);

    response.sendRedirect("list.jsp");

%>

 

  • zipCheck: 우편번호 검색하는 새창 jsp

 

<%@page import="com.address.ZipCodeBean"%>

<%@page import="java.util.ArrayList"%>

<%@page import="com.address.AddressDAO"%>

<%@ 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>

a:hover{

    text-decoration: none; color:#000;

}

a:link{

    text-decoration: none; color:#000;

}

a:visited{

    text-decoration: none; color:#000;

}

</style>

<script src="../js/jquery-3.5.1.min.js"></script>

<%

    request.setCharacterEncoding("utf-8");

    String dong=request.getParameter("dong");

    

    AddressDAO dao=AddressDAO.getInstance();

    ArrayList<ZipCodeBean>zarr=dao.zipcodeRead(dong);

%>

<script>

function dongCheck(){

    if($("#dong").val()==""){

        alert("동이름을 입력하세요");

        $("#dong").focus();

        return false;

    }

    $("#frm").submit();

}

function send(code,sido,gugun,dong,bunji){

    var address=sido+" "+gugun+" "+dong+" "+bunji;

    opener.document.frm.zipcode.value=code; //insert.jsp에 있는 form의 이름이 frm.그 frm의 zipcode의 값을 code로 바꾸겠다.

    opener.document.frm.addr.value=address;

    self.close();   

}

</script>

</head>

<body>

<form action="zipCheck.jsp" id="frm" name="frm">

<table>

    <tr>

        <td>동이름 입력: <input type="text" name="dong" id="dong">

        <input type="button" value="검색" onclick="dongCheck()">

        </td>

    </tr>

    <tr>

    <%

        if(zarr.isEmpty()){

    %>

            <tr>

             <td>검색된 결과가 없습니다.</td>

            </tr>

    <%  

        }else{

    %>

        <tr>

            <td>검색 후, 아래 우편번호를 클릭하면 자동으로 입력됩니다.</td>

        </tr>

    <%

        for(ZipCodeBean z:zarr){

            String zip =z.getZipcode();

            String sido =z.getSido();

            String bunji =z.getBunji();

            String gugun =z.getGugun();

            String d =z.getDong();

    %>

            <tr>    

                <td><a href="javascript:send('<%=zip%>','<%=sido%>','<%=gugun%>','<%=d%>','<%=bunji%>')">

                <!-- javascript:자바스크립트임을 알려줌. 문자열이라서 홑따옴표 -->

                <%=zip%><%=sido%><%=gugun%><%=d%><%=bunji%>

                </a></td>

            </tr>

    <%

            } //for

       }//else

    %>

    </tr>

</table>

</form>

</body>

</html>

 

 

  • ZipCodeBean.java : 도시, 구, 동, 우편번호가 저장되어있는 DB와 관련된 게터 세터, 생성자

 

 

package com.address;

public class ZipCodeBean {

    private String zipcode;

    private String sido;

    private String gugun;

    private String dong;

    private String bunji;

    private int seq;

    public String getZipcode() {

        return zipcode;

    }

    public void setZipcode(String zipcode) {

        this.zipcode = zipcode;

    }

    public String getSido() {

        return sido;

    }

    public void setSido(String sido) {

        this.sido = sido;

    }

    public String getGugun() {

        return gugun==null? "":gugun.trim();

    }

    public void setGugun(String gugun) {

        this.gugun = gugun;

    }

    public String getDong() {

        return dong;

    }

    public void setDong(String dong) {

        this.dong = dong;

    }

    public String getBunji() {

        return bunji==null? "":bunji.trim(); //null이면 공백 아니면 bunji값 (삼항연산자)

    }

    public void setBunji(String bunji) {

        this.bunji = bunji;

    }

    public int getSeq() {

        return seq;

    }

    public void setSeq(int seq) {

        this.seq = seq;

    }

} 

 

 

  • input.jsp를 복사해서 input2.jsp 파일 생성

  • function으로 함수를 부를 수도 있지만 제이쿼리를 쓰기위한 라이브러리 파일을 다운받아서 사용

 

  • 절대경로: 루트부터

  • 상대경로: 나 자신으로 부터 (. (점): 나 자신, ..(점점): 부모)

  • 아이디는 #으로 시작, 클래스는 . 으로 시작

  • val(): 밸류값을 가져오는 함수

  • 태그는 # 붙이지 않음. []는 속성

 


  • 제이쿼리를 이용해서 alert창 띄우기 (input2.jsp)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<%@ 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>
<!--다운받은 제이쿼리 이용<script src="../js/jquery-3.5.1.min.js"></script> -->
<!--제이쿼리 주소이용 -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
/*
$(document).ready(function(){ //function이 로드될때까지 기다려라
    $("#btn").click(function(){ //btn이 클릭되면 함수를 호출할건데 그 함수의 이름 없이 바로 내용이 들어간다.
        alert("test");
    }); 
})
*/
$(function(){
    $("#btn").on("click",function(){ //btn이 클릭되면 함수를 호출할건데 그 함수의 이름 없이 바로 내용이 들어간다.
        if($("#name").val()==""){ //get.ElementByName과 같은 뜻. val()은 밸류 값을 가져오는 함수
            alert("이름을 입력하세요");
            return false;
        } //if
        if($("#studentNum").val()==""){
            alert("학번을 입력하세요");
            return false;
        } //if
        if($("input[name='hobby']:checked").length==0){ //태그는 #안붙임. []는 속성
            alert("취미를 입력하세요");
            return false;
        } //if
        //frm.submit();
        $("#frm").submit();
    }); //click
}) //function
</script>
</head>
<body>
<form action="inputResult.jsp" method="post" name="frm" id="frm">
<!--method="post"하면 선택된 값들이 주소창에 안보임--> <!--method="get"하면 주소창에 선택값들이 표시됨 -->
이름: <input type="text" name="name" id="name"><br> <!-- DOM방식은 id로 접근 -->
학번: <input type="text" name="studentNum" id="studentNum"><br>
성별:
<!--
<input type="radio" name="gender" value="man" checked>남자
<input type="radio" name="gender" value="woman">여자<br>
-->
<input type="radio" name="gender" value="man" checked  id="man">
<label for="man">남자</label> <!-- id, label을 이용하여 글자를 클릭해도 선택됨 -->
<input type="radio" name="gender" value="woman" checked  id="woman">
<label for="woman">여자</label><br>
전공:
<select name="major" id="major">
    <option value="국문학과">국문학과</option>
    <option value="영문학과">영문학과</option>
    <option value="수학과">수학과</option>
    <option value="정치학과">정치학과</option>
    <option value="체육학과">체육학과</option>
</select>
<br>
취미<br>
<input type="checkbox" name="hobby" value="운동">운동
<input type="checkbox" name="hobby" value="운동1">운동1
<input type="checkbox" name="hobby" value="운동2">운동2
<input type="checkbox" name="hobby" value="운동3">운동3
<input type="checkbox" name="hobby" value="운동4">운동4 <br>
<input type="button" value="보내기" id="btn">
<input type="reset" value="취소">
</form>
</body>
</html>
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<%@ 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>
<script>
function check(){
    if(document.getElementById("name").value==""){
        alert("이름을 입력하세요");
        return;
    }
    if(document.getElementById("studentNum").value==""){
        alert("학번을 입력하세요");
        return;
    }
    var obj=document.getElementsByName("hobby");
    var checkCnt=false;
    for(i=0;i<obj.length;i++){
        if(obj[i].checked){
            checkCnt=true;    
        }
    }
    if(checkCnt==false){
        alert("취미를 선택하세요");
        return;
    }
    frm.submit(); //직접 submit()이라는 메소드를 호출. 액션을 들고 가줌
}
</script>
</head>
<body>
<form action="inputResult.jsp" method="post" name="frm"> 
<!--method="post"하면 선택된 값들이 주소창에 안보임--> <!--method="get"하면 주소창에 선택값들이 표시됨 -->
이름: <input type="text" name="name" id="name"><br> <!-- DOM방식은 id로 접근 -->
학번: <input type="text" name="studentNum" id="studentNum"><br>
성별: 
<!-- 
<input type="radio" name="gender" value="man" checked>남자
<input type="radio" name="gender" value="woman">여자<br>
-->
<input type="radio" name="gender" value="man" checked  id="man">
<label for="man">남자</label> <!-- id, label을 이용하여 글자를 클릭해도 선택됨 -->
<input type="radio" name="gender" value="woman" checked  id="woman">
<label for="woman">여자</label><br>
전공: 
<select name="major">
    <option value="국문학과" selected>국문학과</option>
    <option value="영문학과">영문학과</option>
    <option value="수학과" >수학과</option>
    <option value="정치학과">정치학과</option>
    <option value="체육학과">체육학과</option>
</select>
<br>
취미<br>
<input type="checkbox" name="hobby" value="운동">운동
<input type="checkbox" name="hobby" value="운동1">운동1
<input type="checkbox" name="hobby" value="운동2">운동2
<input type="checkbox" name="hobby" value="운동3">운동3
<input type="checkbox" name="hobby" value="운동4">운동4 <br>
<input type="button" value="보내기" onclick="check()"> 
<!-- submit=form안에 있는 값들을 들고 액션한테 가라는 뜻. 그전에 검사하기-->
<!-- button=모양만 버튼. 아무 역할이 없음. 그래서 뒤에 onclick="check()"-->
<input type="reset" value="취소">
</form>
</body>
</html>
cs

 


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ 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>
<%
    request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="student" class="com.exam.StudentBean"/> 
<!-- jsp의 액션태그. StudentBean의 student객체를 만드는 것과 같음-->
<jsp:setProperty property="*" name="student"/>
<!-- id와 name을 동일하게. 데이터들이 연결되도록 -->
<%
    String[]h=student.getHobby();
    String strHobby="";
    for(int i=0;i<h.length;i++){
        strHobby+=h[i]+" ";
    }
%>
</head>
<body>
이름: <jsp:getProperty property="name" name="student"/>
<!-- student 객체의 name을 가져오기 -->
<hr>
이름: <%=student.getName() %> <br>
학번: <%=student.getStudentNum() %> <br>
성별: <%=student.getGender() %> <br>
전공: <%=student.getMajor() %> <br>
취미: <%=strHobby %>
</body>
</html>
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.exam;
 
public class StudentBean {
    private String name; //이름
    private String studentNum; //학번
    private String gender; //성별
    private String major; //전공
    private String[] hobby; //취미
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getStudentNum() {
        return studentNum;
    }
    public void setStudentNum(String studentNum) {
        this.studentNum = studentNum;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
    public String[] getHobby() {
        return hobby;
    }
    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }
}
cs

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<%@ 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>
<script>
    function test(){
        if(document.getElementById("name").value==""){
            alert("이름을 입력하세요");
            return;
        }
        if(document.getElementById("kor").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("국어성적을 입력하세요"); //isNaN: 문자인지 아닌지 판별
            return;
        }
        if(document.getElementById("eng").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("영어성적을 입력하세요");
            return;
        }
        if(document.getElementById("math").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("수학성적을 입력하세요");
            return;
        }
        document.getElementById("frm").submit();
    }
</script>
</head>
<body>
<form action="scoreResult3.jsp" id="frm">
이름: <input type="text" name="name" id="name"><br>
국어: <input type="text" name="kor" id="kor"><br>
영어: <input type="text" name="eng" id="eng"><br>
수학: <input type="text" name="math" id="math"><br>
<input type="button" value="전송" onclick="test()">
</form>
</body>
</html>
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%@page import="com.exam.ScoreBean3"%>
<%@ 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>
<%
    request.setCharacterEncoding("utf-8");
    String name=request.getParameter("name");
    int kor=Integer.parseInt(request.getParameter("kor"));
    int eng=Integer.parseInt(request.getParameter("eng"));
    int math=Integer.parseInt(request.getParameter("math"));
    ScoreBean3 sb=new ScoreBean3(name,kor,eng,math); //생성자를 이용하여 값 할당
    
%>
</head>
<body>
<!-- scoreResult3.jsp -->
scoreResult3.jsp<br>
이름: <%=sb.getName() %><br>
국어: <%=sb.getKor() %><br>
영어: <%=sb.getEng() %><br>
수학: <%=sb.getMath() %><br>
총점: <%=sb.getTot() %><br>
평균: <%=sb.getAvg() %><br>
학점: <%=sb.getGrade() %>
</body>
</html>
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.exam;
 
public class ScoreBean3 {
    private String name;
    private int kor;
    private int eng;
    private int math;
    
    //getter
    public String getName() {
        return name;
    }
    public int getKor() {
        return kor;
    }
    public int getEng() {
        return eng;
    }
    public int getMath() {
        return math;
    }
    
    //생성자 source-Generate Constructor using Fields...
    public ScoreBean3(String name, int kor, int eng, int math) {
        super();
        this.name = name;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
    public int getTot() {
        return (kor+eng+math);
    }
    public int getAvg() {
        return (kor+eng+math)/3;
    }
    public String getGrade() {
        String grade="";
        switch((kor+eng+math)/3/10) {
            case 10:
            case 9: grade="A학점"break;
            case 8: grade="B학점"break;
            case 7: grade="C학점"break;
            default: grade="F학점"break;
        }
        return grade;
    }
}
cs
  • score2.jsp/scoreResult2.jsp 두 JSP 파일과 ScoreBean 자바파일 만들기.

  • 생성자와 객체를 생성하고 메소드를 호출하기. 이름과 국영수 성적을 인터넷 페이지에 출력.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<%@ 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>
<script>
    function test(){
        if(document.getElementById("name").value==""){
            alert("이름을 입력하세요");
            return;
        }
        if(document.getElementById("kor").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("국어성적을 입력하세요"); //isNaN: 문자인지 아닌지 판별
            return;
        }
        if(document.getElementById("eng").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("영어성적을 입력하세요");
            return;
        }
        if(document.getElementById("math").value==""
                ||isNaN(document.getElementById("kor").value)){
            alert("수학성적을 입력하세요");
            return;
        }
        document.getElementById("frm").submit();
    }
</script>
</head>
<body>
<form action="scoreResult2.jsp" id="frm">
이름: <input type="text" name="name" id="name"><br>
국어: <input type="text" name="kor" id="kor"><br>
영어: <input type="text" name="eng" id="eng"><br>
수학: <input type="text" name="math" id="math"><br>
<input type="button" value="전송" onclick="test()">
</form>
</body>
</html>
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@page import="com.exam.ScoreBean"%>
<%@ 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>
<%
    request.setCharacterEncoding("utf-8");
    String name=request.getParameter("name");
    int kor=Integer.parseInt(request.getParameter("kor"));
    int eng=Integer.parseInt(request.getParameter("eng"));
    int math=Integer.parseInt(request.getParameter("math"));
    ScoreBean sb=new ScoreBean();
    sb.setName(name);
    sb.setKor(kor);
    sb.setEng(eng);
    sb.setMath(math);
%>
</head>
<body>
<!-- scoreResult2.jsp -->
scoreResult2.jsp
이름: <%=sb.getName() %><br>
국어: <%=sb.getKor() %><br>
영어: <%=sb.getEng() %><br>
수학: <%=sb.getMath() %><br>
총점: <%=sb.getTot() %><br>
평균: <%=sb.getAvg() %><br>
학점: <%=sb.getGrade() %>
</body>
</html>
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.exam;
 
public class ScoreBean {
    private String name;
    private int kor;
    private int eng;
    private int math;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getKor() {
        return kor;
    }
    public void setKor(int kor) {
        this.kor = kor;
    }
    public int getEng() {
        return eng;
    }
    public void setEng(int eng) {
        this.eng = eng;
    }
    public int getMath() {
        return math;
    }
    public void setMath(int math) {
        this.math = math;
    }
    
    public int getTot() {
        return (kor+eng+math);
    }
    public int getAvg() {
        return (kor+eng+math)/3;
    }
    public String getGrade() {
        String grade="";
        switch((kor+eng+math)/3/10) {
            case 10:
            case 9: grade="A학점"break;
            case 8: grade="B학점"break;
            case 7: grade="C학점"break;
            default: grade="F학점"break;
        }
        return grade;
    }
}
cs

 

  • 자바스크립트에서도 자바처럼 함수를 호출하여 인터넷 페이지에 출력할 수 있다.

  • dateExam.jsp, DateBean.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@page import="com.exam.DateBean"%>
<%@ 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>
<%
    DateBean bean=new DateBean();
%>
<%=bean.getToday()%>
<hr>
<%=bean.getDay() %>
</body>
</html>
cs

 


 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.exam;
import java.util.Calendar;
public class DateBean {
    Calendar ca=Calendar.getInstance();
    String[]arr= {"일","월","화","수","목","금","토"};
    
    public String getToday() {
        String str=ca.get(Calendar.YEAR)+"년";
        str+=ca.get(Calendar.MONDAY)+1+"월";
        str+=ca.get(Calendar.DATE)+"일";
        str+=arr[ca.get(Calendar.DAY_OF_WEEK)-1]+"요일";
        return str;
    }
    public String getDay() {
        StringBuilder sb=new StringBuilder(); //문자열이 계속 바뀌는 상황에선 StringBuilder가 유용(동적인 문자열)
        sb.append(ca.get(Calendar.YEAR)+"년");
        sb.append(ca.get(Calendar.MONDAY)+1+"월");
        sb.append(ca.get(Calendar.DATE)+"일");
        sb.append(arr[ca.get(Calendar.DAY_OF_WEEK)-1]+"요일");
        return sb.toString(); 
    }
}
 
 
cs

 

  • 캘린더 함수를 이용하여 오늘 날짜 출력하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<%@page import="java.util.Calendar"%>
<%@ 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>
<%
Calendar ca=Calendar.getInstance();
String[]arr={"일요일","월요일","화요일","수요일","목요일","금요일","토요일"};
String day="";
switch(ca.get(Calendar.DAY_OF_WEEK)){
    case 1: day="일요일"break
    case 2: day="월요일"break;
    case 3: day="화요일"break;
    case 4: day="수요일"break;
    case 5: day="목요일"break;
    case 6: day="금요일"break;
    case 7: day="토요일"break;
}
%>
<%!
public String getDay(int x){
    String str="";
    switch(x){
        case 1: str="일요일"break
        case 2: str="월요일"break;
        case 3: str="화요일"break;
        case 4: str="수요일"break;
        case 5: str="목요일"break;
        case 6: str="금요일"break;
        case 7: str="토요일"break;
    }
    return str;
}
%>
</head>
<body>
오늘은 <%=ca.get(Calendar.YEAR) %>
<%=ca.get(Calendar.MONTH)+1 %>
<%=ca.get(Calendar.DATE) %>
<%=day %>
<hr>
배열요일:
<%=arr[ca.get(Calendar.DAY_OF_WEEK)-1]%>
<hr>
함수요일: <%=getDay(ca.get(Calendar.DAY_OF_WEEK))%>
</body>
</html>
cs

 

+ Recent posts