[JAVA_Back-End]

[JSP] Eclipse + Tomcat으로 웹프로그래밍 본문

Programming/JSP

[JSP] Eclipse + Tomcat으로 웹프로그래밍

너굴위 2023. 9. 26. 17:11
728x90
반응형

Java를 사용한 웹 프로그램

- Servlet   - class

- JSP     -html문서

 

서비스환경

Linux(Unix) + JDK + WAS(Apache-Tomcat)

=> AWS

=> 배포(deployment)

개발환경

Window - JDK +WAS(Apache -Tomcat) + IDE

IDE - WAS 환경 구성

 

Visual Studio Code 

Eclipse

Intellij

*WAS(Web Application Server)

=> 웹 프로그램 해석 서버

     해석 => html, css, js

jsp - Apache-Tomcat,Resion, Jetty...

 

1. JDK

2. WAS

3. IDE

4. Database

 

eclipse 통해서 개발환경을 설정

1. 환경설정 - html / css / jsp 파일의 인코딩 설정 = utf-8

2. server - was

3. window - web browser -> 디폴트 설정

 

eclipse 프로젝트 설정

퍼스펙스티 - j2ee

프로젝트 - Dynamic Web Project

프로젝트명 = URL명

 

webapp이하에 jsp파일 넣기

주의할 점 

- 확장자를 jsp로 놓는다.

 

 

각 폴더의 이름에 따라 경로가 달라질 수 있다.

 

 

 

 

jsp(Java Server Pages)

구성요소

HTML / CSS / JS

디렉티브

            <%@ page          - 페이지에 대한 환경설정

            <%@ page import =""            - import구문이 나옴 (java api 사용 가능)

 

스크립트

     scriptlet

                 <%       - java 소스 (메서드 내부)

                 출력 구문

                 System.out.println()  - 디버깅(콘솔)

                 out.println()  - 화면구성

 

expression 

                <%=

                <% out.println()

declaration

                <%!     - 메서드 선언

 

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

pageEncoding="UTF-8"%>

 

scriptlet 사용할 수 있는 기본 객체(인스턴스화 필요 없음)

 

<% request.setCaracterEncoding("utf-8");

%>

 

 

 

구구단 

캘린더

 

jsp파일 안에서

html -> body 안쪽에 <% %> 상태로 java 구문 넣기

 

표 입력 => 동일하게 body -> <% %>안에 입력할 수 있도록 하기


js01.jsp - data의 예외처리
<%@ 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>
<script type="text/javascript">
//필수 입력항목 검사
//정적 이벤트
const checkfrm1=function(){
//alert('click');
if(document.frm.data.value == ''){
alert('data1를 입력하셔야 합니다.');
return;
}
document.frm.submit();
};


//동적 이벤트
window.onload = function(){
document.getElementById('btn').onclick=function(){
if(document.frm.data.value == ''){
alert('data2를 입력하셔야 합니다.');
return;
}

document.frm.submit();
};
};

</script>
<body>


<form action="./js01_ok.jsp" method="get" name ="frm">
데이터 <input type="text" name = "data"/>
<input type="submit" value="전송">
<input type="button" value="전송" onclick="checkfrm1()"> <!-- 전송버튼에 함수를 부여 -->
<input type="button" id="btn" value="전송"> <!-- id를 주어서 동적 이벤트를 부여한다 -->
</form>




</body>
</html>

예외처리 결과

 

 

form.jsp  - 입력과 체크박스 폼 만들기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>




<form action="./viewParameter.jsp" method ="post"> <!-- 어느파일로 어떤 데이터를 보낼 것인지에 대한 정의 -->
이름: <input type="text" name="name" size="10"> <br>
주소: <input type="text" name="address" size="30"> <br>
좋아하는 동물:
<input type="checkbox" name="pet" value="dog">강아지
<input type="checkbox" name="pet" value="cat">고양이
<input type="checkbox" name="pet" value="pig">돼지


<br>
<input type="submit" value="전송">
</form>
</body>
</html>
viewParameter.jsp - 입력폼에 대한 결과값을 메서드와 함께 출력하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>


<%@ page import="java.util.Enumeration" %>
<%@ page import="java.util.Map" %>


