package demo.writer;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

public class PrintWriterDemo1 {

	public static void main(String[] args) throws Exception {
		
		// PrintWriter writer = new PrintWriter("c:/temp/scores.csv");
		
		//File file = new File("c:/temp/scores.csv");
		//PrintWriter writer = new PrintWriter(file);
		
		PrintWriter writer = new PrintWriter(new FileWriter("c:/temp/scores.csv"));
		
		writer.println("김유신,전자공학과,3,3.8");
		writer.println("이순신,기계공학과,3,4.1");
		writer.println("강감찬,무기재료공학과,1,4.5");
		writer.println("홍길동,환경공학과,2,3.2");
		
		writer.flush();
		
		writer.close();
	}
}

'자바 > io' 카테고리의 다른 글

serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.serialization;

import java.io.Serializable;

public class Employee implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private String name;
	private String position;
	// 직렬화, 역직렬화 대상에서 제외된다.
	private transient int password;
	private Family child;
	
	public Employee() {}

	
	
	public Employee(String name, String position, int password, Family child) {
		super();
		this.name = name;
		this.position = position;
		this.password = password;
		this.child = child;
	}



	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		this.password = password;
	}

	public Family getChild() {
		return child;
	}

	public void setChild(Family child) {
		this.child = child;
	}
	
	
}
package demo.serialization;

import java.io.Serializable;

public class Family implements Serializable {

	private String name;
	private int count;
	
	public Family() {}

