[필기정리] Day69 - get, post 방식, insert, select 등

Web/JSP

2020. 10. 2. 18:58

# GET vs POST

  웹브라우저와 서버 간에 정보를 주고 받을 때 사용하는 전송방식

- get : url에 데이터가 표시됨, 정보 크기의 제한이 있음

- post : url에 데이터가 표시되지 않아 보안성이 좋음, 정보 크기의 제한이 없음

 

Q1. getTest.html에서 이름과 비밀번호를 입력받아 getTest.jsp에서 이름과 비밀번호를 출력하시오. (get방법)

A.

- getTest.html

<html>
<head>
<title>회원가입</title>
</head>
<body>
	<form method = "get" action="getTest.jsp">
    	<table border="1">
        	<caption>회원가입</caption> 
            	<tr>
                	<td>
                    <label for="name">이름</label>
                    </td>
                    <td>
                    <input type="text" name="name" id="name" required>
                    </td>
                </tr>
                
                <tr>
                	<td>
                    <label for="pw">비밀번호</label>
                    </td>
                	<td>
                    <input type="text" name="pw" id="pw" required>
                    </td>
                </tr>
                <tr>
                	<td colspan="2">
                    	<input type="submit" value="전송">
                        <input type="reset" value="초기화">
                    </td>
                </tr>
            </table>
        </form>
	</body>
</html>

- getTest.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>
      <%
      String name = request.getParameter("name");
      String pw = request.getParameter("pw");
      %>
      이름 : <%= name %>
      비밀번호 : <%= pw %>
    </body>
  </html>

 

Q2. getTest2.html에서 getTest2라는 링크를 클릭하면 getText2.jsp로 이동해서 이름과 비밀번호를 출력하시오.

      이름과 비밀번호는 url에 같이 보내시오.(get방법)

A.

- getTest2.html

<html>
<head>
<title>회원가입</title>
</head>
<body>
<a href="http://localhost:8080/getTest2.jsp?name=jhn&pw=1234">getTest2</a>	
</body>
</html>

- getTest2.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>
      <%
      String name = request.getParameter("name");
      String pw = request.getParameter("pw");
      %>
      이름 : <%= name %>
      비밀번호 : <%= pw %>
    </body>
  </html>

Q3. postTest.html에서 이름과 비밀번호를 입력받아 postTest.jsp에서 출력하시오. (post방법)

A.

- postTest.html

<html>
<head>
<title>회원가입</title>
</head>
<body>
	<form method = "post" action="postTest.jsp">
    	<table border="1">
        	<caption>회원가입</caption> 
            	<tr>
                	<td>
                    <label for="name">이름</label>
                    </td>
                    <td>
                    <input type="text" name="name" id="name" required>
                    </td>
                </tr>
                
                <tr>
                	<td>
                    <label for="pw">비밀번호</label>
                    </td>
                	<td>
                    <input type="text" name="pw" id="pw" required>
                    </td>
                </tr>
                <tr>
                	<td colspan="2">
                    	<input type="submit" value="전송">
                        <input type="reset" value="초기화">
                    </td>
                </tr>
            </table>
        </form>
	</body>
</html>

- postTest.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>
      <%
      String name = request.getParameter("name");
      String pw = request.getParameter("pw");
      %>
      이름 : <%= name %>
      비밀번호 : <%= pw %>
    </body>
  </html>

 

 

Q4. postTest2.html에서 이름을 입력받고, 숨김정보로 007이라는 값을 postTest2.jsp로 보내시오.

     그리고 이름과 숨김정보를 출력하시오.

A.

- postTest2.html

<html>
<head>
<title>회원가입</title>
</head>
<body>
	<form method = "post" action="postTest.jsp">
     	<input type="hidden" name="hidden" value="007">
    	<table border="1">
        	<caption>회원가입</caption> 
            	<tr>
                	<td>
                    <label for="name">이름</label>
                    </td>
                    <td>
                    <input type="text" name="name" id="name" required>
                    </td>
                </tr>
             
                <tr>
                	<td colspan="2">
                    	<input type="submit" value="전송">
                        <input type="reset" value="초기화">
                    </td>
                </tr>
            </table>
        </form>
	</body>