<%
request.setCharacterEncoding("utf-8");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>요청 파라미터 출력</title>
</head>
<body>
<b>request.getParameter() 메서드 사용</b> <br>
name 파라미터 =<%=request.getParameter("name")%> <br>
address 파라미터 =<%=request.getParameter("address") %>
<p>
<b>request.getParameterValues() 메서드 사용</b> <br>
<%
String[] values = request.getParameterValues("pet");
if(values!=null){
for(int i=0;i<values.length;i++){
%>
<%= values[i] %>
<%
}
}
%>
<p>
<b>request.getParameterNames()메서드 사용</b> <br>
<% Enumeration paramEnum = request.getParameterNames();
while(paramEnum.hasMoreElements()){
String name = (String)paramEnum.nextElement();%>
<%= name %>
<%
}
%>
<p>
<b>request.getParameterMap()메서드 사용</b><br>
<%
Map parameterMap=request.getParameterMap();
String[] nameParam =(String[])parameterMap.get("name");
if(nameParam !=null){
%>
name = <%= nameParam[0] %>
<%
}


%>
</body>
</html>

입력 폼 결과화면
입력한 폼에 대한 결과

calendar.jsp - 입력폼과 표를 제작하여 캘린더 만들기
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String strCalendar = "";
if(request.getParameter("year")!=null && request.getParameter("month")!=null){
request.setCharacterEncoding("utf-8");
int year = Integer.parseInt(request.getParameter("year"));
int month = Integer.parseInt(request.getParameter("month"));
//System.out.println(year + " " + month);

Date startCalendar = new Date( year, month-1, 1);
Date endCalendar = new Date( year, month, 1-1);
//Date todayCalendar = new Date();

int startDayOfWeek = startCalendar.getDay();
int endDate = endCalendar.getDate();
int endDayOfWeek = endCalendar.getDay();
//int today = todayCalendar.getDate();

strCalendar = "<table border='1 solid black' width='350' cellspacing='0' style='text-align:center;'>";
// 달력에 년 월 추가
strCalendar += String.format("<tr><td colspan='7'><b>%d년 %d월</b></td></tr>",year, month);

String[] arrDay = {"일", "월", "화", "수", "목", "금", "토"};
strCalendar += "<tr>";

// 달력에 요일 추가
for(int i=0; i<7; i++){
if(i==0){
strCalendar += String.format("<td style='color:red'>%s</td>",arrDay[i]);
} else {
strCalendar += String.format("<td>%s</td>",arrDay[i]);
}
}
strCalendar += "</tr>";
strCalendar += "<tr>";

// 달력 앞 공백 추가
for( int i=1; i<startDayOfWeek ; i++){
strCalendar += "<td></td>";
}

// 달력 내용 추가
for( int i=1, n=startDayOfWeek ; i<=endDate ; i++, n++){
// 달력 태그 추가 , 일요일 red
if( n%7 == 1){
strCalendar += "<td style='color:red'>";
} else {
strCalendar += "<td>";
}
strCalendar += "" + i + "</td>";
// 오늘 bold
/*if( today == i ){
strCalendar += "<b>" + i + "</b></td>";
} else {
strCalendar += "" + i + "</td>";
}*/
// 달력 행 가르기
if( n%7 == 0 ){
strCalendar += "</tr>";
if(i!=endDate){
strCalendar += "<tr>";
}
}
}
// 달력 뒷 공백 추가


//System.out.println(endDate);
for(int i=endDayOfWeek; i<7; i++){
strCalendar += "<td></td>";
}
strCalendar += "</tr></table>";
}




%>




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">


window.onload = function() {
document.getElementById('btn').onclick = function() {
//alert('click');
if(document.frm.year.value.trim() == '') {
alert('년도를 입력해 주셔야 합니다.');
return;
} else{
let year = parseInt(document.frm.year.value.trim());
if(year <= 2021 || year>=2024) {
alert('년도를 정확하게 입력하셔야 합니다.');
return;
}
}
if (document.frm.month.value.trim() == '') {
alert('월을 입력해 주셔야 합니다.');
return;
} else {
let month = parseInt(document.frm.month.value.trim());
if(month <=0 || month>12) {
alert('월을 정확하게 입력하셔야 합니다.');
return;
}
}
document.frm.submit();
}
}




</script>



