-개발환경-
IDE : Eclipse IDE for Enterprise Java Developers ver-2020-06 (4.16.0) Tomcat : Tomcat v8.0 Server Java : java 8 |
-poll.jsp-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<%@ page import="com.koreait.onLinePoll.PollRead"%>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>투표하기</title>
</head>
<body>
<%
String filepath=application.getRealPath("/")+"poll.txt"; // "/"는 웹서비스가 실행되는 web root(최상위 경로)를 의미한다.
ArrayList<String> poll = PollRead.pollread(filepath);
int itemCount = (poll.size() -1 ) /2 ;
%>
<form action="pollWrite.jsp" method="get">
<!-- border=테두리 , cellpadding :안여백 , cellspacing : 셀간격 . align : 표위치 정렬-->
<table width="500" border="1" cellpadding="5" cellspacing="0" align="center">
<tr height="50"><!-- 한 행을 의미 -->
<th>
<%=poll.get(0)%> <!-- 간단한표현식에 이용 -->
</th>
</tr>
<%
for (int i=1;i<=itemCount;i++){
%>
<tr height="50">
<td>
<input type='radio' name='poll' value='<%=i%>'/><%=poll.get(i) %>
</td>
</tr>
<%
}
%>
<tr height="50">
<td align="center">
<input type="submit" value="투표하기"/>
<input type="button" value="결과보기" onclick="location.href='pollResult.jsp'"/> <!-- html event인 onclick -->
</td>
</tr>
</table>
</form>
</body>
</html>
|
cs |
-Description
17 : 투표 목록 수
21 : method를 post방식으로 하면 데이터를 숨겨서 다른 파일에 전달. get방식으로하면 인터넷주소로 데이터 전달(보안취약)
25 : border :테두리두깨, cellpadding :안여백 , cellspacing : 셀간격 . align : 표위치 정렬방법지정
26 : <tr></tr> 한 행을 의미
28 : <%= => 간단한 표현법 내부에는 출력할 내용이 들어감 . 여기선 '코로나가 언제 종식될까요?''
33~42 : 투표항목의 갯수만큼 반복하며 radio 버튼과 투표 항목을 출력한다
38 : name이 poll인 라디오 버튼들을 구현. 고유 value들은 1부터 시작하는 정수
47 : 인풋타입인 submit가 실행될 시 , form 태그가 수행됨
48 : html event 인 onclick 으로 인하여 클릭될 시 pollResult.jsp로 페이지이동
-PollRead.java-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package com.koreait.onLinePoll;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class PollRead {
public static ArrayList<String> pollread(String filePath){
ArrayList<String> text=null;
Scanner scanner;
String memo="";
try {
text= new ArrayList<String>();
scanner = new Scanner(new File(filePath));
while (scanner.hasNextLine()) {
String str = scanner.nextLine().trim();
if (str.length() > 0) {
text.add(str);
}
}
} catch (FileNotFoundException e) {
System.out.println("파일을 찾을수 없습니다");
}
return text;
}
}
|
cs |
-Description
17 : 파일 객체를 인자로 scanner객체 생성
18 : scanner.hasNextLine() 는 scanner.nextLine() 와 주로같이 쓰이며 ,
scanner.hasNextLine() 는 다음줄이 있는지 검사.
scanner.nextLine() 은 다음 한 줄을 반환함
21 : 따온 한줄한줄을 text ArrayList에 넣어줌
27 : text ArrayList 반환
문장의 마지막에 scanner.close() 는 써도 안써도 무관
-pollWrite.java-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package com.koreait.onLinePoll;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class PollWrite {
public static void pollWrite(String filepath,ArrayList<String> poll) {
PrintWriter printWriter=null;
try {
printWriter=new PrintWriter(filepath);
for(int i=0;i<poll.size();i++) {
printWriter.write(poll.get(i)+"\r\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(printWriter!=null)
printWriter.close();
}
}
}
|
cs |
-Description
10 : 파일에 내용을 쓰기위해 PrintWriter 참조변수 선언
12 : 파일경로+파일이름을 토대로 PrintWriter 객체생성
14 : printWriter.write로 poll ArrayList의 내용을 한줄씩 복제 ,
Java로 줄바꿈을 파일출력시 윈도우에선 "\r\n" 을 써야 정상적 개행이 이루어짐
유닉스(리눅스)계열 에선 "\n"
20~21 : 파일출력(저장) 시 , 파일내용을 가져오는 것과 달리 꼭 닫아줘야함,
닫지 않는다면 저장또한 이뤄지지 않음
-pollWrite.jsp-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<%@page import="com.koreait.onLinePoll.PollWrite"%>
<%@ page import="com.koreait.onLinePoll.PollRead"%>
<%@ page import="java.util.*" %>
<%@ 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>
<%
request.setCharacterEncoding("UTF-8");
String temp= request.getParameter("poll");//'1'~ 범위임
//투표데이터가 넘어왔나 ( null 이나 공백이 아닌가) =>반드시 null먼저 검사
if(temp!=null && temp.trim().length()>0){
try{
int result =Integer.valueOf(temp);
int itemCount=0;
String filepath=application.getRealPath("/")+"poll.txt"; // "/"는 웹서비스가 실행되는 web root(최상위 경로)를 의미한다.
ArrayList<String> poll = PollRead.pollread(filepath);
if(poll!=null){
itemCount=(poll.size()-1)/2;
}else{
out.println("<script>");//자바스크립트 쓰겟다는것
out.println("alert('투표가 진행되지 않았습니다!')");
out.println("location.href='poll.jsp'");//특정페이지로 쏴줌
out.println("</script>");//자바스크립트 쓰겟다는것
}
if(result>=1 && result<=itemCount){
int value=Integer.valueOf(poll.get(result+itemCount));
poll.set(result+itemCount,value+1+"");
PollWrite.pollWrite(filepath, poll);
response.sendRedirect("pollResult.jsp");
}else{
out.println("<script>");//자바스크립트 쓰겟다는것
out.println("alert('범위값이 잘못되었습니다!')");
out.println("location.href='poll.jsp'");//특정페이지로 쏴줌
out.println("</script>");//자바스크립트 쓰겟다는것
}
}
catch (Exception e){
out.println("<script>");//자바스크립트 쓰겟다는것
out.println("alert('숫자가 아닙니다!')");
out.println("location.href='poll.jsp'");//특정페이지로 쏴줌
out.println("</script>");//자바스크립트 쓰겟다는것
}
}else{
out.println("<script>");//자바스크립트 쓰겟다는것
out.println("alert('투표하세요~~~')");
out.println("location.href='poll.jsp'");//특정페이지로 쏴줌
out.println("</script>");//자바스크립트 쓰겟다는것
}
%>
</body>
</html>
|
cs |
-Description
15 : post 방식으로 데이터가 넘어올 때 한글 깨짐을 방지
16 : request.getParameter("poll") 을 통해 poll.jsp-form태그내부의
name="poll"인 라디오타입에서 선택된 value를 가져옴
21 : poll.jsp에서 넘어온 값을 정수로 저장
23 : "/"는 웹서비스가 실행되는 web root(최상위 경로)를 의미한다.
24 : 기존 poll.txt에 저장되어있는 값을 불러옴
34~35 : result에 매칭되는 값을 하나 증가시켜준 후 poll ArrayList에 다시 저장.
37 : poll ArrayList 내용을 파일에 저장
39 : response.sendRedirect("pollResult.jsp");로 바로 투표 결과를 보여준다.
41~44 : javascript태그 내부에 자바스크립트 문법작성
42 : 경고창
43 : location.href='poll.jsp' 특정 페이지로 쏴주는 자바스크립트 명령어
투표 선택창으로 돌아감
-pollResult.jsp-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.koreait.onLinePoll.PollRead"%>
<%@page import="java.util.Scanner"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- 일정 시간이 경과되면 특정 웹 사이트로 이동하기 -->
<meta http-equiv="refresh" content="1; url='?'"/>
<title>Insert title here</title>
</head>
<body>
<%
String filepath= application.getRealPath("/")+"poll.txt";
ArrayList<String> poll= PollRead.pollread(filepath);
int itemCount= (poll.size()-1)/2;
int sum=0;
for(int i=itemCount+1;i<poll.size();i++)
sum+= Integer.valueOf(poll.get(i));
DecimalFormat df1=new DecimalFormat("#,##0표");
DecimalFormat df2=new DecimalFormat("0.0%");
%>
<table width="500" border="1" cellpadding="5" cellspacing="0" align="center">
<tr height="50">
<th colspan="2"><!-- colspan="2" 2칸을 합치겠다. -->
<%=poll.get(0) %>
</th>
</tr>
<%
for (int i=1;i<=itemCount;i++){
int pyo = Integer.valueOf(poll.get(i+itemCount));
double per= pyo/(double)sum;
%>
<tr height="50">
<td width="150">
<%=poll.get(i) %>(<%=df1.format(pyo) %>)
</td>
<td width="350"> <!-- <hr/> 태그로 막대그래프 효과를 낸다 -->
<hr color="#FA58F4" size="20" width="<%=350*per %>" align="left"/>
</td>
</tr>
<%
}
%>
<tr height="50">
<td align="center" colspan="2">
<input type="button" value="투표하기로 가기" onclick="location.href='poll.jsp'">
</td>
</tr>
</table>
</body>
</html>
|
cs |
-Description
14 : 1초후 갱신, ?는 자기 자신사이트로 갱신
http-equiv 은 기본언어 , 문자셋 , 기본 스타일 시트를 설정 , 브라우저 호환 설정 , 그리고
페이지 리로드기능있는데 여기선 페이지 리로드 기능의 refresh 를 이용.
content 의 값은 초단위 갱신
22 : poll.txt 로 부터 poll ArrayList로 데이터 가져오기
26~27 : poll의 데이터를 전부 sum
29~30 : making DecimalFormat's format
35 : colspan="2" 2칸을 합치겠다.
42~43 : getting 득표수 and getting 득표율 for using sum
50 : I made simple stick graph for using hr tag.
and also made the state that stick graph can be changed for using this "<%=350*per %>"
58 : the conception that can move to another site is onclick="location.href='poll.jsp'" about html.
-요약-
-javascript-
페이지이동
location.href='poll.jsp'
-jsp-
<%= => : 표현식태그 ,간단한처리에 이용되며 내부에는 출력할 내용이 들어감
request.setCharacterEncoding("UTF-8"); : post 방식으로 데이터가 넘어올 때 한글 깨짐을 방지
request.getParameter("poll"); : 이전 페이지의 form태그 내부 name속성의 값이 poll인 태그의 value 소환.
application.getRealPath("/"); : "/"는 웹서비스가 실행되는 web root(최상위 경로)를 의미한다.
-java-
file scanner객체 생성 : scanner = new Scanner(new File(filePath));
scanner.hasNextLine() , scanner.nextLine() : 주로 이 둘이 같이 쓰이며
scanner.hasNextLine() 는 다음줄이 있는지 검사.
scanner.nextLine() 은 다음 한 줄을 반환함
파일에 출력을 위한 객체생성
PrintWriter printWriter=new PrintWriter(String filepath);
파일에 한줄 출력
printWriter.write(String 변수+"\r\n"); //윈도우는 "\r\n" , 유닉스(리눅스)는 "\n"
파일출력내용 저장
printWriter.close();
-html-
form 태그 속성의 method
get : 인터넷주소로 데이터 전달(보안취약)
post : 데이터를 숨겨서 다른 파일에 전달
열 합치기 : colspan="2" // 2열 합치기
가로 막대 선 : <hr/>
호출관계
<input type="submit"> 은 form tag의 action값을 호출
onclick="location.href='pollResult.jsp'" 로 페이지 이동
<meta http-equiv="refresh" content="1; url='?'"/> : 1초후 갱신, ?는 자기 자신사이트로 갱신
http-equiv 은 기본언어 , 문자셋 , 기본 스타일 시트를 설정 , 브라우저 호환 설정 , 그리고
페이지 리로드기능있는데 여기선 페이지 리로드 기능의 refresh 를 이용.
content 의 값은 초단위 갱신
padding
cellpadding :안여백
cellspacing : 셀간격
-css-
None
-마침글-
I made online poll for using JSP's request order & several html tags
'21년이전 > 국비-JSP' 카테고리의 다른 글
국비-쿠키(Cookie) (0) | 2021.03.19 |
---|---|
JSP-출석 게시판 구현 (0) | 2021.03.18 |
JSP-인클루드 액션태그 이용 (0) | 2021.03.14 |
JSP- Calendar(not DB & using web crawling) (0) | 2021.03.11 |
JSP-html 구조 (0) | 2021.02.25 |