</html>

- postTest2.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>
      <%
      String name = request.getParameter("name");
      String hidden = request.getParameter("hidden");
      %>
      이름 : <%= name %>
      숨김 값 : <%= hidden %>
    </body>
  </html>

 

# insert

create table member(
num int auto_increment primary key,
name varchar(20),
id varchar(20),
pw varchar(20)
);

Q. Input.html에서 이름, 아이디, 비밀번호를 입력받아서 InputOK.jsp에서 저장을 하시오.

    저장이 성공적으로 이루어 졌으면 welcome.html로 이동하고 실패했으면 fail.html로 이동하시오.

A. Input.html

<html>
<head>
<title>회원가입</title>
</head>
<body>
	<form method = "post" action="inputOK.jsp">
    	<table border="1">
        	<caption>회원가입</caption> 
            	<tr>
                	<td>
                    <label for="name">이름</label>
                    </td>
                    <td>
                    <input type="text" name="name" id="name" required>
                    </td>
                </tr>
                
                <tr>
                	<td>
                    <label for="name">아이디</label>
                    </td>
                    <td>
                    <input type="text" name="id" id="id" required>
                    </td>
                </tr>
                
                <tr>
                	<td>
                    <label for="name">비밀번호</label>
                    </td>
                    <td>
                    <input type="text" name="pw" id="pw" required>
                    </td>
                </tr>
             
                <tr>
                	<td colspan="2">
                    	<input type="submit" value="전송">
                    </td>
                </tr>
            </table>
        </form>
	</body>
</html>

- inputOK.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/project?serverTimezone=UTC&characterEncoding=UTF-8";
String id = "root";
String pw = "1234";
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String sql = null;
ResultSet rs = null;

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    conn = DriverManager.getConnection(url, id, pw);
    System.out.println("Connection 객체 생성 성공");
    stmt = conn.createStatement();
    
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (SQLException e) {
	System.out.println("Connection 객체 생성 실패");
}

request.setCharacterEncoding("utf-8");
String name, id, pw = null;
int result = 0;
name = request.getParameter("name");
id = request.getParameter("id");
pw = request.getParameter("pw");
sql = "insert into member(name, id, pw) values(?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, id);
pstmt.setString(3, pw);
result = pstmt.executeUpdate();
if(result > 0) {
	response.sendRedirect("/coderbear/welcome.jsp");
} else {
	response.sendRedirect("/coderbear/fail.jsp");
}
%>
</body>
</html>

#select

Q. showMember.html에서 멤버보기 링크를 클릭하면 showMember.jsp에서 등록되어 있는 멤버를 보여주시오.

A.

- showMember.html

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title></title>
</head>
<body>
    <a href ="showMember.jsp">멤버보기</a> 
</body>
</html>

- showMember.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title></title>
</head>
<body>
	<table border="1">
		<caption>목록</caption>
		<tr>
			<td>번호</td>
			<td>이름</td>
			<td>아이디</td>
		</tr>
		<%
			sql = "select * from member";
			rs = stmt.executeQuery(sql);
			int no;
			String name, id = null;
			
			while(rs.next()) {
				no = rs.getInt("no");
				name = rs.getString("name");
				id = rs.getString("id");
		%>
			<tr>
				<td><%= no %></td>
				<td><%= name %></td>
				<td><%= id %></td>
			</tr>
		<%
			}
		%>
	</table>
</body>
</html>

 

ex) 게시판 만들기

Q. 아래와 같이 구현하시오.

 

 

 

 

A.

- dbconn.jsp