<body>
<form action="./calendar.jsp" method="get" name="frm">
<input type="text" name="year">년도
<input type="text" name="month">
<input type="submit" id="btn" value="확인">
</form>


<form action="./calendar.jsp">
<select name="year">
<option value="2022">2022년</option>
<option value="2023">2023년</option>
<option value="2024">2024년</option>
</select>
<select name="month">
<option value="1">1월</option>
<option value="2">2월</option>
<option value="3">3월</option>
<option value="4">4월</option>
<option value="5">5월</option>
<option value="6">6월</option>
<option value="7">7월</option>
<option value="8">8월</option>
<option value="9">9월</option>
<option value="10">10월</option>
<option value="11">11월</option>
<option value="12">12월</option>
</select>
<input type="submit" value="확인2">
</form>
<%=strCalendar %>
</body>
</html>

 

캘린더 결과

 

 


JDBC삽입 위치

jdbc01.jsp - DB연결하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


<%


String url = "jdbc:mariadb://localhost:3306/sample"; //드라이버 로딩
String user = "root";
String password = "!123456";


Connection conn = null;

try{
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
System.out.println("연결성공");
} catch(ClassNotFoundException e){
System.out.println("에러"+e.getMessage());
}catch(SQLException e){
System.out.println("에러"+e.getMessage());
}finally{
conn.close();
}


%>




</body>
</html>

 

콘솔에서 연결성공 확인

 

 

 

jdbc03.jsp - 부서테이블에서 부서번호, 부서이름, 지역 불러오기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.PreparedStatement" %>
<%


String url = "jdbc:mariadb://localhost:3306/sample"; //드라이버 로딩
String user = "root";
String password = "!123456";


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




StringBuilder sbHtml = new StringBuilder();


try{
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
System.out.println("연결성공");


String sql ="select * from dept";
pstmt = conn.prepareStatement(sql);


rs = pstmt.executeQuery();
out.println("<table width='300' border='1'");
while(rs.next()){
//System.out.println(rs.getString("deptno"));
sbHtml.append("<tr>");
sbHtml.append("<td>"+rs.getString("deptno")+"</td>");
sbHtml.append("<td>"+rs.getString("dname")+"</td>");
sbHtml.append("<td>"+rs.getString("loc")+"</td>");
sbHtml.append("</tr>");
}




} catch(ClassNotFoundException e){
System.out.println("에러"+e.getMessage());
}catch(SQLException e){
System.out.println("에러"+e.getMessage());
}finally{
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
}




%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml.toString() %> <!-- 위쪽에 java구문 올리고 body에는 적용하는 형식으로 만들기 -->




</body>
</html>

select 결과

 

 

 

dept.jsp - 부서번호 부서이름 부서위치를 insert 하고 update할 수 있는 폼
<%@ 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 type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick=function(){
//검사 구문
document.frm.submit();


};


document.getElementById('btn2').onclick=function(){
//검사 구문
document.frm2.submit();


};
};


</script>
</head>
<body>
<!-- dept.jsp (사용자 입력) -> dept_ok.jsp(데이터베이스 입력) -->


<form action="./dept_ok.jsp" method="post" name="frm">
부서번호<input type="text" name="deptno"/><br />
부서이름<input type="text" name="dname"/><br />
부서위치<input type="text" name="loc"/><br />
<input type="button" id="btn" value="내용 입력"/><br />
</form>


<!-- 부서번호 중심으로 부서이름, 부서위치 수정 -->
<form action="./dept_update_ok.jsp" method="post" name="frm2">
부서번호<input type="text" name="deptno2"/><br />
부서이름<input type="text" name="dname2"/><br />
부서위치<input type="text" name="loc2"/><br />
<input type="button" id="btn2" value="내용 입력2"/><br />


</form>




</body>
</html>
dept_ok.jsp - 내용 입력 누르면 데이터가 DB에 insert 될 수 있도록 함
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>


<!-- dept_ok.jsp -->
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.PreparedStatement" %>


<%
request.setCharacterEncoding("utf-8");


String deptno = request.getParameter("deptno");
String dname = request.getParameter("dname");
String loc = request.getParameter("loc");

//System.out.println(deptno);
//System.out.println(dname);
//System.out.println(loc);