	public Family(String name, int count) {
		this.name = name;
		this.count = count;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
}
package demo.serialization;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationDemo1 {

	public static void main(String[] args) throws Exception {
		
		Family f = new Family("자녀", 2);
		Employee employee = new Employee();
		employee.setName("홍길동");
		employee.setPosition("과장");
		employee.setPassword(1234);
		employee.setChild(f);
		
		FileOutputStream fos = new FileOutputStream("c:/temp/emp.sav");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		// void writeObject(Object o)
		// 객체를 직렬화한다.
		oos.writeObject(employee);
		
		oos.close();
	}
}
package demo.serialization;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationDemo1 {

	public static void main(String[] args) throws Exception {
		
		FileInputStream fis = new FileInputStream("c:/temp/emp.sav");
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		// Object readObject()
		// 스트림으로 읽어들인 데이터를 이용해서 객체를 복원(역직렬화)한다.
		Object obj = ois.readObject();
		// System.out.println(obj);
		Employee emp = (Employee) obj;
		System.out.println("이름 : " + emp.getName());
		System.out.println("직위 : " + emp.getPosition());
		System.out.println("비번 : " + emp.getPassword());
		System.out.println("가족 : " + emp.getChild().getName());
		System.out.println("가족수 : " + emp.getChild().getCount());
		
		ois.close();
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.reader;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo1 {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		FileReader reader = new FileReader("c:/temp/data.csv");
		BufferedReader br = new BufferedReader(reader);
		
		/*
		br.readLine();
		br.readLine();
		br.readLine();
		
		// 15~17 이미 읽어서 null 뜸.
		String text1 = br.readLine();
		String text2 = br.readLine();
		String text3 = br.readLine();
		String text4 = br.readLine();
		
		System.out.println(text1);
		System.out.println(text2);
		System.out.println(text3);
		System.out.println(text4);
		*/
		
		String text = null;
		while ((text=br.readLine()) != null) {
			System.out.println(text);
		}
		
		br.close();
	}
}
package demo.reader;

import java.io.BufferedReader;
import java.io.FileReader;

public class BufferedReaderDemo2 {

	public static void main(String[] args) throws Exception {
		BufferedReader reader = new BufferedReader(new FileReader("c:/temp/data.csv"));

		int totalEventCount = 0;
		String text = null;
		while ((text=reader.readLine()) != null) {
			String[] items = text.split(",");
			
			String location = items[5].replace("\"", "");
			if (location.startsWith("서울특별시")) {
			// 발생건수
			int event = Integer.parseInt(items[6]);
			totalEventCount += event;
			}
		}
		System.out.println("서울지역 발생건수 : " + totalEventCount);
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.file;

import java.io.File;
import java.util.Date;

public class FileDemo1 {

	public static void main(String[] args) {
		
		// 지정된 파일의 정보를 가지는 파일객체 생성하기
		File file = new File("c:/java_workspace/oop6/Account.java");
		
		// String getName()
		// 파일명 획득하기
		String filename = file.getName();
		System.out.println("파일명 : " + filename);
		
		// long length()
		// 파일 사이즈 획득하기
		long filesize = file.length();
		System.out.println("파일 사이즈 : " + filesize + "바이트");

		// String getPath()
		// 전체 경로 획득하기
		String path = file.getPath();
		System.out.println("전체 경로 : " + path);
		
		// String getParent()
		// 파일이 위치한 디렉토리 경로 획득하기
		String directoryPath = file.getParent();
		System.out.println("디렉토리 경로 : " + directoryPath);
		
		// boolean isFile()
		// 파일인지 여부를 반환한다. 파일인 경우 true를 반환
		boolean isFile = file.isFile();
		System.out.println("파일인가? " + isFile);
		
		// boolean isDirectory()
		// 디렉토리인지 여부를 반환한다. 디렉토리인 경우 true를 반환
		boolean isDirectory = file.isDirectory();
		System.out.println("디렉토리인가 ? " + isDirectory);
		
		// boolean isExist()
		// 존재하는지 여부를 반환한다.
		boolean exist = file.exists();
		System.out.println("존재하는가? " + exist);
		
		// long lastModified()
		// 파일의 최종 수정 일자를 유닉스 시간으로 반환한다.
		long time = file.lastModified();
		System.out.println("최종 수정 일자 : " + time);
		Date date = new Date(time);
		System.out.println("최종 수정 일자 : " + date);
		
	}
}

package demo.file;

import java.io.File;

public class FileDemo2 {

	public static void main(String[] args) throws Exception {
		
		File file = new File("c:/temp/sample.txt");

		// 새 파일 생성하기
		file.createNewFile();
		
	}
}
package demo.file;

import java.io.File;

public class FileDemo3 {

	public static void main(String[] args) {
		
		File dir = new File("c:/temp/source");
		dir.mkdir();
		
		File dirs = new File("c:/temp/resource/images/logo");
		dirs.mkdirs();
	}
}
package demo.file;

import java.io.File;

public class FileDemo4 {

	public static void main(String[] args) {
		
		// 파일의 전체 경로를 활용해서 파일 객체를 초기화
		File file1 = new File("c:/temp/sample.txt");
		
		// 디렉토리명과 파일명을 활용해서 파일객체를 초기화
		File file2 = new File("c:/temp", "sample.txt");

		// 디렉토리 정보를 가진 파일 객체와 파일명을 활용해서 파일 객체를 초기화
		File dir = new File("c:/temp");
		File file3 = new File(dir, "sample.txt");
	}
}
package demo.file;

import java.io.File;

public class FileDemo5 {

	public static void main(String[] args) {
		
		File file1 = new File("c:/temp/source/a.txt");
		file1.delete();
		
		// 폴더 안에 다른 파일이 있으면 폴더는 지워지지 않는다.
		File dir = new File("c:/temp/source");
		dir.delete();
		
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {

	public static void main(String[] args) throws IOException {

		// 지정된 파일을 읽어오는 FileInputStream 생성하기
		FileInputStream in = new FileInputStream("c:/temp/suyoung.jpg");
		
		// 지정된 파일명을 기록하는 FileOutputStream 생성하기
		FileOutputStream out = new FileOutputStream("c:/temp/copy_suyoung.jpg");
		
		int value = 0;
		// InputStream으로부터 1byte씩 읽어온다.
		while ((value = in.read()) != -1) {
			// OutputStream을 사용해서 읽어온 값을 기록한다.
			out.write(value);
		}
		in.close();
		out.close();
	}
}
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class FileCopy2 {

	public static void main(String[] args) throws Exception {
		InputStream in = new FileInputStream("c:/temp/suyoung.jpg");
		OutputStream out = new FileOutputStream("c:/temp/copycopy_suyoung.jpg");
		
		IOUtils.copy(in, out);
	}
}
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class ImageCrawler {

	public static void main(String[] args) throws Exception {
		long startTime = System.currentTimeMillis();
		
		// URL url = new URL("https://img3.daumcdn.net/thumb/R658x0.q70/?fname=https://t1.daumcdn.net/news/201903/26/newsen/20190326101733645qadi.jpg");
		
		// InputStream in = url.openStream();
		// FileOutputStream out = new FileOutputStream("C:/temp/lee.jpg");
		
		FileInputStream in = new FileInputStream("c:/temp/tomcat.exe");
		FileOutputStream out = new FileOutputStream("c:/temp/copy_tomcat.ext");
		
		// 배열에 저장되는 데이터의 개수를 저장하는 변수
		int len = 0;
		// intputStream으로 읽어들인 데이터를 저장하는 배열
		byte[] buf = new byte[1024*8];
		
		// int red(byte[] buf)는 inputStream으로 읽어들인 데이터를
		// 전달받은 배열에 저장하고, 최종적으로 저장된 개수를 반환한다.
		
		while ((len = in.read(buf)) != -1) {
			// void write(byte[] buf, int offset, int len)은 전달받은 배열에 저장된 데이터를
			// offset위치부터 len 개수만큼 기록한다.
			out.write(buf, 0, len);
			
		}
		
		long endTime = System.currentTimeMillis();
		
		//int value = 0;
		//while ((value = in.read()) != -1) {
		//	out.write(value);
		//}
		in.close();
		out.close();
		
	}
}
package demo.bytestream;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class ImageCrawler2 {

	public static void main(String[] args) throws Exception {
		
		URL url = new URL("https://imgnews.pstatic.net/image/346/2019/03/26/0000025295_001_20190326072103336.jpg?type=w647");
		
		InputStream in = url.openStream();
		OutputStream out = new FileOutputStream("c:/temp/미니_소세지.jpeg");
		
		IOUtils.copy(in, out);
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.bridge;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BridgeStreamDemo1 {

	public static void main(String[] args) throws Exception {
		
		System.out.println("이름을 입력하세요.");
		
		// 소스(키보드)와 연결된 InputStream
		// InputStream is = System.in;
		// 바이트스트림을 문자스트림으로 변환해주는 InputStreamReader
		// InputStreamReader isr = new InputStreamReader(is);
		// 다른 문자스트림과 연결해서 성능을 향상시키는 BufferedReader
		// BufferedReader br = new BufferedReader(isr);
		
		// 압축
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		
		String text = br.readLine();
		System.out.println(text);
		
		// 키보드와 연결된 스트림 사용하기
		// InputStream in = System.in;
		// 키보드와 연결된 스트림으로 1byte 읽어오기
		// int value = in.read();
		
		// System.out.println(value);
		
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
package db.utils;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionUtils {

	public static Connection getConnection() throws Exception {
		Class.forName("oracle.jdbc.OracleDriver");
		
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "hr";
		String password = "zxcv1234";
		
		Connection conn = DriverManager.getConnection(url, user, password);
		
		return conn;		
	}
}

'자바 > jdbc' 카테고리의 다른 글

demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package db.demo3;

import java.sql.Date;

public class UserVO {

	private String id;
	private String name;
	private String pwd;
	private String phone;
	private String email;
	private int point;
	private Date createDate;
	
	public UserVO(String id, String name, String pwd, String phone, String email, int point, Date createDate) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
		this.phone = phone;
		this.email = email;
		this.point = point;
		this.createDate = createDate;
	}

	public UserVO() {}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getPoint() {
		return point;
	}

	public void setPoint(int point) {
		this.point = point;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
}

 

package db.demo3;

import java.util.ArrayList;

public class UserService {
	
	UserDAO userDao = new UserDAO();
	
	public void removeUser(String id) throws Exception {
		UserVO user = userDao.getUserById(id);
		
		if (user == null) {
			throw new Exception("사용자 정보가 존재하지 않습니다.");
		}
		userDao.deleteUser(id);
	}
	
	
	
	public void modifyUserInfo(UserVO newUser) throws Exception {
		UserVO user = userDao.getUserById(newUser.getId());
		if (user == null) {
			throw new Exception("사용자 정보가 존재하지 않습니다.");
		}
		
		user.setName(newUser.getName());
		user.setPhone(newUser.getPhone());
		user.setEmail(newUser.getEmail());
		
		userDao.updateUser(user);
	}

	public UserVO findUserById(String id) throws Exception {
		UserVO user = userDao.getUserById(id);
		if (user == null) {
			throw new Exception("[" + id + "]에 해당하는 사용자 정보를 찾을 수 없습니다.");
		}
		return user;
	}
	
	public ArrayList<UserVO> searchUsers(String name) throws Exception {
		ArrayList<UserVO> users = userDao.searchUsersByName(name);
		if (users.isEmpty()) {
			throw new Exception("[" + name + "]에 해당하는 사용자 정보를 찾을 수 없습니다.");
		}
		
		// 검색된 정보가 있을 경우에만 정보를 반환함
		return users;
		
	}
	public ArrayList<UserVO> getAllUsers() throws Exception {
		ArrayList<UserVO> users = userDao.getAllUsers();
		
		return users;
	}
	
	public void addNewUser(UserVO user) throws Exception {
		
		
		// 사용자가 입력한 아이디로 사용자 정보를 조회한다.
		UserVO dbUser = userDao.getUserById(user.getId());
		// 이미 등록된 사용자 정보가 존재하는지 체크한다.
		if (dbUser != null) {
			throw new Exception("동일한 아이디를 가진 사용자가 이미 존재합니다.");
		}
		
		// 등록된 사용자 정보가 없으면 신규 사용자로 등록한다.
		userDao.addUser(user);
	}
}

 

package db.demo3;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import db.utils.ConnectionUtils;

public class UserDAO {

	// 사용자 정보 변경하기
	public void updateUser(UserVO user) throws Exception {
		String sql = "update store_users set user_name = ? , user_phone = ?, user_email = ? where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		pstmt.setString(1, user.getName());
		pstmt.setString(2, user.getPhone());
		pstmt.setString(3, user.getEmail());
		pstmt.setString(4, user.getId());
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
	}
	
	// 새로운 사용자 정보 추가하기
	public void addUser(UserVO user) throws Exception {
		String sql = "insert into store_users (user_id, user_name, user_pwd, user_phone, user_email, user_point) "
				+ "values (?, ?, ?, ?, ?, 0)";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
	
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getName());
		pstmt.setString(3, user.getPwd());
		pstmt.setString(4, user.getPhone());
		pstmt.setString(5, user.getEmail());
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
	}
	
	// 지정된 아이디에 해당하는 사용자 정보 삭제하기
	public void deleteUser(String id) throws Exception {
		String sql = "delete from store_users where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, id);
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
		
	}
	
	// 지정된 이름에 해당하는 사용자 정보 조회하기
	public ArrayList<UserVO> searchUsersByName(String name) throws Exception {
		ArrayList<UserVO> users = new ArrayList<UserVO>();
		
		String sql = "select * from store_users where user_name = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, name);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			UserVO user = new UserVO();
			user.setId(rs.getString("user_id"));
			user.setName(rs.getString("user_name"));
			user.setPwd(rs.getString("user_pwd"));
			user.setPhone(rs.getString("user_phone"));
			user.setEmail(rs.getString("user_email"));
			user.setPoint(rs.getInt("user_point"));
			user.setCreateDate(rs.getDate("user_create_date"));
			
			users.add(user);
		}
		
		rs.close();
		pstmt.close();
		con.close();		
		return users;
	}
	
	
	// 지정된 아이디에 해당하는 사용자 정보 조회하기 1
	public UserVO getUserById (String id) throws Exception {
		UserVO user = null;
		
		String sql = "select * from store_users where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, id);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			user = new UserVO();
			//UserVO user = new UserVO();
			user.setId(rs.getString("user_id"));
			user.setName(rs.getString("user_name"));
			user.setPwd(rs.getString("user_pwd"));
			user.setPhone(rs.getString("user_phone"));
			user.setEmail(rs.getString("user_email"));
			user.setPoint(rs.getInt("user_point"));
			user.setCreateDate(rs.getDate("user_create_date"));
		}
		rs.close();
		pstmt.close();
		con.close();
		
		return user;
	}
	
	// 전체 사용자 정보 조회하기
	public ArrayList<UserVO> getAllUsers() throws Exception {
		ArrayList<UserVO> users = new ArrayList<UserVO>();
		
		String sql = "select * from store_users order by user_id asc";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			String id = rs.getString("user_id");
			String name = rs.getString("user_name");
			String pwd = rs.getString("user_pwd");
			String phone = rs.getString("user_phone");
			String email = rs.getString("user_email");
			int point = rs.getInt("user_point");
			Date createDate = rs.getDate("user_create_date");
			
			UserVO user = new UserVO();
			user.setId(id);
			user.setName(name);
			user.setPwd(pwd);
			user.setPhone(phone);
			user.setEmail(email);
			user.setPoint(point);
			user.setCreateDate(createDate);
			
			users.add(user);
		}
		rs.close();
		pstmt.close();
		con.close();
		
		return users;
	}
}

 

package db.demo3;

import java.util.ArrayList;
import java.util.Scanner;

public class UserApp {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		
		UserService service = new UserService();
		
		while (true) {
			try {
				System.out.println("1. 가입 2. 전체 조회 3. 이름 검색 4. 아이디 검색 5. 삭제 6. 경로 변경 0. 종료");
				
				System.out.println("메뉴 선택> ");
				int menu = scanner.nextInt();
				
				if (menu == 1) {
					System.out.println("[회원 가입]");
					System.out.println("아이디 입력> ");
					String id = scanner.next();
					System.out.println("이름 입력> ");
					String name = scanner.next();
					System.out.println("비밀번호 입력> ");
					String pwd = scanner.next();
					System.out.println("전화번호 입력> ");
					String phone = scanner.next();
					System.out.println("이메일 입력> ");
					String email = scanner.next();
					
					UserVO user = new UserVO();
					user.setId(id);
					user.setName(name);
					user.setPwd(pwd);
					user.setPhone(phone);
					user.setEmail(email);
					
					service.addNewUser(user);
					
				} else if (menu == 2) {
					System.out.println("[전체 조회]");
					
					ArrayList<UserVO> users = service.getAllUsers();
					if (users.isEmpty()) {
						System.out.println("조회된 사용자 정보가 없습니다.");
					} else {
						for (UserVO user : users) {
							System.out.println("아이디: " + user.getId());
							System.out.println("이름: " + user.getName());
							System.out.println("연락처: " + user.getPhone());
							System.out.println();
						}
					}
					
				} else if (menu == 3) {
					System.out.println("[이름으로 검색하기]");
					
					System.out.println("검색할 이름 입력> ");
					String name = scanner.next();
					
					ArrayList<UserVO> users = service.searchUsers(name);
					for (UserVO user : users) {
							System.out.println("아이디: " + user.getId());
							System.out.println("이름: " + user.getName());
							System.out.println("연락처: " + user.getPhone());
							System.out.println();
					}
				} else if (menu == 4) {
					System.out.println("[아이디로 검색하기]");
					
					System.out.println("검색할 아이디 입력> ");
					String id = scanner.next();
					
					UserVO user = service.findUserById(id);
					System.out.println("아이디: " + user.getId());
					System.out.println("이름: " + user.getName());
					System.out.println("연락처: " + user.getPhone());
					System.out.println("이메일: " + user.getEmail());
					System.out.println("포인트: " + user.getPoint());
					System.out.println("가입일: " + user.getCreateDate());
					System.out.println();
					
				} else if (menu == 5) {
					System.out.println("[사용자 정보 삭제]");
					
					System.out.println("삭제 대상 아이디 입력> ");
					String id = scanner.next();
					
					service.removeUser(id);
					
				} else if (menu == 6) {
					System.out.println("[사용자 정보 업데이트]");
					
					System.out.println("변경 대상 아이디 입력> ");
					String id = scanner.next();
					System.out.println("새 이름 입력> ");
					String name = scanner.next();
					System.out.println("새 연락처 입력> ");
					String phone = scanner.next();
					System.out.println("새 이메일 입력> ");
					String email = scanner.next();
					
					UserVO user = new UserVO();
					user.setId(id);
					user.setName(name);
					user.setPhone(phone);
					user.setEmail(email);
					
					service.modifyUserInfo(user);
					
				} else if (menu == 0) {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println();
		}
		scanner.close();
	}
}

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package db.demo2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Scanner;

public class BookService {

	Scanner scanner = new Scanner(System.in);
	
	// 모든 책 정보를 조회하는 기능
	public void selectAllBooks() throws Exception {
		/*
		 * 1. SQL 정의
		 * 2. 드라이브 메모리 로딩
		 * 3. Connection 획득
		 * 4. PreparedStatement 획득
		 * (5. ?에 값 설정)
		 * 6. 실행
		 * (7. ResultSet 처리)
		 * 8. 자원 해제 
		 */

		String sql = "select book_no, book_title, book_author, book_publisher, book_price, book_pubdate, book_create_date from books";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			int no = rs.getInt("book_no");
			String title = rs.getString("book_title");
			String author = rs.getString("book_author");
			String publisher = rs.getString("book_publisher");
			int price = rs.getInt("book_price");
			String pubdate = rs.getString("book_pubdate");
			Date createdate = rs.getDate("book_create_date");
			
			System.out.println(no + ", " + author + ", " + publisher + ", " + price + ", " + pubdate + ", " + createdate);
		}
		rs.close();
		pstmt.close();
		conn.close();
	}
	
	// 제목을 전달받아서 그 제목에 해당하는 책 정보를 조회하는 기능
	public void selectBooksByTitle(String keyword) throws Exception {
		String sql = "select book_no, book_title, book_author, book_publisher, book_price, book_pubdate, book_create_date from books where book_title like '%' || ? || '%' ";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, keyword);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			int no = rs.getInt("book_no");
			String title = rs.getString("book_title");
			String author = rs.getString("book_author");
			String publisher = rs.getString("book_publisher");
			int price = rs.getInt("book_price");
			String pubdate = rs.getString("book_pubdate");
			Date createdate = rs.getDate("book_create_date");
			
			System.out.println(no + ", " + title + ", " + author + ", " + publisher + ", " + price + ", " + pubdate + ", " + createdate);
		}
		rs.close();
		pstmt.close();
		conn.close();
		
		
	}
	
	// 책 정보를 전달받아서 db에 저장하는 기능
	public void insertNewBook(int no, String title, String author, String publisher, int price, String pubdate) throws Exception {
		String sql = "insert into books (book_no, book_title, book_author, book_publisher, book_price, book_pubdate) "
				+ " values (?, ?, ?, ?, ?, ?)";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, no);
		pstmt.setString(2, title);
		pstmt.setString(3, author);
		pstmt.setString(4, publisher);
		pstmt.setInt(5, price);
		pstmt.setString(6, pubdate);
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 저장되었습니다.");
		
		pstmt.close();
		conn.close();
		
	}
	
	// 삭제할 책 번호를 전달받아서 DB에서 책 정보를 삭제하는 기능
	public void deleteBookByNo(int no) throws Exception {
		String sql = "delete from books where book_no = ?";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, no);
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 삭제되었습니다.");
		pstmt.close();
		conn.close();
		
	}
	
	// 책 정보를 전달받아서 변경하는 기능
	public void updateBook(int no, String title, String author, String publisher, int price, String pubdate) throws Exception {
		String sql = "update books set book_title = ? , book_author = ?, book_publisher = ?, book_price = ?, book_pubdate = ? where book_no = ?";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, title);
		pstmt.setString(2, author);
		pstmt.setString(3, publisher);
		pstmt.setInt(4, price);
		pstmt.setString(5, pubdate);
		pstmt.setInt(6, no);
		
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 변경되었습니다.");
		
		pstmt.close();
		conn.close();
		
	}
	
}

 

package db.demo2;

import java.util.Scanner;

public class BookApp {

