728x90
728x90

 

 

오늘은 jsp와 자바를 이용, 투표프로그램을 만들어 볼 것이다. 역시 텍스트편집 프로그램은 이클립스를 이용한다.

 


 

ObjectAid 플러그인 설치

이클립스 > help > install new software > (Work with) add > 아래와 같이 입력한다.
next와 약관 동의를 체크하여 설치를 마친다.

 

 

사진에서는 Contact all update sites during install to find required software
옵션이 체크되어있지만 오류가 날 경우 저 옵션을 해제해주면 문제없이 설치된다.

 

 

ObjectAid UML Explorer

 

www.objectaid.com

 

이클립스의 플러그인은 개발을 좀 더 윤택하고 편리하게 한다. 
예전에는 폴더를 찾아 직접 다운로드 했어야 했는데 지금은 그럴 필요가 없다.

 

 

ObjectAid Class Diagram 을 선택하여 생성한 후 poll 폴더 안의 자바 프로그램들을 선택하여
pollUML.ucls 문서 위로 드래그하면 자동으로 이렇게 생성된다.

 

 

프로젝트 파일과 폴더 구성은 아래와 같이 할 것이다. 자세한 코드는 아래에. 이놈이 분명 올려뒀다고 했는데 보이지 않는 경우 접은 글 기능을 이용한 것이니 클릭하면 숨겨진 내용들이 펼쳐지면서 보인다.

 

 

 


 

자바 파일 (poll 패키지)

 

1) DBConnectionMgr.java

...더보기
package poll;

import java.sql.*;
import java.util.Properties;
import java.util.Vector;

public class DBConnectionMgr {
    private Vector connections = new Vector(10);
    private String _driver = "org.gjt.mm.mysql.Driver",
    _url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=EUC_KR",
    _user = "root",  //각자의 아이디와 비번
    _password = "1234";
    
    private boolean _traceOn = false;
    private boolean initialized = false;
    private int _openConnections = 50;
    private static DBConnectionMgr instance = null;

    public DBConnectionMgr() {
    }

    /** Use this method to set the maximum number of open connections before
     unused connections are closed.
     */
     
    public static DBConnectionMgr getInstance() {
        if (instance == null) {
            synchronized (DBConnectionMgr.class) {
                if (instance == null) {
                    instance = new DBConnectionMgr();
                }
            }
        }

        return instance;
    }

    public void setOpenConnectionCount(int count) {
        _openConnections = count;
    }


    public void setEnableTrace(boolean enable) {
        _traceOn = enable;
    }


    /** Returns a Vector of java.sql.Connection objects */
    public Vector getConnectionList() {
        return connections;
    }


