728x90
728x90

 

 

 

 

오늘은 방명록을 구현해볼 것이다. 기능은 로그인, 글쓰기, 수정과 삭제, 그리고 비밀글 작성이 들어가며 관리자의 경우 회원의 비밀글도 조회 및 삭제가 가능하다. 당연히 타 회원이 쓴 비밀글은 일반 회원이 볼 수 없다. 그럼 GO!

 

 

 

 


 

1. 테이블 생성

로그인과 회원가입의 상세한 기능은 이전 글을 참고. 회원 부분은 만들어 둔 기능을 활용한다.
그럼 첫 번째 작업 순서로 먼저 Mysql에 접속하여 쿼리문을 돌리면 테이블들이 생성된다.

 

 

 

table.sql

create table tblJoin(
	id char(20) primary key,
	pwd char(20) not null,
	name char(20) not null,
	email char(30),
	hp char(40),
	grade char(2) default '0'
)COLLATE='euckr_korean_ci';

create table tblGuestBook(
	num int primary key auto_increment,
	id char(20) not null,
	contents text,
	ip char(15) not null,
	regdate date,
	regtime datetime,
	secret char(2) default '0'
)COLLATE='euckr_korean_ci';

create table tblComment(
 	cnum int primary key auto_increment,
 	num int not null,
 	cid char(20) not null,
 	comment text,
 	cip char(15) not null,
 	cregDate date
)COLLATE='euckr_korean_ci';

 

 


 

 

2. 자바 파일 생성

guestbook 패키지를 만든 후 beans 파일들을 생성한다. 총 세 개가 필요하다. 
CommentBean.java, GuestBookBean.java, JoinBean.java.
그리고 DBConnectionMgr.java 파일을 전 패키지에서 가져와 복사한다.

 

 

DBConnectionMgr.java

package guestbook;

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;
    }
}

 

 

 

CommentBean.java

package guestbook;

public class CommentBean {
	private int cnum;
	private int num;
	private String cid;
	private String comment;
	private String cip;
	private String cregDate;
	public int getCnum() {
		return cnum;
	}
	public void setCnum(int cnum) {
		this.cnum = cnum;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}
	public String getCip() {
		return cip;
	}
	public void setCip(String cip) {
		this.cip = cip;
	}
	public String getCregDate() {
		return cregDate;
	}
	public void setCregDate(String cregDate) {
		this.cregDate = cregDate;
	}
}

 

 

 

GuestBookBean.java

package guestbook;

public class GuestBookBean {
	private int num;
	private String id;
	private String contents;
	private String ip;
	private String regdate;
	private String regtime;
	private String secret;
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContents() {
		return contents;
	}
	public void setContents(String contents) {
		this.contents = contents;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getRegdate() {
		return regdate;
	}
	public void setRegdate(String regdate) {
		this.regdate = regdate;
	}
	public String getRegtime() {
		return regtime;
	}
	public void setRegtime(String regtime) {
		this.regtime = regtime;
	}
	public String getSecret() {
		return secret;
	}
	public void setSecret(String secret) {
		this.secret = secret;
	}
	
}

 

 

 

JoinBean.java.

package guestbook;

public class JoinBean {
	private String id;
	private String pwd;
	private String name;
	private String email;
	private String hp;
	private String grade;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getHp() {
		return hp;
	}
	public void setHp(String hp) {
		this.hp = hp;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
}

 

 

 

GuestBookMgr.java

package guestbook;

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

public class GuestBookMgr {
	
	private DBConnectionMgr pool;
	private final SimpleDateFormat SDF_DATE =
			new SimpleDateFormat("yyyy'년'  M'월' d'일' (E)");
	private final SimpleDateFormat SDF_TIME =
			new SimpleDateFormat("H:mm:ss");
	
	public GuestBookMgr() {
		pool = DBConnectionMgr.getInstance();
	}

	//Join Login
	public boolean loginJoin(String id, String pwd) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "select * from tblJoin where id=? and pwd =?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			if(pstmt.executeQuery().next())
				flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return flag;
	}
	
	//Join Information
	public JoinBean getJoin(String id) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		JoinBean bean = new JoinBean();
		try {
			con = pool.getConnection();
			sql = "select * from tblJoin where id=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			if(rs.next()){
				bean.setId(rs.getString(1));
				bean.setPwd(rs.getString(2));
				bean.setName(rs.getString(3));
				bean.setEmail(rs.getString(4));
				bean.setHp(rs.getString(5));
				bean.setGrade(rs.getString(6));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}
	
