day04_insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="java.sql.*" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>db에 인서트 하기</title>
</head>
<body>
	<%
	//1 . 드라이버 로딩
			Class.forName("com.mysql.jdbc.Driver");
			
			Connection conn=null;
			Statement stmt=null;
			ResultSet rs=null;
		//2. 연결
			try{
				//test는 database 이름 입니다 
				//mysql안에 database 만드는 명령:
				//c:/>mysqladmin -u root creat test -p
				
				String url="jdbc:mysql://localhost:3306/test";
				String user="root"; // 계정 이름 
				String password="1234"; //계정 비밀번호
				conn = DriverManager.getConnection(url, user, password);
				out.print("연결성공 :"+ conn.toString());
			}catch(Exception e){
				out.print("연결 실패-"+e.getMessage());
			}
			
			/*  create table jsp2(no integer primary key auto_increment,
						title varchar(20),context varchar(100)); */
			
			String sql="insert into jsp2 (title,context) values(?,?);";
			
			PreparedStatement preState = conn.prepareStatement(sql);
			
			String title=request.getParameter("title");//첫번째?
			String context=request.getParameter("context");//두번째?
					
			preState.setString(1,title);//첫번째 ?값을 셋팅하기
			preState.setString(2,context);//두번째 ?값을 셋팅하기
					
			int outcome=-1;		
			outcome=preState.executeUpdate();//insert 문 실행
			if(outcome>0){
				out.print("insert 성공 <br/>");
				out.print("결과"+outcome);
			}
	%>
			db에 insert하고 dayo4_list.jsp로 이동하게 만듭니다.
			<jsp:forward page="day04_list.jsp"></jsp:forward>
</body>
</html>


day04_writeForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>게시판 입력 폼</title>
	<style type="text/css">
		table{ border: 1px thin red; border-style: solid; padding:10px 10px 10px 10px;
			 background-color:silver;
			 }
	</style>

</head>
<body>
	<form action="day04_insert.jsp">
		<table>
			<tr>
				<td>글제목</td>
				<td>
					<input type="text" name="title" size="20" required="required">
				</td>
			</tr>
			<tr>
				<td>글내용</td>
				<td>
					<textarea rows="5" name="content"></textarea>
				</td>
			</tr>
			<tr>
				<td>
				<input type="submit" value="저장">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>


day04_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"  %>    
<%@ page import="bean.Item" %>
<%@ page import="java.util.ArrayList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>db에 jsp2테이블 가져오기</title>
		
		<link href="myStyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>		
	<%
		//1 . 드라이버 로딩
			Class.forName("com.mysql.jdbc.Driver");
			
			Connection conn=null;
			Statement stmt=null;
			ResultSet rs=null;
		//2. 연결
			try{
				//test는 database 이름 입니다 
				//mysql안에 database 만드는 명령:
				//c:/>mysqladmin -u root creat test -p
				
				String url="jdbc:mysql://localhost:3306/test";
				String user="root"; // 계정 이름 
				String password="1234"; //계정 비밀번호
				conn = DriverManager.getConnection(url, user, password);
				out.print("연결성공 :"+ conn.toString());
			}catch(Exception e){
				out.print("연결 실패-"+e.getMessage());
			}
		
					
			String query="select * from jsp2;";
			stmt=conn.createStatement();
			
			//db에 명령을 날리면 결과가 옵니다.
			rs=stmt.executeQuery(query);
			/* 
			out.print("<table>");
			while(rs.next()){//한칸 아래로 이동
				out.print("<tr><td> no </td><td>");
				out.print(rs.getString("no")+"</td></tr>");
				
				out.print("<tr><td id='title'> title </td><td class='title'>");
				out.print(rs.getString("title")+"</td></tr>");
				
				out.print("<tr><td> context </td><td>");
				out.print(rs.getString("context")+"</td></tr>");				
			}
			out.print("</table>"); */
			
			ArrayList<Item> arrayList= new ArrayList<Item>();
			while(rs.next()){
				//String -> int로 cast
				int no = Integer.parseInt(rs.getString("no"));
				String title = rs.getString("title");
				String context = rs.getString("context");
				Item item = new Item(no,title,context);
				arrayList.add(item);
			
			%> 
				<table>
					<tr>
						<td colspan="3">예제 테이블명 : jsp2</td>
					</tr>
					<tr>
						<th>no</th><!-- th 글씨 굵고 가운데 정렬 -->
						<td>title</td>
						<td>context</td>
					</tr>
					<tr>
						<td><%=no %></td>
						<td>
							<a href="day04_modify.jsp?no=<%=no%>">
								<%=title %>
							</a>
							</td>
						<td><%=context %></td>
					</tr>
				</table>
			<%
			}//while문 닫기
			rs.close();
			stmt.close();
			conn.close();
		%>

</body>
</html>


WEB-INF/src/bean/Item.java
package bean;

//필드, 생성자 ,getter,setter,toString
public class Item {
	int no;
	String title;
	String context;
	
	public Item(){}//default Constructs
	
	public Item(int no, String title, String context) {
		super();
		this.no = no;
		this.title = title;
		this.context = context;
	}

	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContext() {
		return context;
	}
	public void setContext(String context) {
		this.context = context;
	}

	@Override
	public String toString() {
		return "Item [no=" + no + ", title=" 
				+ title + ", context=" + context +"]";
	}
	
}




day04_modify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>수정/삭제 페이지</title>
	<link rel="stylesheet" href="myStyle.css" type="text/css">
</head>
<body>
	<% String no = request.getParameter("no"); 
	   //no에 해당하는 데이터를 db에서 불러와서 화면에 보여주자
	   
	   //커넥션을 맺고 no에 해당하는 데이터를 select문으로 불러와서
	   //resultSet을 읽어서 화면에 출력하기
	   
	%>
	<form action="#">
		<table>
			<tr>
				<td>글제목</td>
				<td>
					<input type="text" name="title" size="20" required="required">
				</td>
			</tr>
			<tr>
				<td>글내용</td>
				<td>
					<textarea rows="5" name="content"></textarea>
				</td>
			</tr>
			<tr>
				<td>
					<input type="button" value="수정">
				</td>
				<td>
					<input type="button" value="삭제">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>


WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JDBC study</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- jdbc 드라이버를 application 단위로 로딩하자 -->
  <!-- 서버시작시에 Loader라는 클래스를 실행 하기 -->
  <servlet>
      <servlet-name>JDBCDriverLoader</servlet-name>
  	  <servlet-class>loader.Loader</servlet-class>
  	  <init-param>
  	      <param-name>jdbcdirver</param-name>
  	      <param-value>com.mysql.jdbc.Driver</param-value>
  	  </init-param>
  	  <load-on-startup>1</load-on-startup>
  </servlet>
  
</web-app>


WEB-INF/src/loaer/Loader.java

package loader;

import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

//JDBC-connection 드라이버 로딩
public class Loader extends HttpServlet{
	public void init(ServletConfig config)throws ServletException{
		try{
			/*web.xml안에 있는
			<init-param>
	  	      <param-name>jdbcdirver</param-name>
	  	      <param-value>com.mysql.jdbc.Driver</param-value>
	  	      jdbcdriver의 value 값 읽어오기*/
			
			//String drivers="com.mysql.jdbc.Driver"
			String drivers= config.getInitParameter("jdbcdriver");
			StringTokenizer st = new StringTokenizer(drivers,",");
			while(st.hasMoreTokens()){
				String jdbcDriver=st.nextToken();
				Class.forName(jdbcDriver);
			}
			System.out.println("드라이버 로딩 성공");
		}catch (Exception e) {
			System.out.println("드라이버 로딩 실패");
			throw new ServletException(e);
		}
	}
}


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

4일차 JDBC2  (0) 2012.05.25
4일차 JDBC  (1) 2012.05.25
4일차 db에 insert 하기  (0) 2012.05.24
4일차 게시판 입력 폼  (0) 2012.05.24
4일차 JDBC(INSERT 하고 SELECT 내용 모두 화면에 표시하기)  (0) 2012.05.24

+ Recent posts