<%@page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/project?serverTimezone=UTC&characterEncoding=UTF-8";
String id = "root";
String pw = "1234";
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String sql = null;
ResultSet rs = null;

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    // 데이터베이스와 연결하는 드라이버 클래스를 찾아 로드한다.
    conn = DriverManager.getConnection(url, id, pw);
    // 연결을 관리하는 Connection 객체를 생성한다.
    System.out.println("Connection 객체 생성 성공");
    stmt = conn.createStatement();
    
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (SQLException e) {
	System.out.println("Connection 객체 생성 실패");
}
%>
</body>
</html>

- index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<html>
<head>
<title>회원가입</title>
</head>
<body>
	<table border="1">
		<caption>목록</caption>
		<tr>
			<td>번호</td>
			<td>제목</td>
			<td>작성자</td>
			<td>작성일</td>
			<td>조회 수</td>
		</tr>
		<%
			sql = "select * from board";
			rs = stmt.executeQuery(sql);
			int no, rCnt;
			String name, title, contents, wTime = null;
			
			while(rs.next()) {
				no = rs.getInt("no");
				name = rs.getString("name");
				title = rs.getString("title");
				contents = rs.getString("contents");
				wTime = rs.getString("wTime");
				rCnt = rs.getInt("rCnt");
		%>
			<tr>
				<td><%= no %></td>
				<td><a href="/haena/contents.jsp?no=<%= no %>"><%= title %></a></td>
				<td><%= name %></td>
				<td><%= wTime %></td>
				<td><%= rCnt %></td>	
			</tr>
		<%
			}
		%>
	</table>
	<a href="write.jsp">글쓰기</a>
</body>
</html>

- write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post" action="writeResult.jsp">
<table border="1">
	<caption>글쓰기</caption>
	<tr>
		<td>제목</td>
		<td><input type="text" name="title"></td>
	</tr>
	<tr>
		<td>이름</td>
		<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<td>비밀번호</td>
		<td><input type="password" name="password"></td>
	</tr>
	<tr>
		<td>E-mail</td>
		<td><input type="text" name="email"></td>
	</tr>
	<tr>
		<td colspan="2">
			<textarea name="contents" cols="40" rows="8"></textarea>
		</td>
	</tr>
	<tr>
		<td colspan="2">
		<input type="submit" value="등록">
		<a href="/Haena/index.jsp"><input type="button" value="목록"></a>
		</td>
	</tr>
</table>
</form>

</body>
</html>

- writeResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String title = request.getParameter("title");
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String contents = request.getParameter("contents");
sql = "INSERT INTO BOARD(title, name, password, email, contents) VALUES(?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, name);
pstmt.setString(3, password);
pstmt.setString(4, email);
pstmt.setString(5, contents);
int result = 0;
result = pstmt.executeUpdate();
if(result > 0) {
	System.out.println(result + " 데이터 삽입성공");
%>
<script type="text/javascript">
	alert("글쓰기가 완료되었습니다.");
</script>	
<%
response.sendRedirect("/Haena/index.jsp");
} else {
	System.out.println(result + " 데이터 삽입실패");
%>
<%
response.sendRedirect("/Haena/write.jsp");
}
%>
</body>
</html>

- contents.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
int no = Integer.parseInt(request.getParameter("no"));
sql = "select * from board where no="+no+"";
String sql2 = "update board set rCnt = rCnt+1 where no=? ";
PreparedStatement pstmt2 = conn.prepareStatement(sql2);
pstmt2.setInt(1, no);
int result2 = pstmt2.executeUpdate();
if(result2 > 0) {
	System.out.println("조회 수가 올라갔습니다.");
}
rs = stmt.executeQuery(sql);
%>
<table border="1">
<%
	while(rs.next()) {
		String title = rs.getString("title");
		String name = rs.getString("name");
		String contents = rs.getString("contents");
		String wTime = rs.getString("wTime");
%>
	<caption>내용보기</caption>
	<tr>
		<td>제목</td>
		<td><input type="text" name="title" value="<%= title %>" readOnly></td>
	</tr>
	<tr>
		<td>이름</td>
		<td><input type="text" name="name"  value="<%= name %>" readOnly></td>
	</tr>
	<tr>
		<td>작성일</td>
		<td><input type="text" name="wTime"  value="<%= wTime %>" readOnly></td>
	</tr>
	<tr>
		<td colspan="2">
			<textarea name="contents" cols="40" rows="8" readOnly><%= contents %></textarea>
		</td>
	</tr>
<%
	}