	//GuestBook Insert
	public void insertGuestBook(GuestBookBean bean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "insert tblGuestBook(id, contents, ip, regdate, regtime, secret) "
					+ "values (?,?,?, now(), now(), ?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, bean.getId());
			pstmt.setString(2, bean.getContents());
			pstmt.setString(3, bean.getIp());
			pstmt.setString(4, bean.getSecret());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//GuestBook List : 비밀글은 본인 및 관리자만 볼 수 있다.
	public Vector<GuestBookBean> listGuestBook(String id, String grade){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<GuestBookBean> vlist = new Vector<GuestBookBean>();		
		try {
			con = pool.getConnection();
			if(grade.equals("1"/*admin*/)) {
				sql = "select * from tblGuestBook order by num desc";
				pstmt = con.prepareStatement(sql);
			} else /*일반로그인*/ {
				sql = "select * from tblGuestBook where id=? or secret=? order by num desc";
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, id);
				pstmt.setString(2, "0"); //비밀글이 아닌 글	
			}
			rs = pstmt.executeQuery();
			while (rs.next()) {
				GuestBookBean bean = new GuestBookBean();
				bean.setNum(rs.getInt(1));
				bean.setId(rs.getString(2));
				bean.setContents(rs.getString(3));
				bean.setIp(rs.getString(4));
				String tempDate = SDF_DATE.format(rs.getDate(5));
				bean.setRegdate(tempDate);
				String tempTime = SDF_TIME.format(rs.getTime(6));
				bean.setRegtime(tempTime);
				bean.setSecret(rs.getString(7));
				vlist.addElement(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	
	//GuestBook Read
	public GuestBookBean getGuestBook(int num) { 
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		GuestBookBean bean = new GuestBookBean();
		try {
			con = pool.getConnection();
			sql = " select * from tblGuestBook where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();  
			if(rs.next()) { // num이 pk 라 while 대신 if문
				bean.setNum(rs.getInt(1));
				bean.setId(rs.getString(2));
				bean.setContents(rs.getString(3));
				bean.setIp(rs.getString(4));
				String tempDate = SDF_DATE.format(rs.getDate(5));
				bean.setRegdate(tempDate);
				String tempTime = SDF_TIME.format(rs.getTime(6));
				bean.setRegtime(tempTime);
				bean.setSecret(rs.getString(7));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}
	
	//GuestBook Update : contents, ip, secret
	public void updateGuestBook (GuestBookBean bean) {  //rs x
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "update tblGuestBook set contents=?, ip=?, secret=? "
					+ "where num=?";
			pstmt = con.prepareStatement(sql);
			
			pstmt.setString(1, bean.getContents());
			pstmt.setString(2, bean.getIp());
			pstmt.setString(3, bean.getSecret());
			pstmt.setInt(4, bean.getNum());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//GuestBook Delete
	public void deleteGuestBook (int num) { // num : pk
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblGuestBook where num = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//Comment Insert
		public void insertComment(CommentBean bean) {
			Connection con = null;
			PreparedStatement pstmt = null;
			String sql = null;
			try {
				con = pool.getConnection();
				sql = "insert tblComment(num, cid, comment, cip, cregDate values (?,?,?,?,now())";
				pstmt = con.prepareStatement(sql);
				pstmt.setInt(1, bean.getNum());
				pstmt.setString(2, bean.getCid());
				pstmt.setString(3, bean.getComment());
				pstmt.setString(4, bean.getCip());				
				pstmt.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.freeConnection(con, pstmt);
			}
		}
		
	//Comment List
	public Vector<CommentBean> listComment(int num){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<CommentBean> vlist = new Vector<CommentBean>();
		try {
			con = pool.getConnection();
			sql = " select * from tblComment where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				CommentBean bean = new CommentBean();
				bean.setCnum(rs.getInt(1));
				bean.setNum(rs.getInt(2));
				bean.setCid(rs.getString(3));
				bean.setComment(rs.getString(4));
				bean.setCip(rs.getString(5));
				String tempDate = SDF_DATE.format(rs.getDate(6));
				bean.setCregDate(tempDate);
				vlist.addElement(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	
	//Comment Delete
	public void deleteComment(int cnum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblComment where cnum=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, cnum);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
	}
	
	//Comment All Delete (원글이 삭제되면 댓글도 삭제)
	public void deleteAllComment(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblComment where cnum=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
	}
	
}

 

 


 

 

3. JSP 파일

 

login.jsp

<%@page contentType="text/html;charset=EUC_KR"%>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<%
	request.setCharacterEncoding("EUC-KR");
	String id = (String)session.getAttribute("idKey");
	String url = request.getParameter("url");
%>
<title>로그인</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<body bgcolor="#996600">
<br><br>
<div align="center">
<%
		if(id!=null){
			%>
				<b><%=login.getName()%></b>님 환영합니다.<br>
				<a href="showGuestBook.jsp" >방명록 </a>&nbsp;
				<a href="logout.jsp" >로그아웃</a>
			<%
		}else{
%>
<h2>GuestBook 로그인</h2>
<FORM METHOD="POST" ACTION="loginProc.jsp?url=<%=url%>"><!-- get방식과 post방식 동시에 -->
<table border="1">
	<tr>
		<td>id</td>
		<td> <input name="id" value="aaa">
		</td>
	</tr>
	<tr>
		<td>pwd</td>
		<td><input name="pwd" value="1234"></td>
	</tr>
	<tr>
		<td align="center" colspan="2">
		<INPUT TYPE="submit" value="로그인">
		</td>
	</tr>
</table>
<input type="hidden" name="url" value="<%=url%>">
</FORM>
<%}%>
</div>
</body>

 

 

 

logout.jsp

<%@page contentType="text/html;charset=EUC-KR"%>
<%
    session.invalidate();
%>
<script>
   alert('로그아웃 되었습니다.');
   location.href="login.jsp"; 
</script>

 

 

 

loginProc.jsp

<%@page contentType="text/html;charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="guestbook.GuestBookMgr"/>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<jsp:setProperty name="login" property="*"/>
<%
		String url="login.jsp";
		if(request.getParameter("url")!=null&&
				!request.getParameter("url").equals("null")){
			url=request.getParameter("url");
		}
		boolean flag = mgr.loginJoin(login.getId(), login.getPwd());
		String msg = "로그인 실패";
		if(flag){
			msg = "로그인 성공";
			login = mgr.getJoin(login.getId());
			session.setAttribute("idKey", login.getId());
			session.setAttribute("login", login);
		}
%>
<script>
	alert("<%=msg%>");	
	location.href="<%=url%>";
</script>

 

 

 

getSession.jsp

<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); %> 
<%
	String id=(String)session.getAttribute("idKey");
	if(id==null){
		StringBuffer url = request.getRequestURL();
		response.sendRedirect("login.jsp?url="+url);
	}else {
		//닫는 중괄호는 이 페이지를 include하는 페이지에 구현
%> 

 

 

 

postGuestBook.jsp

<%@page pageEncoding="EUC-KR"%>
<jsp:useBean id="login" class="guestbook.JoinBean"  scope="session"/>
<html>
<head>
<title>GuestBook</title>
<script type="text/javascript">
	function checkInputs() {
		frm = document.postFrm;
		if(frm.contents.value==""){
			alert("내용을 입력해 주세요.");
			frm.contents.focus();
			return;
		}
		frm.submit();
	}
</script>
</head>
<body>
	<div align="center">
		<table cellspacing="0" cellpadding="3">
			<tr>
				<td bgcolor="#F5F5F5"><font size="4"><b>글올리기</b></font></td>
			</tr>
		</table>
		<form name="postFrm" method="post" action="processGuestBook.jsp">
			<table border="1" bordercolor="#000000" cellspacing="0" cellpadding="0">
				<tr>
					<td>
						<table>
							<tr>
								<td height="40" align="center">
								<img src="img/face.bmp" border="0" alt="성명"> 
								<input title="이름을 적어주세요" name="name" size="9" maxlength="20" value="<%=login.getName() %>" readonly>
								<img src="img/email.bmp" border="0" alt="메일">
								<input title="전자메일 주소를 적는 곳이군요" name="email" size="20"
									maxlength="80" value="<%=login.getEmail() %>"> 
								<img src="img/hp.bmp" border="0" alt="홈페이지"> 
								<input title="홈페이지도 있으면 알려주세요." name="hp" size="25"
									maxlength="80" value="<%=login.getHp()%>">
									</td>
							</tr>
							<tr>
								<td align="center">
									<textarea title="좋은 글 남겨주세요"
										name="contents" cols="60" rows="6">하이~~~</textarea>
								</td>
							</tr>
							<tr>
								<td width="500" height="30" colspan="3" align="center">
									<!-- table start -->
									<input type="hidden" name="id" value="<%=login.getId().trim()%>">
									<input type="button" value="글올리기" onclick="javascript:checkInputs()"> 
									<input type="reset" value="고치기">
									<input type="checkbox" name="secret" value="1">비밀글
									<!--table end  -->
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

 

 

 

 

postGuestBook.jsp

<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% 
	request.setCharacterEncoding("EUC-KR"); 
%> 
<jsp:useBean id="mgr" class="guestbook.GuestBookMgr"></jsp:useBean>
<jsp:useBean id="bean" class="guestbook.GuestBookBean"></jsp:useBean>
<jsp:setProperty property="*" name="bean" />
<%
	// 방명록 ip값
	bean.setIp(request.getRemoteAddr());
	// 비밀글 체크를 안 한 상태
	if(bean.getSecret()==null){
		bean.setSecret("0");
	}
	mgr.insertGuestBook(bean);
	response.sendRedirect("showGuestBook.jsp");
%>

 

 

 

 

showGuestBook.jsp

<%@page import="guestbook.JoinBean"%>
<%@page import="guestbook.GuestBookBean"%>
<%@page import="guestbook.GuestBookMgr"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR"); %>
<%@include file="getSession.jsp"%>
<%
	//GuestBookMgr mgr = new GuestBookMgr();
	//Vector<GuestBookBean> vlist = mgr.listGuestBook(login.getId(), login.getGrade());
%>

<html>
<head>
<title>GuestBook</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript"></script>
</head>
<body bgcolor="#996600">
	<div align="center">
<%@include file="postGuestBook.jsp"%>
<%
	GuestBookMgr mgr = new GuestBookMgr();
	Vector<GuestBookBean> vlist = mgr.listGuestBook(login.getId(), login.getGrade());
%>
		<table width="520" cellspacing="0" cellpadding="3">
			<tr bgcolor="#F5F5F5">
				<td><font size="2"> <b><%=login.getName()%></b>님 환영합니다.
				</font></td>
				<td align="right"><a href="logout.jsp">로그아웃</a></td>
			</tr>
		</table>
		<!-- GuestBook List Start -->
		<%
			if(vlist.isEmpty()){
		%>
		<table width="520" cellspacing="0" cellpadding="7">
			<tr>
				<td>등록된 글이 없습니다.</td>
			</tr>
		</table>
		<% } else {%>
		<%
			for(int i=0; i<vlist.size(); i++){
				GuestBookBean bean = vlist.get(i);
				//방명록 쓴 사람의 정보
				JoinBean writer = mgr.getJoin(bean.getId());
		%>
		<table width="520" border="1" bordercolor="#000000" cellspacing="0"
			cellpadding="0">
			<tr>
				<td>
					<table bgcolor="#F5F5F5">
						<tr>
							<td width="225">NO : <%=vlist.size()-i%></td>
							<td width="225"><img src="img/face.bmp" border="0" alt="이름">
								<a href="mailto:<%=writer.getEmail()%>"> <%=writer.getName() %></a>
							</td>
							<td width="150" align="center">
								<%if(writer.getHp()==null||writer.getHp().equals("")){
							out.print("홈페이지가 없네요.");
						}else{
						%> <a href="http://<%=writer.getHp()%>"> <img alt="홈페이지 "
									src="img/hp.bmp" border="0">
							</a> <%}%>
							</td>
						</tr>
						<tr>
							<td colspan="3"><%=bean.getContents() %></td>
						</tr>
						<tr>
							<td>IP : <%=bean.getIp()%></td>
							<td><%=bean.getRegdate()+" "+bean.getRegtime()%></td>
							<%
								//로그인 id랑 방명록 쓴 사람의 id가 동일하면 수정, 삭제, 비밀글 모드 활성화
								boolean chk = login.getId().equals(writer.getId());
								if (chk||login.getGrade().equals("1")){  //동일하거나 grade가 1이든지 (관리자)
									if(chk){
							%>
							<a href="">[수정]</a>
							<% } //관리자가 수정은 못하게 한다. %> 
							<a href="">[삭제]</a>
								<%=bean.getSecret().equals("1")?"비밀글":""	%>					
							<%}	%>
							<td>[수정][삭제][비밀글]</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
		<%} //--for%>
		<%}%>
		<!-- GuestBook List End -->
	</div>
</body>
</html>
<%}%>

 

 

 

 


 

기타. 이클립스에서 tomcat 연동시 getRemoteAddr 메소드에서 0:0:0:0:0:0:0:1 를 리턴하는 오류

Run -> Run Configurations" 메뉴 > 연동하는 Tomcat 서버를 선택 > "Arguments" 탭 > VM arguments 에 아래의 항목을 추가한 후, "Apply" 버튼을 클릭하고 "Close" 버튼을 클릭.

 

-Djava.net.preferIPv4Stack=true

 

 

이클립스에서 tomcat 연동시 getRemoteAddr 메소드에서 0:0:0:0:0:0:0:1 를 리턴하는 오류 해결하는 방법

이클립스에서 tomcat 연동하여서 tomcat 을 실행한 후, 웹 접속하면 웹 브라우저의 IP 주소를 가벼오는 g...

blog.naver.com

 

 

 

https://servlet.com/

728x90
728x90
블로그 이미지

coding-restaurant

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

,

v