String url = "jdbc:mariadb://localhost:3306/sample"; //드라이버 로딩
String user = "root";
String password = "!123456";

Connection conn = null;
PreparedStatement pstmt=null;

try{
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "insert into dept2 values(?,?,?)";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, deptno);
pstmt.setString(2, dname);
pstmt.setString(3, loc);

int result = pstmt.executeUpdate();

out.println("입력 성공: "+result);

}catch(ClassNotFoundException e){
System.out.println("에러"+e.getMessage());
}catch(SQLException e){
System.out.println("에러"+e.getMessage());
}finally{
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
}


%>
dept_update_ok.jsp - 내용 입력2 누르면 부서 번호에 대한 부서이름과 부서위치가 변경될 수 있도록 함
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>


<!-- dept_ok.jsp -->
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.PreparedStatement" %>


<%
request.setCharacterEncoding("utf-8");


String deptno = request.getParameter("deptno2");
String dname = request.getParameter("dname2");
String loc = request.getParameter("loc2");


//System.out.println(deptno);
//System.out.println(dname);
//System.out.println(loc);


String url = "jdbc:mariadb://localhost:3306/sample"; //드라이버 로딩
String user = "root";
String password = "!123456";


Connection conn = null;
PreparedStatement pstmt=null;


try{
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "update dept2 set dname=?, loc=? where deptno=?"; //부서 번호에 대한 정보 변경
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, dname);
pstmt.setString(2, loc);
pstmt.setString(3, deptno);


int result = pstmt.executeUpdate();


out.println("수정 성공: "+result);


}catch(ClassNotFoundException e){
System.out.println("에러"+e.getMessage());
}catch(SQLException e){
System.out.println("에러"+e.getMessage());
}finally{
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
}




%>

내용입력버튼과 내용입력2버튼을 통해 insert / update한 결과

 

 

dept_list.jsp - 데이터 삽입 / 데이터 삭제할 수 있는 폼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>


<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>


<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>


<%@ page import="java.sql.SQLException" %>


<%
String url = "jdbc:mariadb://localhost:3306/sample";
String user = "root";
String password = "!123456";


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


StringBuilder sbHtml = new StringBuilder();
try {
Class.forName( "org.mariadb.jdbc.Driver" );

conn = DriverManager.getConnection(url, user, password);
System.out.println( "연결 성공" );

String sql = "select * from dept2";
pstmt = conn.prepareStatement( sql );

rs = pstmt.executeQuery();

sbHtml.append( "<table width='600' border='1'>" );
while( rs.next() ) {
sbHtml.append( "<tr>" );
sbHtml.append( "<td>" + rs.getString( "deptno" ) + "</td>" );
sbHtml.append( "<td>" + rs.getString( "dname" ) + "</td>" );
sbHtml.append( "<td>" + rs.getString( "loc" ) + "</td>" );
sbHtml.append( "</tr>" );
}
sbHtml.append( "</table>" );

} catch( ClassNotFoundException e ) {
System.out.println( "[에러] " + e.getMessage() );
} catch( SQLException e ) {
System.out.println( "[에러] " + e.getMessage() );
} finally {
if( rs != null ) rs.close();
if( pstmt != null ) pstmt.close();
if( conn != null ) conn.close();
}
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'btn' ).onclick = function() {
location.href = './dept_insert.jsp';
};



document.getElementById('btn2').onclick= function(){
//검사 구문
document.dfrm.submit();

};
};
</script>
</head>
<body>


<%=sbHtml.toString() %>
<br />
<input type="button" id="btn" value="내용 입력" />




<form action="./dept_delete_ok.jsp" method="post" name="dfrm">
부서번호<input type="text" name="deptno"/><br />
<input type="button" id="btn2" value="내용 삭제" />
</form>


</body>
</html>
dept_insert.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 type="text/javascript">
window.onload = function() {
document.getElementById( 'btn' ).onclick = function() {
document.frm.submit();
};
};
</script>
</head>
<body>


<form action="./dept_insert_ok.jsp" method="post" name="frm">
부서번호 <input type="text" name="deptno" /><br />
부서이름 <input type="text" name="dname" /><br />
부서위치 <input type="text" name="loc" /><br /><br />
<input type="button" id="btn" value="내용 입력" />
</form>


</body>
</html>
dept_insert_ok.jsp - 내용입력을 누르면 데이터가 삽입되도록 함
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- dept_ok.jsp -->


<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.SQLException" %>


<%
request.setCharacterEncoding( "utf-8" );


String deptno = request.getParameter( "deptno" );
String dname = request.getParameter( "dname" );
String loc = request.getParameter( "loc" );

String url = "jdbc:mariadb://localhost:3306/sample";
String user = "root";
String password = "!123456";

Connection conn = null;
PreparedStatement pstmt = null;


int flag = 1;

try {
Class.forName( "org.mariadb.jdbc.Driver" );
conn = DriverManager.getConnection( url, user, password );

String sql = "insert into dept2 values ( ?, ?, ? )";
pstmt = conn.prepareStatement( sql );
pstmt.setString( 1, deptno );
pstmt.setString( 2, dname );
pstmt.setString( 3, loc );

int result = pstmt.executeUpdate();


flag = 0;

} catch( ClassNotFoundException e ) {
System.out.println( "[에러] " + e.getMessage() );
} catch( SQLException e) {
System.out.println( "[에러] " + e.getMessage() );
} finally {
if( pstmt != null ) pstmt.close();
if( conn != null ) conn.close();
}


out.println( "<script type='text/javascript'>" );
if( flag == 0 ) {
// 정상
out.println( "alert( '정상 입력' );" );
out.println( "location.href='./dept_list.jsp';" );
} else if( flag == 1 ) {
// 에러
out.println( "alert( '에러' );" );
out.println( "history.back();" );
}
out.println( "</script>" );
%>
dept_delete_ok.jsp - 내용삭제를 누르면 삭제될 수 있도록 하는 기능
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- dept_ok.jsp -->


<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.SQLException" %>


<%
request.setCharacterEncoding( "utf-8" );


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


String url = "jdbc:mariadb://localhost:3306/sample";
String user = "root";
String password = "!123456";

Connection conn = null;
PreparedStatement pstmt = null;


int flag = 1;

try {
Class.forName( "org.mariadb.jdbc.Driver" );
conn = DriverManager.getConnection( url, user, password );

String sql = "delete from dept2 where deptno=?";
pstmt = conn.prepareStatement( sql );
pstmt.setString( 1, deptno );


int result = pstmt.executeUpdate();


flag = 0;

} catch( ClassNotFoundException e ) {
System.out.println( "[에러] " + e.getMessage() );
} catch( SQLException e) {
System.out.println( "[에러] " + e.getMessage() );
} finally {
if( pstmt != null ) pstmt.close();
if( conn != null ) conn.close();
}


out.println( "<script type='text/javascript'>" );
if( flag == 0 ) {
// 정상
out.println( "alert( '정상 입력' );" );
out.println( "location.href='./dept_list.jsp';" );
} else if( flag == 1 ) {
// 에러
out.println( "alert( '에러' );" );
out.println( "history.back();" );
}
out.println( "</script>" );
%>

 


context.xml - DB연결을위한 xml파일
<?xml version="1.0" encoding="utf-8" ?>
<Context>

<Resource
name ="jdbc/mariadb1"
auth="Container"
type="javax.sql.DataSource"
driverClassName ="org.mariadb.jdbc.Driver"
url="jdbc:mariadb://localhost:3306/sample"
username="root"
password="!123456"/> <!-- 톰캣이 데이터베이스에 대한 상황을 알고 있음 -->


</Context>

 

jdbc01.jsp  - 커넥션 풀 방식으로 DB연결하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>


<%@ page import="javax.sql.DataSource" %>


<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>




<%
Connection conn=null;

try{
Context initCtx = new InitialContext();
Context envCtx =(Context)initCtx.lookup("java:comp/env");
DataSource dataSource = (DataSource)envCtx.lookup("jdbc/mariadb1");

conn = dataSource.getConnection();

System.out.println("연결 성공");

}catch(NamingException e){
System.out.println( "[에러] " + e.getMessage() );
}catch(SQLException e){
System.out.println( "[에러] " + e.getMessage() );
}finally{
if(conn!=null)conn.close();
}


%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


</body>
</html>

결과

 

jdbc02.jsp - 커넥션 풀로 부서정보를 출력하는 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>


