티스토리 뷰
1.pollWrite.jsp 소스코드
<%@page import="kr.koreait.olinePoll.PollWrite"%>
<%@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>Insert title here</title>
</head>
<body>
<%
//pollRead.jsp 에서 넘어오는 파일을 받음
String temp=request.getParameter("poll");
//pollRead.jsp 에서 아무것도 넘어오지 않았거나(null) 공백이 들어와서 내용이 없이 왔다면 처리하지 않는다
if(temp!=null && temp.trim().length()>0){
//넘어온 내용이 숫자가 아니라면 처리 하지않는다
try{
int p = Integer.parseInt(temp);
//투표한 항목의 득표수를 증가시키기 위해서 파일에 저장된 투표내용을 읽어옴
String filename=application.getRealPath("/")+"poll.txt";
ArrayList<String> poll = PollRead.pollRead(filename);
int itemCount =(poll.size()-1)/2;
//증가시킬 득표수 계산
int index= itemCount+p;
//확인작업
// out.println("증가시킬 위치 :"+index);
//ArrayList에서 증가시킬 위치에 해당되는 값을 얻어온다
int result=Integer.parseInt(poll.get(index));
//얻어온 득표수 result를 1증가시켜 다시 ArrayList에 저장
poll.set(index, result+1+"");
//poll.set(int,String)이므로 String을 맞추기위해서 ""사용
//ArrayList의 내용을 파일에 저장하는 메소드 호출
PollWrite.pollWrite(poll, filename);
( ※ PollWrite.java 사용 )
// 결과 보기 페이지에 넘겨줌
response.sendRedirect("pollResult.jsp");
}catch(Exception e){
out.println("<script>");
out.println("alert('잘못된 데이터 입니다')");
out.println("location.href='pollRead.jsp'");
out.println("</script>");
}
}else{
out.println("<script>");
out.println("alert('데이터가 넘어오지 않았습니다')");
out.println("location.href='pollRead.jsp'");
out.println("</script>");
}
%>
</body>
</html>
2.PollWrite.java 사용
package kr.koreait.olinePoll;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class PollWrite {
//투표 내용이 저장된 ArrayList의 저장할 파일명을 넘겨받고
//ArrayList 의 내용을 파일에 저장하는 메서드 생성
public static void pollWrite(ArrayList<String> poll,String filename){
PrintWriter pw=null;
// 파일출력에 사용할 객체 사용
try {
pw=new PrintWriter(filename);
for(String str : poll){
pw.write(str+"\r\n");
// \r : (carriage return) 커서를 줄의 맨 앞으로 보낸다
// \n : (new line) 줄을 바꾼다
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try{if(pw!=null) pw.close();}catch (Exception e) {}
}
}
}
'Programing > JSP' 카테고리의 다른 글
JSP - [주민등록번호 유효성 검사 프로젝트 ] (0) | 2017.06.21 |
---|---|
JSP - [온라인 투표 프로젝트 4 - pollResult.jsp ] (0) | 2017.06.14 |
JSP1-[온라인 투표 프로젝트 2 - 디자인 CSS] (0) | 2017.06.14 |
JSP1-[온라인 투표 프로젝트 1 - pollRead.jsp/pollRead.jsp] (0) | 2017.06.12 |
JSP 기본 세팅 (0) | 2017.06.07 |