	public static void main(String[] args) throws Exception	{
		
		Scanner scanner = new Scanner(System.in);
		BookService service = new BookService();
		
		while (true) {
			System.out.println("1. 전체 조회 2. 제목 검색 3. 책 등록 4. 책 삭제 5. 책 정보 변경 0. 종료");
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			
			if (selectNo == 1) {
				// 모든 책 정보를 조회해서 출력한다.
				service.selectAllBooks();
				
			} else if (selectNo == 2) {
				// 제목을 입력받아서 제목을 포함하고 있는 책 정보를 조회해서 출력한다.
				System.out.println("조회할 책 제목 입력> ");
				String keyword = scanner.next();
				service.selectBooksByTitle(keyword);
			
			} else if (selectNo == 3) {
				// 번호, 제목, 저자, 출판사, 가격, 출판일을 입력받아서 DB에 저장한다.
				System.out.println("저장할 책 번호 입력>");
				int no = scanner.nextInt();
				System.out.println("저장할 책 제목 입력>");
				String title = scanner.next();
				System.out.println("저장할 책 저자 입력>");
				String author = scanner.next();
				System.out.println("저장할 책 출판사 입력>");
				String publisher= scanner.next();
				System.out.println("저장할 책 가격 입력>");
				int price = scanner.nextInt();
				System.out.println("저장할 책 출판일 입력>");
				String pubdate = scanner.next();

				service.insertNewBook(no, title, author, publisher, price, pubdate);

			} else if (selectNo == 4) {
				// 책 번호를 입력받아서 책 정보를 삭제한다.
				System.out.println("삭제할 책 번호 입력> ");
				int no = scanner.nextInt();
				service.deleteBookByNo(no);
				
			} else if (selectNo == 5) {
				// 수정할 책 번호, 변경할 정보(제목, 저자, 출판사, 가격, 출판일)을 입력받아서
				// 책 번호에 해당하는 책 정보를 변경한다.
				
				System.out.println("변경할 책 번호 입력> ");
				int no = scanner.nextInt();
				System.out.println("변경할 책 제목 입력> ");
				String title = scanner.next();
				System.out.println("변경할 책 저자 입력> ");
				String author = scanner.next();
				System.out.println("변경할 책 출판사 입력> ");
				String publisher = scanner.next();
				System.out.println("변경할 책 가격 입력> ");
				int price = scanner.nextInt();
				System.out.println("변경할 책 출판일 입력> ");
				String pubdate = scanner.next();
				
				service.updateBook(no, title, author, publisher, price, pubdate);
				
			} else if (selectNo == 0) {
				System.out.println("종료");
				break;
			} 
		}
	}
}

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo3  (0) 2019.06.10
demo1  (0) 2019.06.10
package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteDemo {

	public static void main(String[] args) throws Exception {
		String sql = "delete from user_contacts where user_name = ?";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, "ㅁ마ㅁㅁ마");
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 삭제되었습니다.");
		
		pstmt.close();
		connection.close();
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertDemo1 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("주소록 등록 프로그램");
		
		System.out.println("순번입력> ");
		int no = scanner.nextInt();
		System.out.println("이름입력> ");
		String name = scanner.next();
		System.out.println("연락처입력> ");
		String phone = scanner.next();
		
		// 1. JDBC 드라이버 메모리 로딩
		Class.forName("oracle.jdbc.OracleDriver");
		
		// 2. Database와 연결을 유지하는 Connection 객체 획득하기
		String url1 = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "hr";
		String password = "zxcv1234";
		Connection connection = DriverManager.getConnection(url1, user, password);
		
		// 3. 실행할 쿼리 정의
		String sql = "insert into user_contacts"
				+ "(user_no, user_name, user_phone, user_create_date)"
				+ "values"
				+ "(?, ?, ?, sysdate)";
		
		// 4. 쿼리를 데이터베이스로 전송하는 PreparedStatement 객체 획득하기
		PreparedStatement pstmt = connection.prepareStatement(sql);
		
		// 5. PreparedStatement의 setXXX(인덱스, 값) 메소드를 사용해서 ?와 치환될 값 설정하기
		pstmt.setInt(1, no);
		pstmt.setString(2, name);
		pstmt.setString(3, phone);
		
		// 6. 쿼리 실행
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 추가되었습니다.");
		
		// 7. 자원 해제 (필수!, 자원 해제는 역순으로!)
		pstmt.close();
		connection.close();
		
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SelectDemo {

	public static void main(String[] args) throws Exception {
		String sql = "select * from user_contacts";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet rs= pstmt.executeQuery();

		while (rs.next()) {
			int no = rs.getInt("user_no");
			String name = rs.getString("user_name");
			String phone = rs.getString("user_phone");
			
			System.out.println(no + ", " + name + ", " + phone);
			
		}
		rs.close();
		pstmt.close();
		conn.close();
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class UpdateDemo {

	public static void main(String[] args) throws Exception {
		String sql = "update user_contacts "
				+ "set "
				+ "user_name = ?, "
				+ "user_phone = ? "
				+ "where user_no = ? ";
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("수정할 사용자 번호 입력> ");
		int no = scanner.nextInt();
		System.out.println("새 이름 입력> ");
		String name = scanner.next();
		System.out.println("새 연락처 입력> ");
		String phone = scanner.next();
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		pstmt.setString(2, phone);
		pstmt.setInt(3, no); // 3은 열 번호. 5 입력시 부적절한 인덱스라며 에러
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 변경되었습니다.");
		
		pstmt.close();
		conn.close();
		
		
	}
}

 

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
package demo.thread;

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		System.out.println("MyRunnable run 실행 시작 ");
		for (int i=0; i<100; i++) {
			System.out.println("MyRunnable 실행 " + i);
		}
		System.out.println("MyRunnable run 실행 종료 ");
	}
}

 

package demo.thread;

public class MyRunnableApp {

	public static void main(String[] args) {
		System.out.println("메인 메소드 시작");

		MyRunnable my = new MyRunnable();
		Thread t = new Thread(my);
		t.start();
		
		for (int i=0; i<100; i++) {
			System.out.println("메인 메소드 실행 " + i);
		}
		
		System.out.println("메인 메소드 종료");
	}
}

 

package demo.thread;

public class MyThread extends Thread {

	@Override
	public void run() {
		System.out.println("MyThread의 run() 메소드 실행 시작");
		for (int i=0; i<100; i++) {
			System.out.println("MyThread 실행 중 " + i);
		}
		System.out.println("MyThread의 run() 메소드 실행 종료");
		
	}
}

 

package demo.thread;

public class ThreadApp {

	public static void main(String[] args) {
		
		System.out.println("메인 메소드 실행 시작");
		
		MyThread my = new MyThread();
		YourThread your = new YourThread();
		
		my.start();
		your.start();
		
		for (int i=0; i<100; i++) {
			System.out.println("메인 스레드 실행 " + i);
		}
		
		System.out.println("메인 메소드 실행 종료");
	}
}

 

package demo.thread;

public class YourThread extends Thread {

	@Override
	public void run() {
		System.out.println("YourThread의 run() 메소드 실행 시작");
		for (int i=0; i<100; i++) {
			System.out.println("YourThread 실행 중 " + i);
		}
		System.out.println("YourThread의 run() 메소드 실행 종료");
		
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.sync;

public class ATM implements Runnable {

	private long balance = 1000000;
	
	@Override
	public void run() {
		for (int i=0; i<25; i++) {
			출금();
		}
	}
	
	public synchronized void 출금() {
		System.out.println("현재 잔액 : " + balance);
		System.out.println("출금 시작");
		balance -= 10000;
		System.out.println("출금 종료");
		System.out.println("출금 후 잔액 : " + balance);
	}
}

 

package demo.sync;


public class ATMApp {

	public static void main(String[] args) {
		ATM atm = new ATM();
		
		Thread t1 = new Thread(atm);
		Thread t2 = new Thread(atm);
		Thread t3 = new Thread(atm);
		Thread t4 = new Thread(atm);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

 

package demo.sync;

import java.util.ArrayList;
import java.util.Vector;

public class ListRunnable implements Runnable {

	
	@Override
	public void run() {
		ArrayList<String> names = new ArrayList<String>();
		
		for(int i=0; i<100; i++) {
			names.add("홍길동" + i);
		}
		System.out.println(names.size());
	}
}

 

package demo.sync;

public class ListRunnableApp {

	public static void main(String[] args) {
		

		ListRunnable work = new ListRunnable();
		
		Thread t1 = new Thread(work);
		Thread t2 = new Thread(work);
		Thread t3 = new Thread(work);

		t1.start();
		t2.start();
		t3.start();
	
	}
}

'자바 > network' 카테고리의 다른 글

thread  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.store;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class StoreClient {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);              // 사용자의 입력을 받는다.
		
		Socket socket = new Socket("192.168.10.254", 8000);    // 서버에 연결요청을 보낸다.
		
		PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // 서버로 메시지 보낼 때 사용
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		boolean isLogin = false;
		
		while (true) {
			if (!isLogin) {
				System.out.println("1. 가입 2. 로그인 0. 종료");
			} else {
				System.out.println("3. 목록조회 4. 상세조회 5. 장바구니조회 6. 장바구니 담기 7. 내정보 보기 8. 비밀번호 변경 9. 로그아웃 0. 종료");
			}
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			
			if (selectNo == 0) {
				System.out.println("프로그램 종료");
				break;
			} else if (selectNo == 1) {
				// 아이디, 이름, 비밀번호 입력받기
				System.out.println("아이디> ");
				String id = scanner.next();
				System.out.println("비밀번호> ");
				String password = scanner.next();
				System.out.println("이름> ");
				String name = scanner.next();
				
				
				// 입력받은 아이디, 비밀번호, 이름을 서버로 보내기
				out.println("add_user:" + id + ":" + password + ":" + name);
				
				// 서버가 보낸 응답 받기
				// 응답 메시지 화면에 표시하기
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 2) {
				System.out.println("아이디> ");
				String id = scanner.next();
				System.out.println("비밀번호> ");
				String password = scanner.next();

				out.println("login_user:" + id + ":" + password);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
				String[] s = message.split(":");
				if (s[1].equals("success")) {
					isLogin = true;
				}
				
			} else if (selectNo == 3) {
				out.println("view_products");
				
				String message = in.readLine();
				/* Ver1
				String resSubstract = message.substring(18);
				String[] splitted = resSubstract.split(":");
				
				for (int i=0; i < splitted.length; i++) {
				String[] splitted2 = splitted[i].split(",");
					for (int j=0; j<splitted2.length; j++) {
						System.out.println(splitted2[j]);
					}
				}
				*/
				
				
				/* Ver2
				String[] splitted = message.split(":");
				
				for (int i=1; i < splitted.length; i++) {
					String[] splitted2 = splitted[i].split(",");
					for (int j=0; j<splitted2.length; j++) {
						System.out.println(splitted2[j]);
					}
				}
				*/
				
				// Ver3
				String[] a = message.substring(18).split(":");
				for (int i=0; i < a.length; i++) {
					String b[] = a[i].split(",");
					System.out.println("상품번호: " + b[0]);
					System.out.println("상품명: " + b[1]);
					System.out.println("가격: " + b[2]);
				}
				
				
			} else if (selectNo == 4) {
				System.out.println("제품번호 입력>");
				int productNo = scanner.nextInt();
				out.println("detail_product:" + productNo);
				
				String message = in.readLine();
				System.out.println(message);
				
			} else if (selectNo == 5) {
				out.println("view_cart");
				
				String message = in.readLine();
				System.out.println(message);
				
			} else if (selectNo == 6) {
				System.out.println("제품번호 입력>");
				int productNo = scanner.nextInt();
				System.out.println("수량 입력>");
				int amount = scanner.nextInt();
				out.println("add_cart:" + productNo + ":" + amount);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 7) {
				out.println("view_user");
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 8) {
				String oldPassword = scanner.next();
				String newPassword = scanner.next();
				out.println("change_pwd:" + oldPassword + ":" + newPassword);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 9) {
				out.println("logout_user");
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
			}
		}
	}
}
package demo.store;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

	public static void main(String[] args) throws Exception {
		
		ServerSocket server = new ServerSocket(8000);
		ArrayList<User> users = new ArrayList<User>();
		ArrayList<Product> products = new ArrayList<Product>();
		ArrayList<Item> carts = new ArrayList<Item>();
		
		User session = null;
		
		while (true) {
			
			Socket socket = server.accept();
			
			// 스트림 연결
			
			// 클라이언트가 보낸 메세지 읽기
			String text = in.readLine();
			
			String[] values = text.split(":");
			// 메세지 해석 add_user:hong:zxcv1234:홍길동
			//             view_carts
			//             detail_product:100
			if ("add_user".equals(values[0])) {
				// 전달된 값을 User객체 생성해서 담고
				// User객체를 위에서 생성한 ArrayList에 담기
				
				// 클라이언트에 응답보내기
				out.println("res_add_user:success");
				
			} else if ("login_user".equals(values[1])) {
				
			}
		}
	}
}

'자바 > network' 카테고리의 다른 글

thread  (0) 2019.06.10
sync  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.simple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SimpleClient {

	public static void main(String[] args) throws Exception {
		
		// 서버에 연결 요청
		Socket socket = new Socket("192.168.10.254", 8000);
		
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		
		PrintWriter writer = new PrintWriter(out);
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		
		// 서버로 메시지 보내기
		writer.println("");
		writer.flush();
		
		// 서버가 보낸 메시지 읽기
		String message = reader.readLine();
		System.out.println("응답메시지: " + message);
		
		socket.close();
		
	}
}

 

package demo.simple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer {

	public static void main(String[] args) throws Exception {
		
		// 클라이언트의 연결 요청을 처리하는 ServerSocket 생성하기
		ServerSocket server = new ServerSocket(8000);
		System.out.println("서버가 시작되었습니다.");
		
		while (true) {
			// Socket accept()
			// 1. 클라이언트의 연결요청이 있을 때까지 프로그램 실행을 일시정지시킨다.
			// 2. 클라이언트의 연결요청이 접수되면 그 클라이언트와 통신할 때 사용할 Socket객체를 제공한다.
			Socket socket = server.accept();
			
			// Socket으로부터 획득한 스트림을 문자열 전송이 가능하도록 적절한 보조 스트림과 연결시키기
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			PrintWriter writer = new PrintWriter(out);
			
			String name = reader.readLine();
			System.out.println("[" + name + "]이 접속하였습니다");
			
		}
		
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.mall;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MallClient {

	public static void main(String[] args) throws Exception {
		
		Socket socket = new Socket("192.168.10.254", 8000);
		
		PrintWriter out = new PrintWriter(socket.getOutputStream());
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		Scanner scanner = new Scanner(System.in);
		
		while (true) {
			System.out.println("1. 전체 조회 2. 상세 조회 3. 등록 0. 종료");
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			if (selectNo == 1) {
				out.println("ALL_REQ");
				out.flush();
				
			} else if (selectNo == 2) {
				System.out.println("상품번호 입력> ");
				int productNo = scanner.nextInt();
				out.println("DETAIL_REQ:" + productNo);
				out.flush();
				
			} else if (selectNo == 3) {
				System.out.println("상품명 입력> ");
				String name = scanner.next();
				System.out.println("제조사 입력> ");
				String maker = scanner.next();
				System.out.println("상품 종류> ");
				String type = scanner.next();
				System.out.println("상품가격 입력> ");
				int price = scanner.nextInt();
				
				out.println("ADD_REQ:" + name + "," + maker + "," + type + "," + price);
				out.flush();
				
			} else if (selectNo == 0) {
				break;
			}
			String message = in.readLine();
			System.out.println("응답 메시지: " + message);
		}
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
file  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

public class FileServer {

	public static void main(String[] args) throws Exception {
		
		// 클라이언트의 연결 요청을 처리할 ServerSocket 생성
		ServerSocket server = new ServerSocket(8000);
		System.out.println("서버가 시작되었습니다.");
		while (true) {
			// 클라이언트의 연결요청이 접수되면 그 클라이언트와 통신할 소켓을 제공받는다.
			Socket socket = server.accept();
			
			// 소켓으로부터 입력스트림/출력스트림 획득
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			// 위에서 획득한 스트림을 문자열, 정수, 파일데이터를 송수신할 수 있는
			// 보조스트림(DataInpuStream, DataOutputStream)과 연결
			DataInputStream dis = new DataInputStream(in);
			DataOutputStream dos = new DataOutputStream(out);
			
			// 클라이언트가 보낸 문자열, 정수 읽어오기
			String filename = System.currentTimeMillis() + dis.readUTF();
			long filesize = dis.readLong();
			
			// 클라이언트가 보낸 파일을 저장할 스트림 생성하기
			FileOutputStream fos = new FileOutputStream("c:/temp/" + filename);
			System.out.println("["+filename+"] 저장을 시작");
			
			// 클라이언트가 보낸 파일데이터 읽어서 파일로 저장하기
			int readSize = 0;						// 읽어온 파일 데이터를 크기를 저장할 변수
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len=dis.read(buf)) != -1) {		// 1. 스트림으로부터 데이터 읽기
				fos.write(buf, 0, len);				// 2. 파일에 기록하기
				readSize += len;                    // 3. 읽어들인 파일 데이터 크기를 증가시키기
				if (readSize == filesize) {         // 4. 읽어들인 파일의 크기와 파일 사이즈가 일치하면 반복 탈출
					break;
				}
			}
			fos.close();
			System.out.println("["+filename+"] 저장이 완료");
			
			dos.writeUTF("["+filename+"]의 저장이 완료되었습니다.");
			dos.flush();			
		}
	}
}​

 

package demo.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

public class FileClient {

	public static void main(String[] args) throws Exception {
		// 소켓을 생성해서 서버에 연결요청하기
		Socket socket = new Socket("192.168.10.254", 8000);
		
		// 소켓으로부터 입력스트림/출력스트림 획득하기
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		
		// 소켓으로부터 획득한 스트림을 보조스트림과 연결하기
		DataOutputStream dos = new DataOutputStream(out);
		DataInputStream dis = new DataInputStream(in);
	
		File file = new File("c:/temp/suyoung.jpg");
		String filename = file.getName();                // 파일 이름 획득
		long filesize = file.length();                   // 파일 사이즈 획득
		FileInputStream fis = new FileInputStream(file); // 파일 데이터 획득을 위한 입력 스트림 생성
		
		// 서버로 파일명, 파일사이즈, 파일데이터 보내기
		dos.writeUTF(filename);
		dos.writeLong(filesize);
		IOUtils.copy(fis, dos); // FileInputStream으로 읽어서 DataOutputStream으로 복사
		
		// 서버로부터 메시지 받기
		String message = dis.readUTF();
		System.out.println("응답 메시지 : " + message);
		
		socket.close();
		
	}
}

 

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.chat;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ChatClient extends JFrame {

	private JTextArea messageTextArea = new JTextArea();
	private JTextArea inputTextArea = new JTextArea();
	private JButton sendButton = new JButton("전송");
	
	public ChatClient() {
		
		try {
			Socket socket = new Socket("192.168.10.254", 8000);
			
			PrintWriter out = new PrintWriter(socket.getOutputStream());
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			// 수신 전용 작업을 실행하는 스레드 생성
			ChatClientThread cct = new ChatClientThread();
			// 서버가 전송한 메시지를 수신하는 스트림 전달
			cct.setIn(in);
			// 메시지를 표현할 콘트롤 전달
			cct.setMessageTextArea(messageTextArea);
			
			cct.start();
			
			setTitle("심플 채팅");
			setLayout(new BorderLayout());
			
			messageTextArea.setEditable(false);
			
			JPanel bottomPanel = new JPanel(new BorderLayout());
			
			JScrollPane scrollPane = new JScrollPane(inputTextArea);
			inputTextArea.setPreferredSize(new Dimension(0, 50));
			bottomPanel.add(scrollPane, BorderLayout.CENTER);
			bottomPanel.add(sendButton, BorderLayout.EAST);
			
			add(new JScrollPane(messageTextArea), BorderLayout.CENTER);
			add(bottomPanel, BorderLayout.SOUTH);
			
			
			setVisible(true);
			setBounds(200, 200, 500, 700);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			sendButton.addActionListener(e->{
				// 입력된 텍스트를 읽어오기
				String text = inputTextArea.getText();
				// 서버로 텍스트 보내기
				out.println(text);
				out.flush();
				
				// 입력창의 텍스트 지우기
				inputTextArea.setText("");
			});
			
			// 전송버튼 비활성화
			sendButton.setEnabled(false);
			
			inputTextArea.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					// 입력창에 입력된 텍스트를 읽어온다.
					String text = inputTextArea.getText();
					// 텍스트의 길이가 1 이상이면 전송버튼 활성화
					// 입력된 텍스트가 없으면 전송버튼 비활성화
					if (text.length() > 0) {
						sendButton.setEnabled(true);
					} else {
						sendButton.setEnabled(false);
					}
				}
			});
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "서버와 통신 중 오류가 발생하였습니다.", "통신 오류", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
	}
	
	public static void main(String[] args) {
		new ChatClient();
	}
	
}

 

package demo.chat;

import java.io.BufferedReader;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class ChatClientThread extends Thread {

	private JTextArea messageTextArea;
	private BufferedReader in;
	
	//public ChatClientThread(JTextArea messageTextArea, BufferedReader in) {
	//	this.messageTextArea = messageTextArea;
	//	this.in = in;
	//}
	
	public void run() {
		while (true) {
			try {
				// 서버로부터 메시지 수신
				String text = in.readLine();
				
				// 메시지를 채팅창에 표현
				messageTextArea.append(text + "\n");
				messageTextArea.setCaretPosition(messageTextArea.getText().length());
				
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "서버와 연결이 끊어졌습니다", "서버 연결 오류", JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
		}
	}

	public void setMessageTextArea(JTextArea messageTextArea) {
		this.messageTextArea = messageTextArea;
	}

	public void setIn(BufferedReader in) {
		this.in = in;
	}
}

 

package demo.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServer {

	// 서버에 접속한 모든 클라이언트와 통신을 담당하는 스레드(ChatServerThread)를
	// 저장하는 ArrayList객체 생성하기
	private ArrayList<ChatServerThread> threadList = new ArrayList<ChatServerThread>();
	
	public ChatServer() {
		try {
			ServerSocket server = new ServerSocket(8000);
			System.out.println("채팅 서버가 시작됨...");
			
			while (true) {
				try {
					System.out.println("클라이언트의 요청 대기중...");
					// 연결 요청을 수락하고,
					// 연결 요청을 한 클라이언트와 통신하는 소켓 획득하기
					Socket socket = server.accept();
					System.out.println("클라이언트의 연결 완료...");
					
					// 송수신을 담당하는 스레드 만들기
					ChatServerThread thread = new ChatServerThread();
					threadList.add(thread);
					thread.setSocket(socket);
					thread.setThreadList(threadList);
					thread.start();
					
					//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					//PrintWriter out = new PrintWriter(socket.getOutputStream());
					
				} catch (Exception e) {
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new ChatServer();
	}
}

 

package demo.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServerThread extends Thread {

	private ArrayList<ChatServerThread> threadList;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	public void sendMessage(String message) throws Exception {
		out.println(message);
		out.flush();
	}
	
	public void broadcastMessage(String message) throws Exception {
		for (ChatServerThread thread : threadList) {
			thread.sendMessage(message);
		}
	}
	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			
			while (true) {
			
			// 클라이언트가 보낸 메시지 수신하기
			String message = in.readLine();
			
			// 수신된 메시지를 모든 클라이언트에게 보내기
			broadcastMessage(message);
			
			}
			
		} catch (Exception e) {
		}
	}

	public void setThreadList(ArrayList<ChatServerThread> threadList) {
		this.threadList = threadList;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}	
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #news-section p {color: red;}
        #weather-section p {color: green;}
        #footer-section {
            background-color: #444;
            color: white;
            padding: 14px;
        }
    </style>
</head>
<body>
    <h1>div 태그 사용하기</h1>
    <div id="contents-section">
        <div id="news-section">
            <h2>뉴스 속보</h2>
            <p>중앙 HTA 이응수 강사가 워크넷 이벤트 응모에 당첨되었습니다.</p>
            <p>중앙 HTA 박수정 학생이 워크넷 이벤트에 아쉽게 탈락했습니다.</p>
        </div>

        <div id="weather-section">
            <h2>날씨 정보</h2>
            <p>오늘 서울의 날씨는 흐리고 차차 비가 오겠습니다.</p>
            <p>내일 서울의 날씨는 비 온 후 기온이 많이 떨어지겠습니다.</p>
        </div>
    </div>
    
    <div id="footer-section">
        <h3>중앙 HTA 방송국</h3>
        <p>주소: 서울특별시 종로구 봉익동 디아망 빌딩</p>
        <p>전화: 02-1234-5678</p>
    </div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .up {color: red;}
        .down {color: blue;}
    </style>
</head>
<body>
    <h1>span 태그 사용하기</h1>
    
    <h2>주식 현황</h2>
    <p>셀트리온 <span class="up">+0.45%</span></p>
    <p>아시아나 항공 <span class="down">-5.97%</span></p>
    <p>에프로젠 KIC <span class="up">+12.52%</span></p>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .gallery {
            width: 400px;
            height: 400px;
        }
        .thumbnail {
            width: 120px;
            height: 120px;
            opacity: 0.3;
        }
        .highlight {
            opacity: 1;
        }
    </style>
</head>
<body>
    <h1>id와 class 속성 사용하기</h1>
    
    <h2>이미지 갤러리</h2>
    
    <div id="img-gallery-box">
        <img src="images/Chrysanthemum.jpg" class="gallery">
    </div>
    
    <div id="img-thumbnail-box">
        <img src="images/Chrysanthemum.jpg" class="thumbnail highlight">
        <img src="images/Desert.jpg" class="thumbnail">
        <img src="images/Hydrangeas.jpg" class="thumbnail">
        <img src="images/Jellyfish.jpg" class="thumbnail">
        <img src="images/Koala.jpg" class="thumbnail">
        <img src="images/Lighthouse.jpg" class="thumbnail">
        <img src="images/Penguins.jpg" class="thumbnail">
        <img src="images/Tulips.jpg" class="thumbnail">
    </div>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script>
        $(".thumbnail").click(function() {
            var imgPath = $(this).attr('src');
            $('.gallery:first').attr('src', imgPath);
            
            $('.thumbnail').siblings().removeClass("highlight");
            $(this).addClass('highlight');
        })
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>폼 요소 연습하기</h1>
    
    <h2>input 태그 연습하기</h2>
    <form>
        <label>숨김필드</label><input type="hidden" /><br />
        <label>이름</label><input type="text" /><br />
        <label>비밀번호</label><input type="password" /><br/>
        <label>생일</label><input type="date" /><br />
        <label>나이</label><input type="number" /><br />
        <label>프로필사진</label><input type="file" /><br />
        <label>성별</label><input type="radio" />남<input type="radio" />여<br />
        <label>관심분야</label><input type="checkbox" />영화
                              <input type="checkbox" />미술
                              <input type="checkbox" />운동
                              <input type="checkbox" />음악<br />
        <input type="submit" />
        <input type="reset" />
    </form>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>input 태그의 주요 속성 연습하기</h1>
    
    <form action="register.jsp">
        <label>value 속성</label><input type="text" name="nickname" value="홍길동" /><br />
        <label>placeholder 속성</label><input type="text" name="username" placeholder="이름을 입력하세요" /><br />
        <label>maxlength 속성</label><input type="text" name="address" maxlength=6 /><br />
        <label>readonly 속성</label><input type="text" name="phone" value="010-111-1111" readonly="readonly"/><br />
        <label>disabled 속성</label><input type="text" name="school" value="서울대학교" disabled="disabled"/><br />
        <label>name 속성</label><input type="text" name="userid" placeholder="아이디를 입력하세요" /><br />
        <label>name 속성</label><input type="date" name="birth" placeholder="생일을 입력하세요" /><br />
        
        <label>name 속성</label><input type="radio" name="gender" value="male" checked="checked">남
                                <input type="radio" name="gender" value="female">여<br>
        <label>name 속성</label><input type="radio" name="career" value="0">신입
                                <input type="radio" name="career" value="3">3년차 이상
                                <input type="radio" name="career" value="5">5년차 이상
                                <input type="radio" name="career" value="7">7년차 이상<br>
                                
        <label>name 속성</label><input type="checkbox" name="tech" value="java" checked="checked">java
                               <input type="checkbox" name="tech" value="script" checked="checked">script
                               <input type="checkbox" name="tech" value="python">python
                               <input type="checkbox" name="tech" value="c">c
                               <input type="checkbox" name="tech" value="SQL">SQL
                               <input type="checkbox" name="tech" value="design">design
        <input type="submit">
    </form>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>select 태그 연습하기</h1>
    
    <form action="register.jsp">
        <label>학력</label>
        <select name="school" id="">
            <option value="E">초등학교 졸업</option>
            <option value="M">중학교 졸업</option>
            <option value="H">고등학교 졸업</option>
            <option value="U" selected="selected">대학교 졸업</option>
            <option value="G">대학원 졸업</option>
        </select> <br>
        
        <label>전공</label>
        <select name="major">
            <optgroup label="인문대학">
                <option value="KQ">국어국문학과</option>
                <option value="ED">영어영문학과</option>
                <option value="BD">신문방송학과</option>
            </optgroup>
            <optgroup label="공과대학">
                <option value="MD">기계공학과</option>
                <option value="ELD">전기공학과</option>
                <option value="ETD">전자공학과</option>
                <option value="ENT">환경공학과</option>
                
            </optgroup> <br>
            <optgroup label="자연대학">
                <option value="MMD">수학과</option>
                <option value="PD">물리학과</option>
                <option value="CD">화학과</option>
                <option value="BYD">생물학과</option>
            </optgroup>
        </select ><br>
        <label>이메일</label><input type="text" name="email1">@
        <select name="email2">
            <option value="" disabled selected>선택하세요</option>
            <option value="daum.net">다음</option>
            <option value="naver.com">네이버</option>
            <option value="google.com">구글</option>
            <option value="nate.com">네이트</option>
            <option value="">직접 입력</option>
        </select>
        <input type="submit" value="제출하기"/>
    </form>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>textarea 태그 연습하기</h1>
    
    <form>
        <label>사용자명</label>
        <input type="text" name="username"> <br>
        <label>자기소개</label>
        <textarea name="profile" rows="5" cols="60"></textarea><br>
        <input type="submit">
    </form>
    
    <hr>
    
    <h2>textarea에 값을 미리 설정하기</h2>
    <form>
        <label>사용자명</label>
        <input type="text" name="username" value="홍길동"> <br>
        <label>자기소개</label>
        <textarea name="profile" rows="5" cols="60">나는 행복합니다~.</textarea><br>
        <input type="submit">
    </form>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .first {
            color: red;
        }
        .main span {
            color: blue;
        }
        .enter span {
            color: yellow;
        }
    </style>
</head>
<body>
    <h1>뉴스</h1>
    
    <h2>주요 뉴스</h2>
    <ul class="main">
        <li class="first">한국당 좌파 야합 반발, 정치투쟁 예고</li>
        <li><span>세월호 CCTV</span> 조작, 특조위에서 밝힌다.</li>
        <li><span>조선업 회복</span> 앞당긴다.</li>
    </ul>
    
    <h2>연예</h2>
    <ul class="enter">
        <li class="first">어벤저스 엔드게임 개봉 4시간만에 100만 돌파</li>
        <li>김상혁 피규어 <span>3000만 원치</span> 수집</li>
        <li>랜선라이프 <span>이영자 구독자 수</span> 보면 열심히 하게 되</li>
    </ul>
    
    <h2>스포츠</h2>
    <ul class="sports">
        <li class="first">3위 굳건 토트넘, 자력 UCL 유력해졌다</li>
        <li>에릭센 팬 서비스도 월드 클래스</li>
        <li>영국 현지, 이제 손흥민의 시대</li>
    </ul>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        label {
        font-weight:bold;
        }
    </style>
</head>
<body>
    <h1>회원가입 폼</h1>
    
    <label>아이디</label><input type="text" name="id" placeholder="아이디 입력하세요."><br>
    <label>이름</label><input type="text" name="name" placeholder="이름 입력하세요."><br>
    <label>비밀번호</label><input type="password" name="pw" placeholder="비밀번호 입력하세요."><br>
    <label>이메일</label><input type="text" name="mail1" placeholder="이메일 입력하세요.">@
    <select name="mail2">
        <option value="" disabled selected>선택하세요</option>
        <option value="naver.com">네이버</option>
        <option value="daum.net">다음</option>
    </select><br>
    <label>생일</label><input type="date"><br>
    <label>자기소개</label><textarea name="profile" cols="100" rows="3" placeholder="자기소개를 300자 이내로 작성하세요."></textarea><br>
    <input type="submit">
</body>
</html>

 

'html' 카테고리의 다른 글

0422  (0) 2019.06.17
sample14~18(link, text, element)  (0) 2019.06.09
sample8~13 (table, img)  (0) 2019.06.09
sample1~7(title, text, list, table)  (0) 2019.06.09

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>링크 만들기</h1>
    <!--
        a 태그를 사용하면 하이퍼링크를 만들 수 있다.
        
        <a href="연결할 문서의 주소" target="링크내용이 표시될 위치">링크이름</a>
        
        target의 속성값
            _blank: 링크된 문서가 새로운 창이나 새로운 탭에서 열린다.
            _self: 링크된 문서가 현재 창에서 열린다(기본값)
    -->
    <h2>프로젝트 내의 문서에 링크 연결하기</h2>
       <p>
        <a href="http://www.daum.net" target="_blank">다음</a>
        <a href="http://www.naver.com">네이버</a>
        <a href="http://www.google.com">구글</a>
    </p>
</body>
</html>


 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>한 페이지 내에서 특정 위치로 이동하는 링크 만들기</h1>
    
    <!--
        페이지의 내용이 긴 경우
        각각의 섹션마다 id를 부여하고,
        a태그에서 href의 속성값으로 id값을 지정하면
        해당 섹션 부분으로 스크롤 점프할 수 있다.
        <a href=#아이디">링크명</a>
    -->
    <h2>링크</h2>
     <p id="menu">
        <a href="#p1">IT</a>
        <a href="#p2">연예</a>
        <a href="#p3">스포츠</a>
    </p>
    
    <p id="p1">
        23일 ...중략... 알려졌다.<a href="#menu">top</a>
    </p>
    <p id="p2">
        22일 ...중략... 덧붙였다.<a href="#menu">top</a>
    </p>
    <p id="p3">
        다음은 ...중략... 했다. <a href="#menu">top</a>
    </p>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #444;
        }
        li {
            float: left;
        }
        li a {
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }
        li a:hover {
            background-color: #111;
        }
    </style>
</head>
<body>
    <ul>
        <li><a href="">홈</a></li>
        <li><a href="">정규과정</a></li>
        <li><a href="">콘텐츠</a></li>
        <li><a href="">취업지원</a></li>
        <li><a href="">학원소개</a></li>
    </ul>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>텍스트를 강조하는 태그</h1>
    
    <p>
    해외의 ...중략... <strong>어디든 마다치 않고 발길을 옮기고 있다.</strong> 서울·경기·인천 등 ...중략... 19일 <em>서울 여의도</em>에서 만난 그는 ...중략... 말했다.
    </p>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        h1, h2, p, ul, li {
            background-color: yellow;
            width: 800px;
            text-align: right;
        }
        strong, em, b, i {
        /* display: block; 인라인 엘리먼트도 블록 엘리먼트로 변경할 수 있다. */
            background-color: lightgreen;
            width: 300px; /* 효과 없음. 너비 조절 불가 */
        }
    </style>
</head>
<body>
    <h1>블록 엘리먼트와 인라인 엘리먼트</h1>
    
    <h2>블록 엘리먼트</h2>
    <p>나도 블록엘리먼트야</p>
    <ul>
        <li>나도 블록 엘리먼트야</li>
        <li>나도 블록 엘리먼트야</li>
    </ul>
    <h2>인라인 엘리먼트</h2>
    <p>
        <strong>인라인 엘리먼트</strong>로 감싸진 콘텐츠는 그 콘텐츠의 <em>너비만큼만 영역</em>을 차지한다.
        
    </p>
</body>
</html>

'html' 카테고리의 다른 글

0422  (0) 2019.06.17
sample19~27(div, span, id, class, form 등)  (0) 2019.06.09
sample8~13 (table, img)  (0) 2019.06.09
sample1~7(title, text, list, table)  (0) 2019.06.09

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>중앙HTA 신입 사원 모집 공고</h1>
    <p>IT 기획, 편집 부서에서 함께 할 신입 사원을 모집합니다.</p>
    <h2>모집 내용</h2>
    <ul>
        <li>모집 직군 : 편집, 기획 부서</li>
        <li>직무 내용 : 도서 프로듀싱 업무(신입 지원 가능)
            <ul>
                <li>도서 기획, 편집</li>
                <li>도서 홍보, 독자 소통</li>
            </ul>
        </li>
        <li>접수 마감일 : 2019년 4월 30일</li>
    </ul>
        
    <p>자세한 내용은 모집 공고 게시판을 참고하시기 바랍니다.</p>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        table, th, td {
            border:1px solid black; /* 테두리: 1픽셀 실선 검정색 */
            border-collapse: collapse; /* 경계 없애기 */
        }
        th, td {
            padding: 15px; /* 테두리와 콘텐츠 사이 간격을 15px로 설정 */
        }
        td {
            text-align: center;
        }
        tr:nth-child(2n) {
            background-color: #eee;
        }
    </style>
</head>
<body>
    <h1>주요 SNS 사이트 이용자 비율</h1>
    <p>주요 SNS 사이트의 서비스 별 이용률을 조사하였습니다.</p>

    <h2>주요 SNS 사이트 서비스별 이용률(%)</h2>
    <table style="width: 100%;">
        <tr>
            <th></th>
            <th>페이스북</th>
            <th>카카오스토리</th>
            <th>밴드</th> 
            <th>인스타그램</th>
            <th>트위터</th>
        </tr>
        <tr>
            <td>2017년</td>
            <td>77.7</td>
            <td>58.3</td>
            <td>32.5</td>
            <td>16.7</td>
            <td>22.1</td>
        </tr>
        <tr>
            <td>2018년</td>
            <td>23.7</td>
            <td>51.0</td>
            <td>40.1</td>
            <td>28.1</td>
            <td>14.5</td>
        </tr>
    </table>
    <h3>분석 내용</h3>
    <ul>
        <li>페이스북은 개인정보 유출사고 후 이용률이 급감함</li>
        <li>인스타그램 이용률이 증가하면서 트위터의 이용률이 감소함</li>
        <li>국내 SNS 이용률은 큰 변동 없음</li>
    </ul>
    
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>표의 칸 병합하기</h1>
    
    <h2>가로 방향 칸 병합하기</h2>
    <table border = "1" style="width: 100%;">
        <tr>
            <td>1</td>
            <td>1</td>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr>
            <td colspan="4">1</td>
        </tr>
        <tr>
            <td colspan="2">1</td>
            <td colspan="2">1</td>
        </tr>
        <tr>
            <td colspan="1">1</td>
            <td colspan="3">1</td>
        </tr>
        <tr>
            <td colspan="3">1</td>
            <td colspan="1">1</td>
        </tr>
    </table>
    
    <h2>세로 방향 칸 병합하기</h2>
    <table border="1" style="width: :100%;">
        <tr>
            <td>1</td>
            <td>1</td>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr>
            <td rowspan="2">1</td>
            <td>1</td>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr>
            <td>1</td>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr>
            <td rowspan="3">1</td>
            <td>1</td>
            <td rowspan="3">1</td>
            <td>1</td>
        </tr>
        <tr>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr>
            <td>1</td>
            <td>1</td>
        </tr>
    </table>
    <h2>가로/세로 방향 칸 병합하기</h2>
    <table border="1" style="100%;">
        <tr>
            <td>구분</td>
            <td colspan="2">상반기</td>
            <td colspan="2">하반기</td>
        </tr>
        <tr>
            <td rowspan="3">영업1팀</td>
            <td colspan="2">매입/매출 현황</td>
            <td colspan="2">매입/매출 현황</td>
        </tr>
        <tr>
            <td>매입</td>
            <td>10억</td>
            <td>매입</td>
            <td>15억</td>
        </tr>
        <tr>
            <td>매출</td>
            <td>20억</td>
            <td>매출</td>
            <td>17억</td>
        </tr> 
        <tr>
            <td colspan="1">비고</td>
            <td colspan="4">상반기에 비해서 하반기의 실적이 감소되었음</td>
        </tr>       
    </table>    
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <table border="1" style="width: 100%;">
        <tr>
            <td colspan="1">이름</td>
            <td colspan="1">홍길동</td>
            <td colspan="1">연락처</td>
            <td colspan="1">010-111-1111</td>
        </tr>
        <tr>
            <td colspan="1">주소</td>
            <td colspan="3">서울 종로구</td>
        </tr>
        <tr>
            <td colspan="1">이메일</td>
            <td colspan="3">hong@gmail.com</td>
        </tr>
    </table>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        thead th {color: red;}
    </style>
</head>
<body>
    <h1>표의 구조 정의하기</h1>
    
    <p>
        thead,tbody,tfoot 태그를 사용하면
        표의 제목, 표의 본문, 표의 요약부를 구성할 수 있다.
    </p>
    
    <table border="1" style="width: 100%;">
        <caption>
            현재 예약 가능한 방 안내
        </caption>
           <thead>
            <tr>
            <th>숙소명</th>
            <th>방 개수</th>
            <th>가격</th>
            </tr>
        </thead>
        
        <tbody>
            <tr>
            <th>개나리방</th>
            <td>1개</td>
            <td>100만 원</td>
        </tr>
        <tr>
            <th>벚꽃방</th>
            <td>4개</td>
            <td>250만 원</td>
        </tr>
        <tr>
            <th>진달래방</th>
            <td>4방(욕실 2개)</td>
            <td>380만 원</td>
        </tr>
        </tbody>
        
        <tfoot>
            <tr>
                <th>창고</th>
                <td colspan="2">모든 요금은 2일 1박 기준(인원 추가 시 1인당 50만 원 추가)</td>
            </tr>
        </tfoot>
        
    </table>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        img {
            opacity: 0.5;
        }
        img:hover {
            opacity: 1;
        }
    </style>
</head>
<body>
    <h1>이미지 표시하기</h1>
    
    <!--
        img 태그를 사용하면 이미지를 표시할 수 있다.
        <img src="이미지 파일의 경로" alt="이미지에 대한 설명"
             width="이미지의 폭" height="이미지의 높이"/>
    -->
    <h2>프로젝트 내의 리소스 사용</h2>
    <p>
        <img src="images/Koala.jpg" width="200" alt="코알라 사진"/>
        <img src="images/Penguins.jpg" width="200" alt="펭귄 사진"/>
        <img src="images/Hydrangeas.jpg" width="200" height="200" alt="수국 사진"/>
    </p>
    
    <h2>외부 리소스 사용</h2>
    <p>
        <img src="http://image.iacstatic.co.kr/allkill/item/2019/04/20190419140853551r.jpg" alt="지리산 뱀사골 토종 벌집꿀" />
    </p>
</body>
</html>

'html' 카테고리의 다른 글

0422  (0) 2019.06.17
sample19~27(div, span, id, class, form 등)  (0) 2019.06.09
sample14~18(link, text, element)  (0) 2019.06.09
sample1~7(title, text, list, table)  (0) 2019.06.09

+ Recent posts