<%@ page import="javax.sql.DataSource" %>




<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>


<%
Connection conn=null;
PreparedStatement pstmt =null;
ResultSet rs = null;


try{
Context initCtx = new InitialContext();
Context envCtx =(Context)initCtx.lookup("java:comp/env");
DataSource dataSource = (DataSource)envCtx.lookup("jdbc/mariadb1");

String sql ="select * from dept";
conn = dataSource.getConnection();
pstmt =conn.prepareStatement(sql);
rs =pstmt.executeQuery();

//System.out.println("연결 성공");
while(rs.next()){
//System.out.println(rs.getString("deptno"));
System.out.println(rs.getString("deptno"));

}

}catch(NamingException e){
System.out.println( "[에러] " + e.getMessage() );
}catch(SQLException e){
System.out.println( "[에러] " + e.getMessage() );
}finally{
if(conn!=null)conn.close();
}


%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


</body>
</html>

 

 


zipcode01.jsp - 커넥션 풀을 사용하여 우편번호 출력하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>


<%@ page import="javax.sql.DataSource" %>




<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>

<%

request.setCharacterEncoding("utf-8");
StringBuilder sbHtml = new StringBuilder();

if(request.getParameter( "strdong" ) != null ) {
String dong=request.getParameter("strdong");



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


try{
Context initCtx = new InitialContext();
Context envCtx =(Context)initCtx.lookup("java:comp/env");
DataSource dataSource = (DataSource)envCtx.lookup("jdbc/mariadb2");


conn = dataSource.getConnection();

String sql ="select zipcode, sido, dong, ri, bunji from zipcode where dong like ?";
pstmt =conn.prepareStatement(sql);
pstmt.setString(1,dong+"%");
rs =pstmt.executeQuery();

//System.out.println("연결 성공");
while(rs.next()){
//System.out.println(rs.getString("deptno"));
sbHtml.append("<tr>");
sbHtml.append("<td>"+rs.getString("zipcode")+"</td>");
sbHtml.append("<td>"+rs.getString("sido")+"</td>");
sbHtml.append("<td>"+rs.getString("dong")+"</td>");
sbHtml.append("<td>"+rs.getString("ri")+"</td>");
sbHtml.append("<td>"+rs.getString("bunji")+"</td>");
sbHtml.append("</tr>");

}
out.println("</table>");
}catch(NamingException e){
System.out.println( "[에러] " + e.getMessage() );
}catch(SQLException e){
System.out.println( "[에러] " + e.getMessage() );
}finally{
if( rs != null ) rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
}
}
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">


window.onload = function() {


document.getElementById('btn').onclick= function(){
//검사 구문
document.dongfrm.submit();


};
};

</script>
</head>
<body>


<form action="./zipcode01.jsp" method="post" name ="dongfrm">
동이름<input type="text" name="strdong"/>
<input type="button" id="btn" value="동이름 검색"/>
</form>


<br /><br />
<table width="800" border="1">
<tr>
<td>우편번호</td><td>시도</td><td></td><td></td><td>번지</td>
</tr>
<%=sbHtml.toString() %>
</table>
</body>
</html>

 

결과


[만들어진 HTML을 사용하여 데이터 조작/연결하기]

 


디자인 -> DB설계
디자인 시간 
-html
- 데이터베이스 구성
테이블 구성
<논리적모델링>
번호              seq    int      not null     (primary key auto_increment)
제목              subject       varchar(150)     not null
글쓴이          writer          varchar(12)       not null
조회 수         hit                int         not null
비밀번호       password     varchar(12)     not null
내용              content        varchar(2000)
이메일           mail            varchar(50)

IP                  wip                varchar(15)       not null

등록일           wdate        datetime             not null


table명 : board1

create table board1 (

seq int primary key auto_increment,

subject varchar(150) not null,

writer varchar(12) not null,

hit    int    not null,

password varchar(12) not null,

content varchar(2000),

mail varchar(50),

wip varchar(15) not null,

wdate datetime not null

);

데이터베이스명:board

사용자명: board

비밀번호:123456


- 프로그램 구성

사용자 추가 후 로그인 -> 테이블 추가
test 데이터 삽입


문제..

