어제 만든거에서 수정 클릭시 내용 변경되서 DB에 저장 되도록 만들어 봄

Post방식으로 만든거라 만들었을때 한글만 깨져서 웹사이트에서 출력되고 DB에서도 한글만 깨져서

저장 됫다. 강사님 한태 물어보니

<%request.setCharacterEncoding("utf-8");%>     <=    해당 인코딩 부분을 넣어주니 해결 됫다.

 

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
request.setCharacterEncoding("utf-8");
%>

<%


    // 지정된 글 번호 얻기
    int num = Integer.parseInt(request.getParameter("num"));

    // 게시글 데이터를 담을 변수 정의
    String writer = "";
    String title = "";
    String regtime = "";
    int hits = 0;
    String content = "";

    // 지정된 글 번호를 가진 레코드 읽기
    Class.forName("org.mariadb.jdbc.Driver");
    try (
        Connection conn = DriverManager.getConnection(
                "jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
        Statement stmt = conn.createStatement();

        // 쿼리 실행
        ResultSet rs = stmt.executeQuery(
                "select * from board where num=" + num);
    ) {

        if (rs.next()) {

            // 글 데이터를 변수에 저장
            writer = rs.getString("writer");
            title = rs.getString("title");
            content = rs.getString("content");
            regtime = rs.getString("regtime");
            hits = rs.getInt("hits");

            // 글 제목과 내용이 웹 페이지에 올바르게 출력되도록
            // 공백과 줄 바꿈 처리
            title = title.replace(" ", "&nbsp;");
            content = content.replace(" ", "&nbsp;").replace("\n", "<br>");

            // 이 글의 조회수를 1 증가
            stmt.executeUpdate("update board set hits=hits+1 where num=" + num);


        }
        // 수정된 내용을 데이터베이스에 업데이트
        PreparedStatement pstmt = conn.prepareStatement("UPDATE board SET content = ? WHERE num = ?");
        pstmt.setString(1, content);
        pstmt.setInt(2, num);
        pstmt.executeUpdate();// 업데이트된 레코드 수를 반환
        pstmt.close();
        
    } catch (Exception e) {
        e.printStackTrace();
    }

%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <style>
        table {
            width: 680px;
            text-align: center;
        }

        th {
            width: 100px;
            background-color: cyan;
        }

        td {
            text-align: left;
            border: 1px solid gray;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <th>제목</th>
            <td><%=title %></td>
        </tr>
        <tr>
            <th>작성자</th>
            <td><%=writer %></td>
        </tr>
        <tr>
            <th>작성일시</th>
            <td><%=regtime %></td>
        </tr>
        <tr>
            <th>조회수</th>
            <td><%=hits %></td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
                <form action="update.jsp" method="post">
                    <input type="hidden" name="num" value="<%=num%>">
                    <textarea name="content" rows="5" cols="50"><%=content%></textarea>
                    <br>
                    <input type="submit" value="수정 완료">
                </form>
            </td>
        </tr>
    </table>
</body>
</html>

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
request.setCharacterEncoding("utf-8");// post방식 추가안하면 한글깨져서 나옴
%>
<%
    String content = request.getParameter("content");
	
    int num = Integer.parseInt(request.getParameter("num"));

    Class.forName("org.mariadb.jdbc.Driver");
    try (
        Connection conn = DriverManager.getConnection(
                "jdbc:mariadb://localhost:3307/jspdb", "root", "maria" );
        PreparedStatement pstmt = conn.prepareStatement("UPDATE board SET content = ? WHERE num = ?");
    ) {
    	
    	// 준비된 문에 content와 num 매개변수를 설정합니다.
        pstmt.setString(1, content);
        pstmt.setInt(2, num);
        
     // 업데이트 문을 실행합니다.
        pstmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 수정된 내용을 처리한 후 해당 게시물로 이동
    response.sendRedirect("view.jsp?num=" + num);
%>

 

굳이.. jsp파일을 2개 만들어서 해본거 같다. 

오늘 만든 새로 만든 게시판에서 공부해보면서 만들어 봐야겠다.

어제는 코드를 따라쳐서 만든거고 오늘은 구글링과 조금의 커닝으로... 만들어 보라고 해서 만들어봄

 

list.jsp

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.*"%>
<%@ 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>
    <style>
        table { width:780px;
                background-color: antiquewhite;
                text-align:center;}
         td { background-color: white;}
         th { background-color: antiquewhite;}
    </style>

<%
Class.forName("org.mariadb.jdbc.Driver");
try {
	Connection conn = DriverManager.getConnection(
			"jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
		
		
		//쿼리 실행
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("select * from board order by num desc");
		{
	
	
	
%>
	<table border="1">
        <tr>
            <th style="width: 10px;">번호</th>
            <th style="width: 30px;">제목</th>
			<th style="width: 10px;">작성자</th>
			<th style="width: 10px;">등록일</th>
			<th style="width: 0px; padding: 10px;"> 조회</th>
			
        </tr>
        <%
        while(rs.next()){
        %>
                <tr>
            <td><%=rs.getInt("num") %></td>
            <td style="text-align:left;">
				<a href="view.jsp?num=<%=rs.getInt("num") %>">
				<%=rs.getString("title") %>
				</a>
				</td>
			<td><%=rs.getString("writer") %></td>
			<td><%=rs.getString("regtime") %></td>
			<td><%=rs.getInt("hits") %></td>
			
        </tr>
<%
        }
		}}catch(Exception e){
	e.printStackTrace();
}
%>
</table>
<br>
<input type="button" value="글쓰기" onclick="location.href='view.jsp'">
    
</body>
</html>

view.jsp

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int num = Integer.parseInt(request.getParameter("num"));
String writer = "";
String title = "";
String content = ""; 

String url = "jdbc:mariadb://localhost:3307/jspdb";
String user = "root";
String pass = "maria";

int hits = 0;

%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
    <style>
        table { width:680px;
                background-color: antiquewhite;
                text-align:center;}
         td { background-color: white;
         		width:600px; text-align:left;
         }
         th { background-color: antiquewhite; }
         .content { height:500px;}
    </style>

<body>
<%
try {
	Class.forName("org.mariadb.jdbc.Driver");
	con = DriverManager.getConnection(url, user, pass);
	stmt = con.createStatement();
	rs = stmt.executeQuery("select * from board where num=" + num);
	System.out.println("DB접속 확인");
	if(rs.next()){
		writer = rs.getString("writer");
		title = rs.getString("title");
		content = rs.getString("content");
		hits = rs.getInt("hits");
	}
	//조회수
	stmt.executeUpdate(
			"update board set hits=hits+1 where num=" + num);
	
%>	
	<table border="1">
		<tr>
		<th>조회수</th>
		<td><%=hits %></td>
		</tr>
	
        <tr>
            <th>제목</th>
          	<td><%=writer %></td>
        </tr>
        
        <tr> 
            <th>작성자</th>
            <td><%=title %></td>
        </tr>  
        <tr>
			<th>내용</th>
			<td class="content" ><%=content %></td>
		</tr>	
     </table>

<% 		       
}catch (Exception e){
	e.printStackTrace();
}

%>

<input type="button" value="목록보기" onclick="location.href='list.jsp'">
	<input type="button" value="수정" onclick="location.href='write.jsp?num=<%=num%>'">
	<input type="button" value="삭제" onclick="location.href='delete.jsp?num=<%=num%>'">
</body>
</html>

default 인터페이스, 메소드

default 메소드 강제성이 없다.

인터페이스에 선언할 때 { } 몸통이 있음

클래스에 인터페이스에 추가할 때 좋음

기존 코드에 추가 할 때 용이

 

인터페이스

package exam0615;

// default 메소드

public interface TestInterface {
	void method();
	
	default void method2() { // default 메소드 강제성이 없다.
		System.out.println("method2");
	}
}


실행

package exam0615;

public class TestEx {

	public static void main(String[] args) {
		MyInterface mi = new MyClassB();
		mi.method2();
		

	}

}
<결과>
MyInterface-method2

 

 

인터페이스

package exam0615;

public interface MyInterface {
	void method1();
	
	default void method2() {
		System.out.println("MyInterface-method2");
	}
}


구현 객체 1

package exam0615;

public class MyClassA implements MyInterface {

	@Override
	public void method1() {
		System.out.println("MyClassA-method1");
		
	}

}


구현 객체 2
package exam0615;

public class MyClassB implements MyInterface {

	@Override
	public void method1() {
		System.out.println("method1");
		
	}

	
}

 

default 인터페이스, 메소드 ( 람다식 )

인터페이스 

package exam0615_2;

@FunctionalInterface// 인터페이스에 추상메소드 한개만 사용 가능 ( 람다식 개념 ) 
// default 인터페이스 가능

public interface MyInterface {
	void method();
//	void aaa();
}


실행

package exam0615_2;

public class MyInterfaceEx {

	public static void main(String[] args) {
		MyInterface my = new MyInterface() {
			
			@Override
			public void method() {
				System.out.println("my");
				
			}
		};
		my.method();
		
		// 람다식
		my = () -> {System.out.println("my1");};
		my.method();
		
		my = () -> {System.out.println("my2");};
		my.method();
	}

}
<결과>
my
my1
my2

 

인터페이스, 메소드 ( 람다식 )

인터페이스

package exam0615_2;

public interface MyInterface2 {
	int method(int x, int y);

}


실행

package exam0615_2;

public class MyInterfaceEx2 {

	public static void main(String[] args) {
		MyInterface2 my3 = new MyInterface2() {
			
			@Override
			public int method(int x, int y) {
				System.out.println(x+y);
				return x+y;
			}
		};
		
		MyInterface2 my2 = (x,y) -> {
			System.out.println(x+y);
		return x+y;
		};
		
		
		
		my3.method(3, 4);
		my2.method(5, 6);
		
		int res = my3.method(20, 30);
		System.out.println(res);
		
		MyInterface2 my4 = (a, b) -> {return a+b;};
		res = my4.method(100, 200);
		System.out.println(res);
		
	}

}
<결과>
7
11
50
50
300

 

예외 직접 만들기 => 처리

예외 상속 ( 예외 만들기 ) 

package exam0615_3;

// 예외 상속
public class TestException extends Exception {
	public TestException(String msg) {
		super(msg);
	}
}


예외 처리

package exam0615_3;

// 예외 처리 
public class Test {
	private int x;

	public int getX() {
		return x;
	}

	public void setX(int x) throws TestException {
		if(x < 0) {
			throw new TestException("x는 0보다 커야 합니다.");// 예외 생성 (예외 메세지 작성)
		}
		
		this.x = x;
	}
	
	
}


실행

package exam0615_3;

public class TestEx {

	public static void main(String[] args) {
		Test test = new Test();
		try {
			test.setX(-100);
		} catch (TestException e) {// 만든 예외 
			// TODO Auto-generated catch block
//			e.printStackTrace();
			System.out.println(e.getMessage());// 예외 메세지 출력
		}
		//작성 했던 예외 메세지 나옴
		//exam0615_3.TestException: x는 0보다 커야 합니다.
//		at chap10/exam0615_3.Test.setX(Test.java:13)
//		at chap10/exam0615_3.TestEx.main(TestEx.java:8)


	}

}
<결과>
x는 0보다 커야 합니다.

 

배열 예외 처리

선언 및 실행

package exam0615_4;

public class TryEx {

	public static void main(String[] args) {
		String[] strArray = {"10","2a"};
		int value = 0;
		for(int i=0; i<=2; i++) {
			try {
				value = Integer.parseInt(strArray[i]);
				
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("인덱스를 초과했음");
			}catch (NumberFormatException e) {
				System.out.println("숫자로 변화할 수 없음");
			} finally {
				System.out.println(value);
			}
			
		}

	}

}
<결과>
10
숫자로 변화할 수 없음
10
인덱스를 초과했음
10

 

배열 예외

선언 및 실행

package sec01.exam01;

public class ArrayEx {

	public static void main(String[] args) {
		
		//ArrayIndexOutOfBoundsException 에러

		
		if(args.length != 2) {
			System.out.println("매개 값이 부족 합니다.");
			System.exit(0);
		}
		
		String data = args[0];
		String data1 = args[1];

		
		System.out.println(args.length);
		System.out.println("args[0] : " + data);
		System.out.println("args[1] : " + data1);
		

	}

}
<결과>
2
args[0] : 10
args[1] : 20

 

Number 예외 

package sec01.exam01;

public class NumberFormatEx {

	public static void main(String[] args) {
		
		// int로 변경 가능
		String data1 = "100";
		int var1 = Integer.parseInt(data1);
		System.out.println(var1);
		
		// 에러 int로 변경 불가
		String data2 = "100as";
		int var2 = Integer.parseInt(data2);
		System.out.println(var1);
//		NumberFormatException 예외 발생
	}

}

 

Null 예외 

package sec01.exam01;


public class NullEx {
	//실행 예외
	public static void main(String[] args) {
		// 컴파일러가 오류 잡음
//		String data = null;
//		System.out.println(data.toString());
		//NullPointerException 예외 발생
		
		
		String data2 = null;
		System.out.println(data2.toString());
		//NullPointerException 예외 발생
		
		// 값이 null인지 비교 
		String data3 = null;
		if(data3 != null) {
			System.out.println(data3.toString());
		}else {
			System.out.println("값이 null이 아님");
		}
		//NullPointerException 예외 발생
	
		
	}

}

 

 

Class 예외 

package sec01.exam02;

class Animal{} // 부모
class Dog extends Animal{}// 자식
class Cat extends Animal{}// 자식
public class ClassCastEx {
	
	//매개변수가 부모타입
	public static void changeDog(Animal animal) {
//		Dog dog = (Dog) animal; // 강제 형변환

		if(animal instanceof Dog) {
			Dog dog = (Dog) animal;
		}else {
			System.out.println("안됩니다.");
		}
	}
	
	public static void main(String[] args) {
		Dog dog = new Dog();
		Cat cat = new Cat();
		
		// 가능
		changeDog(dog);
		
		//ClassCastException 에러 
//		changeDog(cat);

	}

}

 

예외 떠넘기기 throws

package sec01.exam03;

public class ThrowsEx {
	// 예외 떠넘기기
	public static void findClass() throws ClassNotFoundException {
		Class.forName("shdg.fnjgs.dghj");
	}
	
//	public static void main(String[] args) throws ClassNotFoundException {
//		findClass();
//		// ClassNotFoundException: 에러
//		System.out.println("여기");
//	}
	
	public static void main(String[] args) {
		try {
			findClass();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// ClassNotFoundException: 에러
		System.out.println("여기");
	}
	
}

 

배열 다중 catch

package sec01.exam03;

public class TryCatchFinallyRuntimeEx {
	// 다중 catch
	public static void main(String[] args) {
		String data1 = null;
		String data2 = null;
		try {
			data1 = args[0];
			data2 = args[1];
			int value1 = Integer.parseInt(data1);
			int value2 = Integer.parseInt(data2);
			int result = value1 + value2;
			System.out.println(value1 + "+" + value2 + "=" + result);
		} catch (ArrayIndexOutOfBoundsException e) {// <= 배열 예외 생겼을때 처리
			System.out.println("실행 매개값의 수가 부족합니다.");
		} catch (NumberFormatException e) {// <= 문자열로 되어 있는 데이터를 숫자로 변경할때 예외 처리
			e.printStackTrace();
			System.out.println("숫자로 변화할 수 없습니다.");
		}finally {// <= 항상 실행
			System.out.println("다시 실행 하세요.");
		}
	}

}
<결과>
90+80=170
다시 실행 하세요.

 

try, catch 예외 처리 코드 basic

package sec01.exam03;

public class TryEx {
	//try, catch 예외 처리 코드 basic
	public static void main(String[] args) {
		try {
			Class.forName("java.leng.String2");// 해당 파일 존재하지 않음
		} catch (ClassNotFoundException e) { // <= 해당 위치에 오류코드 넣기
			e.printStackTrace();// 오류 코드 확인
			System.out.println("클래스가 존재하지 않습니다.");
			//System.out.println(e.getMessage());
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		

	}

}
<실행>
java.lang.ClassNotFoundException: java.leng.String2
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
	at java.base/java.lang.Class.forName0(Native Method)
	at java.base/java.lang.Class.forName(Class.java:375)
	at chap10/sec01.exam03.TryEx.main(TryEx.java:7)
클래스가 존재하지 않습니다.

 

기본 API 클래스

java.lang 패키지

java.lang 패키지는 자바 프로그램의 기본적인 클래스를 담고 있는 패키지이다.

패키지에 있는 클래스와 인터페이스는 import 없이 사용할 수 있다.

 

 

자바 API 도큐먼트

API ( Aplication Programming Interface )는 API 라이브러리라고 부르기도 하는데, 프로그램 개발에 자주 사용

되는 클래스 및 인터페이스 모음을 말한다.

https://docs.oracle.com/en/java/javase/ 해당 URL에서 버전별로 볼 수 있다.

 

 

 

Object 클래스

객체 비교(equals())

Object 클래스 비교 

package sec01.exam01;

public class Ex01 {

	public static void main(String[] args) {
		Object obj1 = new Object();
		Object obj2 = new Object();
		
		boolean result1 = obj1.equals(obj2);
//		System.out.println(result1); // false
		
		boolean result2 = (obj1 == obj2);
		System.out.println(result2); // false
	}

}

 

 

객체 동등 비교 ( 선언 )

package sec01.exam01;

public class Member {
	String id;

	
	public Member(String id) {
		this.id = id;
	}

	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Member) { // 매개값이 Member 타입인지 확인
			Member member = (Member) obj;
			if (id.equals(member.id)) {
				return true;
			}
		}
		return false;
	}
	
}


객체 동등 비교 ( 실행 )

package sec01.exam01;

public class MemberEx {

	public static void main(String[] args) {
		Member obj1 = new Member("blue");
		Member obj2 = new Member("blue");
		Member obj3 = new Member("red");
		if(obj1.equals(obj2)) {
			System.out.println("obj1와 obj2는 같다.");
		}else {
			System.out.println("obj1와 obj2는 틀리다.");
		}

	}

}
<결과>
obj1와 obj2는 같다.

 

package sec01.exam01;

public class SString {

	public static void main(String[] args) {
//		String str1 = new String("test");
//		String str2 = new String("test");
//		if(str1 == str2) {
//			System.out.println("같다");
//		}else {
//			System.out.println("다르다");
//		} // 결과 : 다르다.
		
		String str1 = new String("test");
		String str2 = new String("test");
		if(str1.equals(str2)) {
			System.out.println("같다");
		}else {
			System.out.println("다르다");
		} // 결과 : 같다.

	}

}

 

객체 해시코드

객체 해시코드란 객체를 식별하는 하나의 정수값을 말한다. 객체의 메모리 번지를 이용해서 해시코드를 만들어 

리턴하기 때문에 객체마다 다른 값을 가지고 있다. 

선언

package sec01.exam01;

import java.util.Objects;

//해쉬코드
public class Key {
	int number;
	public Key(int number) {
		this.number = number;
	}
	// 1 번
//	@Override // 해쉬 코드 재정의
//	public int hashCode() {
//		return number;// 
//		// 해쉬값을 int값으로 바꿔줌
//	}
	
	// 2번
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Key) {
			Key c = (Key) obj;
			if(this.number == c.number) {
				return true;
			}
		}
		return false;
	}
	// 2번
	public int hashCode() {
		return number;
	}

	
}


호출
package sec01.exam01;

import java.util.HashMap;

public class KeyEx {

	public static void main(String[] args) {
		// 1번
//		Key key1 = new Key(100);
//		Key key2 = new Key(100);
//		System.out.println(key1.hashCode());
//		System.out.println(key2.hashCode());
		
		// 2번
		HashMap< Key, String > hashmap = new HashMap<Key, String>();
		hashmap.put(new Key(1), "홍길동");
		String name = hashmap.get(new Key(1));
		System.out.println(name);

	}

}

 

HashMap

package sec01.exam01;

import java.util.HashMap;

public class HashMapEx {

	public static void main(String[] args) {
		//제네릭 <Integer(키값), String(출력물)>
		HashMap<Integer, String> map = new HashMap<>();
		map.put(1, "한국");// put 값 넣기
		map.put(2, "미국");
		map.put(3, "일본");
		String val = map.get(2);// get 값 출력
		System.out.println(val);// get(2) 미국 출력
		

	}

}
<결과>
미국

 

제네릭

선언

package sec01.exam01;
// 제네릭
public class NewBox<T> {
	private T t;

	public T get() {
		return t;
	}

	public void set(T t) {
		this.t = t;
	}
	
}


실행

package sec01.exam01;

public class NewBoxEx {

	public static void main(String[] args) {
//		<클래스> 클래스만 가능
		
		NewBox<String> newBox = new NewBox<String>();
		newBox.set("홍길동");
		String name = newBox.get();
		System.out.println(name);
		
		NewBox<Apple> newBox2 = new NewBox<Apple>();
		newBox2.set(new Apple());
		Apple apple = newBox2.get();
		System.out.println(apple);
		
		NewBox<Integer> a3 = new NewBox<Integer>();
		a3.set(100);
		int res = a3.get();
		System.out.println(res);

	}

}
<결과>
홍길동
sec01.exam01.Apple@1e643faf
100

 

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

JDBC_설정(MariaDB, 이클립스)  (1) 2023.06.17
2023-06-16 21일차  (0) 2023.06.16
2023-06-14 19일차  (0) 2023.06.14
2023-06-13 18일차  (0) 2023.06.13
2023-06-12 17일차  (1) 2023.06.12

코드

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.*"%>
<%@ 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>
<style>
	table { width:680px; text-align:center;}
	th { background-color: cyan;}

	.num { width: 80px;}
	.title{width: 230px;}
	.writer{width: 100px;}
	.regtime{width: 180px;}

	a:link { text-decoration: none; color: blue;}
	a:visited { text-decoration: none; color: gray;}
	a:hover { text-decoration: none; color: red;}
	
</style>


<table>
<tr>
	<th class="num" > 번호 </th>
	<th class="title" > 제목 </th>
	<th class="writer" > 작성자 </th>
	<th class="regtime" > 작성일시 </th>
	<th > 조회수 </th>
<%



	//게시글 리스트 읽어오기
	Class.forName("org.mariadb.jdbc.Driver");
	try(
		Connection conn = DriverManager.getConnection(
				"jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
			
			
			//쿼리 실행
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from board order by num desc");
			){
			// 게시글 레코드가 남아있는 동안 반복하여 화면에 출력
			while (rs.next()){
%>
		<tr>
			<td><%=rs.getInt("num") %></td>
			<td style="text-align:left;">
				<a href="view.jsp?num=<%=rs.getInt("num") %>">
				<%=rs.getString("title") %>
				</a>
				</td>
				<td><%=rs.getString("writer") %></td>
				<td><%=rs.getString("regtime") %></td>
				<td><%=rs.getInt("hits") %></td>
				</tr>
<% 
			}
		}catch(Exception e){
			e.printStackTrace();
		}
%>
</table>

<br>
<input type="button" value="글쓰기" onclick="location.href='write.jsp'">

</body>
</html>

 

제목에 있는 글 클릭시 view.jsp 이동

 

코드

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

<%@ page import="java.sql.*" %>
<%
	// 지정된 글 번호 얻기
	int num = Integer.parseInt(request.getParameter("num"));

	// 게시글 데이터를 담을 변수 정의
	String writer = "";
	String title = "";
	String content = "";
	String regtime = "";
	int hits = 0;
	
	// 지정된 글 번호를 가진 레코드 읽기
	Class.forName("org.mariadb.jdbc.Driver");
	try (
		Connection conn = DriverManager.getConnection(
				"jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
			Statement stmt = conn.createStatement();
			
			// 쿼리 실행
			ResultSet rs = stmt.executeQuery(
					"select * from board where num=" + num);
			){
		if (rs.next()) {
			
			// 글 데이터를 변수에 저장
			writer = rs.getString("writer");
			title = rs.getString("title");
			content = rs.getString("content");
			regtime = rs.getString("regtime");
			hits = rs.getInt("hits");
			
			// 글 제목과 내용이 웹 페이지에 올바르게 출력되도록
			// 공백과 줄 바꿈 처리
			
			title  = title.replace(" ", "&nbsp;");
			content  = content.replace(" ", "&nbsp;").replace("\n", "<br>");
			
			// 이 글의 조회를 1올림
			stmt.executeUpdate(
					"update board set hits=hits+1 where num=" + num);
			
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	table { width:680px; text-align:center;}
	th { width:100px; background-color:cyan;}
	td { text-align:left; border:1px solid gray;}
</style>

</head>
<body>
<table>
	<tr>
		<th>제목</th>
		<td><%=title %></td>
	</tr>
	
	<tr>
		<th>작성자</th>
		<td><%=writer %></td>
	</tr>
	
	<tr>
		<th>작성일시</th>
		<td><%=regtime %></td>
	</tr>
	
	<tr>
		<th>조회수</th>
		<td><%=hits %></td>
	</tr>
	
	<tr>
		<th>내용</th>
		<td><%=content %></td>
	</tr>
	</table>
	<br>
	<input type="button" value="목록보기" onclick="location.href='list.jsp'">
	<input type="button" value="수정" onclick="location.href='write.jsp?num=<%=num%>'">
	<input type="button" value="삭제" onclick="location.href='delete.jsp?num=<%=num%>'">

</body>
</html>

 

 

코드

package swing0614;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.xml.sax.ext.Attributes2;

public class WinPerson extends JFrame {
	
	Connection con = null;
	
	//사용자 입력 칸
	JTextField tf1 = new JTextField();// id
	JTextField tf2 = new JTextField();// name
	JTextField tf3 = new JTextField();// addr
	JTextField tf4 = new JTextField();// phone
	
	// 검색, 입력, 수정, 삭제 기능 수행 버튼
	JButton bt1 = new JButton("검색");
	JButton bt2 = new JButton("입력");
	JButton bt3 = new JButton("수정");
	JButton bt4 = new JButton("삭제 ");
	
	// 텍스트BOX 결과 출력
	JTextArea ta = new JTextArea();
	
	// 각 정보 이름
	JLabel la1 = new JLabel("id");
	JLabel la2 = new JLabel("name");
	JLabel la3 = new JLabel("addr");
	JLabel la4 = new JLabel("phone");
	
	WinPerson() throws ClassNotFoundException, SQLException{
		
        String url = "jdbc:mariadb://localhost:3307/jspdb";
        String user = "root";
        String pass = "maria";
        Class.forName("org.mariadb.jdbc.Driver");
        System.out.println("드라이버 로딩!");

        con = DriverManager.getConnection(url, user, pass);
        System.out.println("접속 성공!");
		
		// 종료 후 실행 중지 
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
		// 윈도우 기초 패널
		Container c = this.getContentPane();
		
		// 컴포넌트를 임의의 위치에 고정시키려고
		this.setLayout(null);
		this.setTitle("person");
		this.setSize(400, 300);
		this.setLocation(500, 500);
		this.setVisible(true);
		
		
		tf1.setSize(80, 20);
		tf1.setLocation(15, 30);
		c.add(tf1);
		tf2.setSize(80, 20);
		tf2.setLocation(100, 30);
		c.add(tf2);
		tf3.setSize(80, 20);
		tf3.setLocation(190, 30);
		c.add(tf3);
		tf4.setSize(80, 20);
		tf4.setLocation(280, 30);
		c.add(tf4);
		
		bt1.setSize(80, 20);
		bt1.setLocation(15, 200);
		c.add(bt1);
		bt2.setSize(80, 20);
		bt2.setLocation(100, 200);
		c.add(bt2);
		bt3.setSize(80, 20);
		bt3.setLocation(190, 200);
		c.add(bt3);
		bt4.setSize(80, 20);
		bt4.setLocation(280, 200);
		c.add(bt4);
		
		la1.setSize(80, 20);
		la1.setLocation(15, 5);
		c.add(la1);
		la2.setSize(80, 20);
		la2.setLocation(100, 5);
		c.add(la2);
		la3.setSize(80, 20);
		la3.setLocation(190, 5);
		c.add(la3);
		la4.setSize(80, 20);
		la4.setLocation(280, 5);
		c.add(la4);
		
		
		
		// 텍스트BOX
//		ta.setSize(320, 80);
//		ta.setLocation(30,100);
//		c.add(ta);
		
		// 텍스트BOX + 스크롤
		JScrollPane scrollPane = new JScrollPane(ta);
		ta.setCaretPosition(ta.getDocument().getLength());
		scrollPane.setSize(320, 80);
		scrollPane.setLocation(30, 80);
		c.add(scrollPane);
		
		// 버튼 클릭되었을 때 수행할 동작 정의
		bt1.addActionListener(new ActionListener() {
			// 검색
			@Override
			public void actionPerformed(ActionEvent e) {
				
				// 사용자가 입력한 값 s1, s2, s3에 저장
				String s1 = tf2.getText();
				String s2 = tf3.getText();
				String s3 = tf4.getText();
				
				String sql = "select * from person"// 테이블의 모든 열을 선택하는 것을 의미
						// name, addr, phone 칼럼 값이 입력된 조건과 일치하는 행을 검색
						// like 연산자와 % 기호를 사용하여 부분 일치 검색을 수행
						+ " where name like '%"+ s1 +"%'"
						+ " and addr like '%"+ s2 + "%'"
						+ " and phone like '%"+ s3 + "%'";
				
				// tf1로부터 입력된 id 값을 s4id에 저장
				// s4id가 비어있지 않다면, 추가적으로 id 칼럼 값을 이용하여 검색하는 쿼리를 생성
				String s4id = tf1.getText();
				if(!s4id.equals("")) {
					sql += " select % from person where id = " + s1;
				}
				 try {
					ta.setText("");// 내용 초기화 데이터 중복으로 쌓이는거 해결
					Statement stmt = con.createStatement();
					ResultSet rs = stmt.executeQuery(sql);
					while(rs.next()) {
						int id = rs.getInt("id");
						String name = rs.getString("name");
						String addr = rs.getString("addr");
						String phone = rs.getString("phone");
						String str = String.format("%d, %s, %s, %s\n", id,name,addr,phone);
						ta.append(str);
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				
			}
		});
	}
		
		
	

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		new WinPerson();

	}

}

 

하나, 중첩 검색 가능 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts