본문 바로가기
Kosta DevOps 과정 280기/Java

jsp

by 롯슈83 2024. 7. 12.

jsp 에서 java 문법을 사용할 수 있게 해주는 스크립트릿

  • <%     %>  : 온갖 자바 문법을 쓸 수 있다.
    • 열고 닫고 하는 것이 번거로울 수 있다.
  • out 내장객체를 이용해서 HTML 을 출력할 수도 있다. 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>도서등록</h2>
    <hr>
    <form action="InsertBookOK.jsp" method="post">
        도서번호 : <input type="text" name = "bookid"><br>
        도서이름 : <input type="text" name = "bookname"><br>
        도서가격 : <input type="text" name = "price"><br>
        출판사명 : <input type="text" name = "publisher"><br>
        <input type="submit" value="등록">
        <input type="reset" value="취소">
    </form>
</body>
</html>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ 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>
	<% 
		//새로운 도서 등록을 위하여 사용자가 입력한 도서의 정보(도서번호, 도서명, 가격, 출판사)는
		//jsp 내장 객체인 request 에 실려서 온다.
		
		//사용자가 요청한 문자 은 한글임을 설정
		request.setCharacterEncoding("UTF-8");
		
		//사용자가 입력한 도서번호, 도서명, 가격, 출판사를 받아와서 변수에 저장
		int bookid = Integer.parseInt(request.getParameter("bookid"));
		String bookname = request.getParameter("bookname");
		int price = Integer.parseInt(request.getParameter("price"));
		String publisher = request.getParameter("publisher");
		
		//DB연결하여 실행 시킬 DB 명령어 sql 을 만든다.
		String sql = "insert into book values(?,?,?,?)";
		
		//데이터베이스 연결에 필요한 변수들을 만든다.
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		int re = 0;
		try{
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, bookid);
			pstmt.setString(2, bookname);
			pstmt.setInt(3, price);
			pstmt.setString(4, publisher);
			re = pstmt.executeUpdate();
			
			conn.close();
			pstmt.close();
		}catch(Exception e){
			out.println(e);	//out 내장객체 사용 가능
		}
		if(re >= 1){
			%>
			<h2>도서등록 성공</h2>
			<%
		}else{
			%>
			<h2>도서등록 실패</h2>
			<%
		}
	%>
</body>
</html>

 

servlet 내장 객체 : jsp 에도 사용 가능

  • response
  • request
  • out : 출력을 위한 객체 

연습2

  • 새로운 부서 등록을 위한 웹 문서들을 서블릿으로 만들고 결과를 확인한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="http://localhost:8088/day0712_a/InsertDept">이동</a>
</body>
</html>
package com.kosta.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class InsertDept
 */
@WebServlet("/InsertDept")
public class InsertDept extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String htmlTxt = "<form action='InsertDeptOK' method='post'>\r\n"
				+ "		부서번호 : <input type='text' name='dno'><br>\r\n"
				+ "		부서이름 :  <input type='text' name='dname'><br>\r\n"
				+ "		부서위치 :  <input type='text' name='dloc'><br>\r\n"
				+ "		<input type='submit' value='등록'>\r\n"
				+ "		<input type='reset' value='취소'>\r\n"
				+ "	</form>"; 
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.print(htmlTxt);
		
		out.close();
	}
}
package com.kosta.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/InsertDeptOK")
public class InsertDeptOK extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		int dno = Integer.parseInt(request.getParameter("dno"));
		String dname = request.getParameter("dname");
		String dloc = request.getParameter("dloc");
		
		String sql = "insert into dept values(?,?,?)";
		
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		int re = 0;
		
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, dno);
			pstmt.setString(2, dname);
			pstmt.setString(3, dloc);
			re = pstmt.executeUpdate();
			
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		
		if(re > 0) {
			out.print("<h1>추가 성공</h1>");
		}else {
			out.print("<h1>추가 실패</h1>");
		}
		out.close();
	}
}

 

쿼리스트링

  • 링크하면서 어떤 정보를 전달하는것. ?= 를 쓰며 이러한 정보를 쿼리 스트링이라고 한다.
package com.kosta.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ListCustomer
 */
@WebServlet("/ListCustomer")
public class ListCustomer extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListCustomer() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sql = "select custid, name from customer";
		String data = "<html>";
		data += "<body>";
		data += "<h2>고객목록 </h2>";
		data += "<hr>";
		data += "<ul>";
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()) {
				int custid = rs.getInt(1);
				String name = rs.getString(2);
				//링크 되면서 어떤 정보를 전달 -> 쿼리스트링 (공백 허용 X)
				data += "<li><a href='DetailCustomer?custid="+custid+"'>"+name +"</a></li>";
			}
			
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		
		data += "</ul>";
		data += "</body>";
		data += "</html>";
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(data);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
package com.kosta.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DetailCustomer")
public class DetailCustomer extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int custid = Integer.parseInt(request.getParameter("custid"));
		String sql = "select * from customer where custid = ?";
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String data = "<html>";
		data += "<body>";
		
		String driver ="oracle.jdbc.driver.OracleDriver";
		String url="jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, custid);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				String name = rs.getString(2);
				String address = rs.getString(3);
				String phone = rs.getString(4);
				data += "고객번호 :"+custid + "<br>";
				data += "고객이름 :"+name + "<br>";
				data += "고객주소 :"+address + "<br>";
				data += "고객전화 :"+phone + "<br>";
			}else {
				System.out.print("custid 확인 요망");
			}
			
			rs.close();
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		data += "<hr>";
		data += "<br>";
		data += "<br>";
		data += "<br>";
		data += "<br>";
		
		data += "<a href='DeleteCustomer?custid="+custid+"' style ='margin-right:16px;color:red'>고객 정보 삭제</a>";
		data += "<a href='UpdateCustomer?custid="+custid+"'>고객 정보 수정</a>";
		data += "</body>";
		data += "</html>";
		out.print(data);
		out.close();
	}
}

 

package com.kosta.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeleteCustomer
 */
@WebServlet("/DeleteCustomer")
public class DeleteCustomer extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		int custid = Integer.parseInt(request.getParameter("custid"));
		String sql = "delete customer where custid=?";
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		PrintWriter out = response.getWriter();
		int re = -1;
		
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, custid);
			
			re = pstmt.executeUpdate();
			
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		
		if(re > 0) {
			out.print("<h1>삭제 성공</h1>");
		}else {
			out.print("<h1>삭제 실패</h1>");
		}
		
	}
}

'Kosta DevOps 과정 280기 > Java' 카테고리의 다른 글

jsp 문장 구성 요소  (0) 2024.07.15
confirm  (0) 2024.07.15
서블릿과 jsp  (0) 2024.07.12
웹 어플리케이션 프로그래밍  (0) 2024.07.12
이벤트 연결하기  (0) 2024.07.11