%>
</table>
<a href="/board2/index.jsp"><input type="button" value="목록"></a>
<a href="/board2/updatePwd.jsp?no=<%= no %>"><input type="button" value="수정"></a>
<a href="/board2/delete.jsp?no=<%= no %>"><input type="button" value="삭제"></a>
</body>
</html>

- updatePwd.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>
<%
request.setCharacterEncoding("utf-8");
System.out.println(request.getParameter("no"));
int no = Integer.parseInt(request.getParameter("no"));
%>
<form method="post" action="update.jsp">
	<input type="hidden" name="no" value="<%= no %>">
	<table>
		<tr>
			<td>
			비밀번호
			</td>
			<td>
				<input type="password" name="password">
			</td>
		</tr>
		<tr>
			<td><input type="submit" value="확인"></td>
		</tr>
	</table>
</form>
</body>
</html>

- update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("no"));
String password = request.getParameter("password");
sql = "select * from board where no="+no+"";
rs = stmt.executeQuery(sql);
while(rs.next()) {
	if(!password.equals(rs.getString("password"))) {
		System.out.println(password);
		System.out.println(rs.getString("password"));
%>
	<div>
		비밀번호가 다릅니다.
		<a href="/Haena/index.jsp">목록</a>
	</div>	
<%
	} else {
		String title = rs.getString("title");
		String name = rs.getString("name");
		String contents = rs.getString("contents");
		String wTime = rs.getString("wTime");
%>
<form method="post" action="updateResult.jsp">
<input type="hidden" name="no" value="<%= no %>">
<table border="1">
<caption>내용보기</caption>
	<tr>
		<td>제목</td>
		<td><input type="text" name="title" value="<%= title %>"></td>
	</tr>
	<tr>
		<td>이름</td>
		<td><input type="text" name="name"  value="<%= name %>"></td>
	</tr>
	<tr>
		<td>작성일</td>
		<td><input type="text" name="wTime"  value="<%= wTime %>" readOnly></td>
	</tr>
	<tr>
		<td colspan="2">
			<textarea name="contents" cols="40" rows="8"><%= contents %></textarea>
		</td>
	</tr>
	<tr>
	<td colspan="2">
	<input type="submit" value="등록">
	<a href="/Haena/index.jsp"><input type="button" value="목록"></a>
	</td>
</tr>
</table>
</form>
<%
		}
	}
%>

</body>
</html>

- updateResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("no"));
String title = request.getParameter("title");
String name = request.getParameter("name");
String contents = request.getParameter("contents");
sql = "UPDATE BOARD SET title=?, name=?, contents=?, wTime=now() WHERE no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, name);
pstmt.setString(3, contents);
pstmt.setInt(4, no);

int result = 0;
result = pstmt.executeUpdate();
if(result > 0) {
	System.out.println(result + " 데이터 수정성공");
%>
<script type="text/javascript">
	alert("글이 수정되었습니다.");
</script>	
<%
response.sendRedirect("/Haena/index.jsp");
} else {
	System.out.println(result + " 데이터 수정실패");
%>
<%
response.sendRedirect("/Haena/update.jsp");
}
%>
</body>
</html>

- delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="dbconn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("no"));
sql = "DELETE FROM BOARD WHERE no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);

int result = 0;
result = pstmt.executeUpdate();
if(result > 0) {
	System.out.println(result + " 데이터 삭제성공");
	response.sendRedirect("/Haena/index.jsp");
} else {
	System.out.println(result + " 데이터 삭제실패");
	response.sendRedirect("/Haena/index.jsp");
}
%>
</body>
</html>
728x90