- calendar에서 한 화면에 캘린더 내용이 나오지 않음(예외처리 따로/ 캘린더 따로)

  => 추가공부 필요해보임

calendar.jsp - 한 화면에 캘린더 내용이 나오지만 예외처리가 확실하게 되지는 않음 (이상한 년도나 달을 입력했을 때 경고메세지는 나오게 만들었음)
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String strCalendar = "";
if(request.getParameter("year")!=null && request.getParameter("month")!=null){
request.setCharacterEncoding("utf-8");
int year = Integer.parseInt(request.getParameter("year"));
int month = Integer.parseInt(request.getParameter("month"));
//System.out.println(year + " " + month);

Date startCalendar = new Date( year, month-1, 1);
Date endCalendar = new Date( year, month, 1-1);
//Date todayCalendar = new Date();

int startDayOfWeek = startCalendar.getDay();
int endDate = endCalendar.getDate();
int endDayOfWeek = endCalendar.getDay();
//int today = todayCalendar.getDate();

strCalendar = "<table border='1 solid black' width='350' cellspacing='0' style='text-align:center;'>";
// 달력에 년 월 추가
strCalendar += String.format("<tr><td colspan='7'><b>%d년 %d월</b></td></tr>",year, month);

String[] arrDay = {"일", "월", "화", "수", "목", "금", "토"};
strCalendar += "<tr>";

// 달력에 요일 추가
for(int i=0; i<7; i++){
if(i==0){
strCalendar += String.format("<td style='color:red'>%s</td>",arrDay[i]);
} else {
strCalendar += String.format("<td>%s</td>",arrDay[i]);
}
}
strCalendar += "</tr>";
strCalendar += "<tr>";

// 달력 앞 공백 추가
for( int i=1; i<startDayOfWeek ; i++){
strCalendar += "<td></td>";
}

// 달력 내용 추가
for( int i=1, n=startDayOfWeek ; i<=endDate ; i++, n++){
// 달력 태그 추가 , 일요일 red
if( n%7 == 1){
strCalendar += "<td style='color:red'>";
} else {
strCalendar += "<td>";
}
strCalendar += "" + i + "</td>";
// 오늘 bold
/*if( today == i ){
strCalendar += "<b>" + i + "</b></td>";
} else {
strCalendar += "" + i + "</td>";
}*/
// 달력 행 가르기
if( n%7 == 0 ){
strCalendar += "</tr>";
if(i!=endDate){
strCalendar += "<tr>";
}
}
}
// 달력 뒷 공백 추가


//System.out.println(endDate);
for(int i=endDayOfWeek; i<7; i++){
strCalendar += "<td></td>";
}
strCalendar += "</tr></table>";
}




%>




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">


window.onload = function() {
document.getElementById('btn').onclick = function() {
//alert('click');
if(document.frm.year.value.trim() == '') {
alert('년도를 입력해 주셔야 합니다.');
return;
} else{
let year = parseInt(document.frm.year.value.trim());
if(year <= 2021 || year>=2024) {
alert('년도를 정확하게 입력하셔야 합니다.');
return;
}
}
if (document.frm.month.value.trim() == '') {
alert('월을 입력해 주셔야 합니다.');
return;
} else {
let month = parseInt(document.frm.month.value.trim());
if(month <=0 || month>12) {
alert('월을 정확하게 입력하셔야 합니다.');
return;
}
}
document.frm.submit();
}
}


</script>








<body>
<form action="./calendar.jsp" method="get" name="frm">
<input type="text" name="year">년도
<input type="text" name="month">
<input type="submit" id="btn" value="확인">
</form>


<form action="./calendar.jsp">
<select name="year">
<option value="2022">2022년</option>
<option value="2023">2023년</option>
<option value="2024">2024년</option>
</select>
<select name="month">
<option value="1">1월</option>
<option value="2">2월</option>
<option value="3">3월</option>
<option value="4">4월</option>
<option value="5">5월</option>
<option value="6">6월</option>
<option value="7">7월</option>
<option value="8">8월</option>
<option value="9">9월</option>
<option value="10">10월</option>
<option value="11">11월</option>
<option value="12">12월</option>
</select>
<input type="submit" value="확인2">
</form>
<%=strCalendar %>
</body>
</html>

 

728x90
반응형