티스토리 뷰
1) Dynamic Web Project --onlinePoll 생성
2) olinePoll --> WebContent --> File --> poll.txt 생성
3) 소스코드
<%@page import="kr.koreait.olinePoll.PollRead"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>온라인 투표 </title>
</head>
<body>
<%
//getRealPath --> 원페이지에 구동되는 root가 컴퓨터에 위치한 실제 경로를 읽어옴
//실제 경로 읽어옴
String filename=application.getRealPath("/")+"poll.txt";
//투표내용이 저장된 텍스트 파일을 읽어와 ArrayList에 저장 (java 파일 이용)
ArrayList<String> poll=PollRead.PollRead(filename);
--------------------------------------------------
java파일
※ java Resources ---> sc --> package --> kr.koreait.olinePoll 생성 --> class--> PollRead 생성
package kr.koreait.olinePoll;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class PollRead {
// 투표내용 텍스트 읽어와서 ArrayList에 저장후 리턴 메서드
public static ArrayList<String> pollRead(String filename){
//투표내용을 저장할 ArrayList 선언
ArrayList<String> poll = null;
//파일에서 읽어드릴 스캐너 선언
Scanner sc= null;
try{
//파일에서 읽어드릴 스캐너 객체 생성
sc=new Scanner(new File(filename));
//투표 내용을 저장할 ArrayList 객체 생성
poll= new ArrayList<>();
//파일에서 더이상 얻어질 것이 없어질 때 까지 반복해서 데이터를 얻음
//hasNextLine --> 스캐너에 다음 읽을 줄이 있으면 true/ 없으면 false
while(sc.hasNextLine()){
//텍스트 파일에서 한줄 읽음 trim() : 여백 없앰
String str = sc.nextLine().trim();
// ArrayList 에 저장 (빈줄은 저장 하지않는다 )
if(str.length()>0){
//읽어온 내용을 ArrayList 에 저장
poll.add(str);
}//if end
}//while end
}catch(Exception e){
e.printStackTrace();
}finally {
//scanner 닫음
try{if(sc!=null) sc.close();}catch(Exception e){}
}
return poll;
}
}//class end
---------------------------------------------------
// 전체 내용 출력
for(String str : poll){
out.println(str +"<br/>");
}
// 투표 항목수를 출력
out.println("전체 라인 수 :"+poll.size()+"<br/>");
int itemCount=(poll.size()-1)/2;
out.println("투표 항목 수 :"+itemCount+"<br/>");
%>
<form action="pollWriter.jsp" method="post">
<table width="500" align="center" border="1">
<tr> // 줄을 나타냄
<th><%=poll.get(0) %></th> // th : 맨 위 제목
</tr> // 줄 마감
<%
for(int i=1;i<=itemCount;i++){
out.println("<tr>");
out.println("<td><input type='radio'name= 'poll' value=''/>"+poll.get(i)+"</td>");
out.println("</tr>");
}
%>
<tr>
<td>
<input type="submit" value="투표하기"/>
<input type="button" value="결과보기"/>
</td>
</tr>
</table>
</form>
</body>
</html>
'Programing > JSP' 카테고리의 다른 글
JSP - [주민등록번호 유효성 검사 프로젝트 ] (0) | 2017.06.21 |
---|---|
JSP - [온라인 투표 프로젝트 4 - pollResult.jsp ] (0) | 2017.06.14 |
JSP1-[온라인 투표 프로젝트 3 - pollWrite.jsp/pollWrite.java] (0) | 2017.06.14 |
JSP1-[온라인 투표 프로젝트 2 - 디자인 CSS] (0) | 2017.06.14 |
JSP 기본 세팅 (0) | 2017.06.07 |