    /** Opens specified "count" of connections and adds them to the existing pool */
    public synchronized void setInitOpenConnections(int count)
            throws SQLException {
        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < count; i++) {
            c = createConnection();
            co = new ConnectionObject(c, false);

            connections.addElement(co);
            trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
        }
    }


    /** Returns a count of open connections */
    public int getConnectionCount() {
        return connections.size();
    }


    /** Returns an unused existing or new connection.  */
    public synchronized Connection getConnection()
            throws Exception {
        if (!initialized) {
            Class c = Class.forName(_driver);
            DriverManager.registerDriver((Driver) c.newInstance());

            initialized = true;
        }


        Connection c = null;
        ConnectionObject co = null;
        boolean badConnection = false;


        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);

            // If connection is not in use, test to ensure it's still valid!
            if (!co.inUse) {
                try {
                    badConnection = co.connection.isClosed();
                    if (!badConnection)
                        badConnection = (co.connection.getWarnings() != null);
                } catch (Exception e) {
                    badConnection = true;
                    e.printStackTrace();
                }

                // Connection is bad, remove from pool
                if (badConnection) {
                    connections.removeElementAt(i);
                    trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
                    continue;
                }

                c = co.connection;
                co.inUse = true;

                trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
                break;
            }
        }

        if (c == null) {
            c = createConnection();
            co = new ConnectionObject(c, true);
            connections.addElement(co);

            trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
        }

        return c;
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void freeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                co.inUse = false;
                break;
            }
        }

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if ((i + 1) > _openConnections && !co.inUse)
                removeConnection(co.connection);
        }
    }

    public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
        try {
            if (r != null) r.close();
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s, ResultSet r) {
        try {
            if (r != null) r.close();
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, PreparedStatement p) {
        try {
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s) {
        try {
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void removeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;
        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                try {
                    c.close();
                    connections.removeElementAt(i);
                    trace("Removed " + c.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }
        }
    }


    private Connection createConnection()
            throws SQLException {
        Connection con = null;

        try {
            if (_user == null)
                _user = "";
            if (_password == null)
                _password = "";

            Properties props = new Properties();
            props.put("user", _user);
            props.put("password", _password);

            con = DriverManager.getConnection(_url, props);
        } catch (Throwable t) {
            throw new SQLException(t.getMessage());
        }

        return con;
    }


    /** Closes all connections and clears out the connection pool */
    public void releaseFreeConnections() {
        trace("ConnectionPoolManager.releaseFreeConnections()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (!co.inUse)
                removeConnection(co.connection);
        }
    }


    /** Closes all connections and clears out the connection pool */
    public void finalize() {
        trace("ConnectionPoolManager.finalize()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            try {
                co.connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            co = null;
        }

        connections.removeAllElements();
    }


    private void trace(String s) {
        if (_traceOn)
            System.err.println(s);
    }

}


class ConnectionObject {
    public java.sql.Connection connection = null;
    public boolean inUse = false;

    public ConnectionObject(Connection c, boolean useFlag) {
        connection = c;
        inUse = useFlag;
    }
}

 

 

 

2) 빈즈 파일

...더보기

PollItemBean

package poll;

public class PollItemBean {
	private int listnum;
	private int itemnum;
	private String [] item;
	private int count;
	
	public int getListnum() {
		return listnum;
	}
	public void setListnum(int listnum) {
		this.listnum = listnum;
	}
	public int getItemnum() {
		return itemnum;
	}
	public void setItemnum(int itemnum) {
		this.itemnum = itemnum;
	}
	public String[] getItem() {
		return item;
	}
	public void setItem(String[] item) {
		this.item = item;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
}

 

 

PollListBean

package poll;

public class PollListBean {
	private int num;
	private String question;
	private String sdate;
	private String edate;
	private String wdate;
	private int type;
	private int active;
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getQuestion() {
		return question;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public String getSdate() {
		return sdate;
	}
	public void setSdate(String sdate) {
		this.sdate = sdate;
	}
	public String getEdate() {
		return edate;
	}
	public void setEdate(String edate) {
		this.edate = edate;
	}
	public String getWdate() {
		return wdate;
	}
	public void setWdate(String wdate) {
		this.wdate = wdate;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public int getActive() {
		return active;
	}
	public void setActive(int active) {
		this.active = active;
	}
}

 

 

PollMgr.java

package poll;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import com.sun.org.apache.bcel.internal.generic.LSTORE;

public class PollMgr {

	private DBConnectionMgr pool;

	public PollMgr() {
		// single-tone pattern. 싱글톤패턴은 private이다.
		pool = DBConnectionMgr.getInstance();
		// math의 메소드는 all static이다. getInstance도 그렇다
	}

	// Max Num
	public int getMaxNum() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int maxNum = 0;

		try {
			con = pool.getConnection();
			sql = " select max(num) from tblPollList ";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next())
				maxNum = rs.getInt(1);
			// num이 넘어오지 않으면 가장 최신의 num값을 리턴한다.
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return maxNum;
	}

	// Poll Insert(설문작성)
	public boolean insertPoll(PollListBean plBean, PollItemBean piBean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "insert tblPollList(question, sdate, edate, wdate, type) "
					+ "values(?,?,?,now(),?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, plBean.getQuestion());
			pstmt.setString(2, plBean.getSdate());
			pstmt.setString(3, plBean.getEdate());
			pstmt.setInt(4, plBean.getType());  //1:복수, 0:단일
			int cnt = pstmt.executeUpdate(); 
			if(cnt==1) { //save
				sql = "insert tblPollItem values(?,?,?,0)";
				pstmt = con.prepareStatement(sql);
				String item[] = piBean.getItem();
				int listNum = getMaxNum();	
				int j = 0;
				for (int i = 0; i < item.length; i++) {
					//space
					if(item[i]==null||item[i].trim().equals(""))
						break;
					pstmt.setInt(1, listNum);
					pstmt.setInt(2, i);
					pstmt.setString(3, item[i]);
					j = pstmt.executeUpdate();
				}//--for
				if(j==1) 
					flag=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return flag;
	}

	// Poll All List : Y (벡터)
	public Vector<PollListBean> getAllList() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<PollListBean> vlist = new Vector<>();
		try {
			con = pool.getConnection();
			sql = "select * from tblPollList order by num desc";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				PollListBean plBean = new PollListBean();
				plBean.setNum(rs.getInt("num"));
				plBean.setQuestion(rs.getString("question"));
				plBean.setSdate(rs.getString("sdate"));
				plBean.setEdate(rs.getString("edate"));
				vlist.addElement(plBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}

	// Sum Count (총 투표한 수)
	public int sumCount(int listNum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int sum = 0;
		try {
			con = pool.getConnection();
			sql = "select sum(count) from tblPollItem where listnum=?";
			pstmt = con.prepareStatement(sql);
			if(listNum==0)
				listNum = getMaxNum();  //가장 최신의 설문
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			if(rs.next())
				sum = rs.getInt(1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return sum;
	}

	// Poll Read (설문 읽어오기) : 하나의 설문을 가져온다
	public PollListBean getPollRead(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		PollListBean plBean = new PollListBean();
		try {
			con = pool.getConnection();
			sql = "select * from tblPollList where num = ?";
			pstmt = con.prepareStatement(sql);
			if(num==0) 
				num = getMaxNum();
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				plBean.setNum(rs.getInt("num"));
				plBean.setQuestion(rs.getString("question"));
				plBean.setType(rs.getInt("type"));
				plBean.setActive(rs.getInt("active"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return plBean;
	}

	// Poll Item List : Y (표의 설문항목, num, count값 벡터로 리턴)
	public Vector<String> getItem(int listNum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<String> vlist = new Vector<>();
		try {
			con = pool.getConnection();
			sql = "select item from tblPollItem " + "where listNum = ?";
			pstmt = con.prepareStatement(sql);
			if (listNum == 0)
				listNum = getMaxNum();
				System.out.print("리스트넘:"+listNum);
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				/*
				 * String item = rs.getString("item"); vlist.addElement(item);
				 */
				vlist.addElement(rs.getString("item"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}

	// Poll Update(투표실행. for 사용해서 배열로 db로 간다.)
	public boolean updatePoll(int listNum, String itemNum[]) {
		//itemnum = 0&itemnum=1&itemnum=2&num=2
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "update tblPollItem set count=count+1"
					+ "where listnum=? and itemnum=?"; //2가지 조건
			pstmt = con.prepareStatement(sql);
			if(listNum==0) {
				listNum = getMaxNum();
			}
			for (int i = 0; i < itemNum.length; i++) {
				pstmt.setInt(1, listNum);
				pstmt.setInt(2, Integer.parseInt(itemNum[i]));
				if(pstmt.executeUpdate()==1) {
					flag = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return flag;
	}

	// Poll View (투표결과)
	public Vector<PollItemBean> getView(int listNum){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<PollItemBean> vlist = new Vector<PollItemBean>();
		try {
			con = pool.getConnection();
			sql = "select item, count from tblPollItem where listnum=?";
			pstmt = con.prepareStatement(sql);
			if(listNum==0) {
				listNum = getMaxNum();
			}
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				PollItemBean piBean = new PollItemBean();
				String item[] = new String[1];
				item[0]=rs.getString("item");
				piBean.setItem(item);
				piBean.setCount(rs.getInt("count"));
				vlist.addElement(piBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	

	// Max Count (하이라이트)
		public int getMaxCount(int listNum) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String sql = null;
			int maxCnt = 0;
			try {
				con = pool.getConnection();
				sql = "select max(count) from tblPollitem "
						+ "where listNum = ?";
				pstmt = con.prepareStatement(sql);
				if(listNum==0)
					listNum = getMaxNum();
				pstmt.setInt(1, listNum);
				rs = pstmt.executeQuery();
				if(rs.next())
					maxCnt = rs.getInt(1);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.freeConnection(con, pstmt, rs);
			}
			return maxCnt;
		}
}

 

 


 

Style.CSS

BODY {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TD {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TH {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
SELECT {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
DIV {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
FORM {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TEXTAREA {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999 ; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; BACKGROUND-COLOR: white
}
INPUT {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; HEIGHT: 19px; BACKGROUND-COLOR: white
}

A:link {text-decoration:none;color:#696969}
A:hover{text-decoration:yes;color:#66CCFF}
A:visited {text-decoration:none;color:#330066}

 

 

Table.sql

//쿼리문을 돌려주세요

create table tblPollList(
 num int primary key auto_increment,
 question varchar(200) not null,
 sdate date,
 edate date,
 wdate date,
 type smallint default 1,
 active smallint default 1
)COLLATE='euckr_korean_ci';

create table tblPollItem(
 listnum int not null,
 itemnum smallint default 0,
 item varchar(50) not null,
 count int,
 primary key(listnum, itemnum)
)COLLATE='euckr_korean_ci';

 

 


 

jsp 파일 (poll 폴더)

 

pollForm

<!-- pollForm.jsp -->
<%@page import="java.util.Vector"%>
<%@page import="poll.PollListBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- db연동 -->
<jsp:useBean id="mgr" class="poll.PollMgr" />
<% 
	request.setCharacterEncoding("EUC-KR"); 
	int num = 0;
	if(request.getParameter("num")!=null){
		num = Integer.parseInt(request.getParameter("num"));
	} //요청한 값이 mgr로 넘어간다
	PollListBean plBean=mgr.getPollRead(num);
	System.out.println("넘:"+num);
	Vector<String> vlist = mgr.getItem(num);
	String question = plBean.getQuestion();
	int type = plBean.getType();
	int active = plBean.getActive();
%>
<form action="pollFormProc.jsp">
<table border="1">
	<tr>
		<td colspan="2" width="300">Q: <%=question %></td>
	</tr>
	<tr>
		<td colspan="2">
	<%
	for(int i=0; i<vlist.size(); i++){
		String item = vlist.get(i);
	%>
	<%if(type==1){%>
	<input type="checkbox" name="itemnum" value="<%=i%>">
	<%}else{%>
	<input type="radio" name="itemnum" value="<%=i%>">
	<%} %>
		<%=item%><br/>
		<%} //for	%>
		</td>
	</tr>
	<tr>
		<td width="150">
		<%if(active==1){%>
		<input type="submit" value="투표">
		<%}else{%>
			투표종료
		<%}%>
		</td>
		<td width="150">
			<input type="button" value="결과" 
			onclick="javascript:window.open('pollView.jsp?num=<%=num%>'
			,'pollView','width=500, height=350')">
		</td>
	</tr>
</table>
<input type="hidden" name="num" value="<%=num%>">
</form>

 

 

pollFormProc

<!-- pollFormProc.jsp -->
<%@page import="poll.PollMgr"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); 
	int num = Integer.parseInt(request.getParameter("num"));
	PollMgr mgr = new PollMgr();
	String itemNum[] = request.getParameterValues("itemnum");
	boolean result = mgr.updatePoll(num, itemNum);
	String msg= "투표가 등록되지 않았습니다.";
	if(result)
		msg= "투표가 등록 되었습니다.";
%> 
<script>
	alert("<%=msg%>");
	location.hrerf="pollst.jsp?num=<%=num%>";
</script>

 

 

pollInsert

<!-- pollInsert.jsp -->
<%@ page contentType="text/html; charset=EUC-KR" %>
<html>
<head>
<title>JSP Poll</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	function send() {
		f = document.frm;
		f.sdate.value = f.sdateY.value+"-"
		+ f.sdateM.value+"-"+f.sdateD.value;
		f.edate.value = f.edateY.value+"-"
		+ f.edateM.value+"-"+f.edateD.value;
		f.submit();
	}
</script>
</head>
<body bgcolor="#FFFFCC">
	<div align="center">
		<br />
		<h2>투표프로그램</h2>
		<hr width="600" />
		<b>설문작성</b>
		<hr width="600" />
		<form name="frm" method="post" action="pollInsertProc.jsp">
			<table border="1" width="500">
				<tr>
					<td><b>질문</b></td>
					<td colspan="2"><input name="question" size="30"></td>
				</tr>
				<tr>
					<td rowspan="10"><b>항목</b></td>
					<%
						for (int i = 1; i <= 4; i++) {
							out.println("<td>" + (i * 2 - 1)
									+ ": <input name='item'></td>");
							out.println("<td>" + (i * 2)
									+ ": <input name='item'></td>");
							out.println("</tr>");
							if (i == 9) {
								out.println("");
							} else {
								out.println("<tr>");
							}
						}//for end
					%>
				<tr>
					<td>시작일</td>
					<td colspan="2"><select name="sdateY">
							<option value="2019">2019
							<option value="2020">2020
					</select>년 <select name="sdateM">
							<%
								for (int i = 1; i <= 12; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>월 <select name="sdateD">
							<%
								for (int i = 1; i <= 31; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>일</td>
				</tr>
				<tr>
					<td>종료일</td>
					<td colspan=2><select name="edateY">
							<option value="2019">2019
							<option value="2020">2020
					</select>년 <select name="edateM">
							<%
								for (int i = 1; i <= 12; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>월 <select name="edateD">
							<%
								for (int i = 1; i <= 31; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>일</td>
				</tr>
				<tr>
					<td>복수투표</td>
					<td colspan=2>
						<input type="radio" name="type" value="1" checked>yes 
						<input type="radio" name="type" value="0">no
					</td>
				</tr>
				<tr>
					<td colspan=3>
						<input type="button" value="작성하기" onclick="send()"> 
						<input type="reset" value="다시쓰기"> 
						<input type="button" value="리스트" onClick="javascript:location.href='pollList.jsp'">
					</td>
				</tr>
			</table>
			<input type="hidden" name="sdate">
			<input type="hidden" name="edate">
		</form>
	</div>
</body>
</html>

 

 

 

pollInsertProc

<!-- pollInsertProc.jsp -->
<%@ page contentType="text/html; charset=EUC-KR" %>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="poll.PollMgr" />
<jsp:useBean id="plBean" class="poll.PollListBean" />
<jsp:setProperty property="*" name="plBean"/>
<jsp:useBean id="piBean" class="poll.PollItemBean" />
<jsp:setProperty property="*" name="piBean"/>
<%
	boolean result = mgr.insertPoll(plBean, piBean);
	String msg="설문 추가에 실패";
	String location = "pollInsert.jsp";
	if(result){
		msg = "설문 추가 성공";
		location = "pollList.jsp";
	}
%>
<script>
	alert("<%=msg%>");
	location.href="<%=location%>";
</script>

 

 

 

pollview

<%@page import="poll.PollItemBean"%>
<%@page import="java.util.Random"%>
<%@page import="java.util.Vector"%>
<%@page import="poll.PollListBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="mgr" class="poll.PollMgr" />
<% 
	request.setCharacterEncoding("EUC-KR"); 
	int num=0;
	if(request.getParameter("num")!=null){
		num = Integer.parseInt(request.getParameter("num"));
	}		
	PollListBean plbBean = mgr.getPollRead(num); //설문에 대한 값
	Vector<PollItemBean> vlist = mgr.getView(num);
	int sumCount = mgr.sumCount(num);
	String question = plbBean.getQuestion();  //투표수
	Random r= new Random(); //막대그래프 랜덤한 색깔 부여
	
%> 
<html>
<head>
<title>JSP Poll</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
<div align="center"><br/>
<h2>투표 결과</h2>
<table border="1" width="400">
	<tr>
		<td colspan="4">
		<b>Q : <%=question%></b>	
		</td>
	</tr>
	<tr>
		<td colspan="3">
		<b>총 투표자 : <%=sumCount%>명<%= %></b>	
		</td>
		<td width="40"><b>count(%)</b></td>
	</tr>
	<%
		for(int i=0; i<vlist.size(); i++){
			PollItemBean piBean = vlist.get(i);
			String item[] = piBean.getItem();
			int count = piBean.getCount();
			int ratio = new Double(Math.round((double)
					count/sumCount*100)).intValue();
			String rgb = "#"+Integer.toHexString(r.nextInt(255*255*255)); //색상수
			int maxCnt = mgr.getMaxCount(num);
	%>
	<tr>
		<td width="20" align = "center"><%=i+1%></td>
		<td width="120" align = "center">
		<%if(maxCnt==count){ %><font color="red"><b><%}%>
			<%=item[0]%>
		<%if(maxCnt==count){ %></b></font><%}%>
		</td>
		<td>
			<table width="<%=ratio%>">
				<tr>
					<td bgcolor="<%=rgb%>" height = "15"></td>
				</tr>
			</table>
		</td>
		<td width="40" align = "center"><%=count%>(<%=ratio%>)</td>
	</tr>
	<%
		}
	%>
</table><br/>
<a href="javascript:window.close()">닫기</a>
</div>
</body>
</html>

 

 

 

pollList

<%@page import="poll.PollListBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% 
request.setCharacterEncoding("EUC-KR"); 
%> 
<jsp:useBean id="mgr" class="poll.PollMgr" />
<html>
<head>
	<title>JSP Poll</title>
	<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
	<div align = "center"><br/>
		<h2>투표 프로그램</h2>
		<hr width="60%" />
		<b>설문폼</b>
		<!-- include 지시자(@include), 액션 태그 두 가지가 있다. 지시자는 조각모음(항상 있는 메뉴들, 기능이 없는데 반복해서 쓸 경우) 때 쓴다. -->
		<!-- include 액션태그(jsp:include...)는 요청정보가 같이 넘어간다. 포워드처럼 -->
		<jsp:include page="pollForm.jsp" />
		<hr width="60%" />
		<b>설문리스트</b>
<table>
	<tr>
		<td>
		<table  border="1">
			<tr>
				<th width="50">번호</th>
				<th width="250" align="left">질문</th>
				<th width="200">시작일~종료일</th>
			</tr>
		<!-- 설문 리스트 Start -->
		<%
			Vector<PollListBean> vlist = mgr.getAllList();
			for(int i=0; i<vlist.size(); i++){
				PollListBean plBean = vlist.get(i);
				int num=plBean.getNum();
				String question = plBean.getQuestion();
				String sdate = plBean.getSdate();
				String edate = plBean.getEdate();
		%>
			<tr align="center">
				<td><%=vlist.size()-i %></td>
				<td align="left">
					<a href="pollList.jsp?num=<%=num%>"><%=question %>
				</td>
				<td><%=sdate+"~"+edate%></td>
			</tr>
			<%} //--for %>
		<!-- 설문 리스트 End -->
		</table>
		</td>
	</tr>
	<tr>
		<td align="center">
			<a href="pollInsert.jsp">설문작성하기</a>
		</td>
	</tr>
</table>
</div>
</body>
</html>

 

* include 지시자와 액션 태그의 차이점

 

JSP include(지시자와 액션태그)

JSP include(지시자와 액션태그) JSP페이지를 모듈화하여 다른 페이지에 include하는 방법은 지시자(directive)와 액션태그(action tag)를 사용하는 방법이 있다. 1. 지시자 include(directive include) '지시자..

doublesprogramming.tistory.com

pollList.jsp 예제에서는 지시자 방식을 사용했다.

728x90
728x90

'Java Friends > JSP' 카테고리의 다른 글

JSP 파일업로드 기능 구현  (0) 2019.07.16
JSP 방명록 구현하기  (0) 2019.07.15
JSP 회원가입, 로그인, 로그아웃 기능 구현  (1) 2019.07.11
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v