728x90
728x90

JSP를 이용한 MVC 패턴을 이용하여 만든다. 
(프레임워크는 MVC2) MVC 패턴의 장점은 확장성이다.
M : Beans + V : Jsp Viewer + C : Mgr control

실습에서는 poolean 기법  / 
connection 객체를 사용한다.

* beans
: 하나의 레코드 (테이블의 행 단위) 를 담는 단위. JSP Page 상에 나열되는 자바 처리 로직은 디자인 코드와 함께 매우 복잡한 코드를 구성함으로 인해 디자인 변경시 자바코드가 영향을 받아 오류가 자주 발생되며, 코드 수정시 코드를 알아볼 수 없어 유지보수가 매우 힘이 든다. 반복되는 자바 코드들을 JAVA 파일안에 저장하여 사용하는 형태로 Beans는 sun에서 제시한 작성 규칙이 존재

* mgr Manager Class(관리 클래스)

 


 

'다이나믹 웹 프로젝트'로 프로젝트를 생성하고, DB와 연동한다. 
클래스명은 대문자여야 프레임워크 들어갔을 때 에러가 없다.

 

 

 


입력


 

teamInsert.html

내장 익스플로러는 자바스크립트 오류를 디버깅하기 힘들다. 크롬으로 열기를 권장. 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Team Mgr</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	function check() {
		f = document.frm;
		if(f.name.value.length==0){
			alert("이름을 입력하세요.");
			f.name.focus();
			return;
		}
		if(f.city.value.length==0){
			alert("사는곳을 입력하세요.");
			f.city.focus();
			return;
		}
		if(f.age.value.length==0){
			alert("나이를 입력하세요.");
			f.age.focus();
			return;
		}
		if(f.team.value.length==0){
			alert("팀명을 입력하세요.");
			f.team.focus();
			return;
		}
		f.submit();
	}
	
	function check2() {
		f = document.frm;
		f.action="teamInsertProc2.jsp";
		f.submit();
	}
</script>
</head>
<body>
<div align="center">
<h1>Team Insert</h1>
<form name="frm" method="post" action="teamInsertProc.jsp"> 
<!-- <form name="frm" method="get" action="teamInsertProc.jsp"> -->
<table border="1">
<tr>
	<td width="50" align="center">이름</td>
	<td width="150"><input name="name" value="홍길동"></td>  
	<!-- input default는 text . bean의 property 이름과 같아야한다. -->
	<!-- 테이블컬럼명, 빈즈의 프로퍼티 명, 폼의 이름은 반드시 일치해야한다. --> 
</tr>
<tr>
	<td align="center">사는곳</td>
	<td><input name="city" value="부산"></td>
</tr>
<tr>
	<td align="center">나이</td>
	<td ><input name="age" value="27"></td>
</tr>
<tr>
	<td align="center">팀명</td>
	<td><input name="team" value="산적"></td>
</tr>
<tr>
	<td align="center" colspan="2">
		<input type="button" value="SAVE" onclick="check()">
		<input type="button" value="SAVE2" onclick="check2()">
	</td>
</tr>
</table><p/>
<a href="teamList.jsp">LIST</a>
<a href="teamSelect.jsp">SELECT</a>
<a href="teamDelete.jsp">DELETE</a>
</form>
</div>
</body>
</html>

 

 

 

table.sql

create table tblTeam(
num int primary key AUTO_INCREMENT, 
name char(10) not null,
city char(10) not null,
age int DEFAULT 0,
team char(10) not null
);

 

 

 

TeamBean.java

package ch07;

public class TeamBean {
	
	private int num;
	private String name;
	private String city;
	private int age;
	private String team;
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getTeam() {
		return team;
	}
	public void setTeam(String team) {
		this.team = team;
	}
}

 

 

server > server.xml 에서 port를 80으로 바꿔주고 URIEncoding 부분 언어 설정해준다.

 

 

DBConnectionMgr.java

package ch07;

/**
 * Copyright(c) 2001 iSavvix Corporation (http://www.isavvix.com/)
 *
 *                        All rights reserved
 *
 * Permission to use, copy, modify and distribute this material for
 * any purpose and without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all
 * copies, and that the name of iSavvix Corporation not be used in
 * advertising or publicity pertaining to this material without the
 * specific, prior written permission of an authorized representative of
 * iSavvix Corporation.
 *
 * ISAVVIX CORPORATION MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES,
 * EXPRESS OR IMPLIED, WITH RESPECT TO THE SOFTWARE, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR ANY PARTICULAR PURPOSE, AND THE WARRANTY AGAINST
 * INFRINGEMENT OF PATENTS OR OTHER INTELLECTUAL PROPERTY RIGHTS.  THE
 * SOFTWARE IS PROVIDED "AS IS", AND IN NO EVENT SHALL ISAVVIX CORPORATION OR
 * ANY OF ITS AFFILIATES BE LIABLE FOR ANY DAMAGES, INCLUDING ANY
 * LOST PROFITS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES RELATING
 * TO THE SOFTWARE.
 *
 */


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


/**
 * Manages a java.sql.Connection pool.
 *
 * @author  Anil Hemrajani
 */
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;
    }
}

 

 

TeamMgr.java

package ch07;

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

//DB연동 SQL문 메소드
public class TeamMgr {

	private DBConnectionMgr pool;

	public TeamMgr() {
		try {
			pool = DBConnectionMgr.getInstance();
//			//System.out.println("성공");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Insert - getXxx, setXxx, isXxx,
	public boolean insertTeam(TeamBean bean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;

		try {
			con = pool.getConnection(); // pool에서 Connection 빌려옴
			sql = "insert tblTeam(name, city, age, team) values (?,?,?,?)";
			// statement 상태로 던져주어야 함. 업그레이드 ver이 preparedstatement ????임
			pstmt = con.prepareStatement(sql);
			// ? 값 받아옴
			pstmt.setString(1, bean.getName());
			pstmt.setString(2, bean.getCity());
			pstmt.setInt(3, bean.getAge());
			pstmt.setString(4, bean.getTeam());

			if (pstmt.executeUpdate() == 1) // int 개수가 1이면 정상저장되었다. 값을 넘길 때.
				flag = true;

		} catch (Exception e) {
			e.printStackTrace(); // 오류 경로
		} finally {
			pool.freeConnection(con, pstmt); // con : 반납, pstmt : close
		}
		return flag;
	}

	// List-java1.8(8.0) -> java 11
	public Vector<TeamBean> listTeam() throws SQLException {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<TeamBean> vlist = new Vector<TeamBean>();

		try {
			con = pool.getConnection();
			sql = "select * from tblTeam";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			// select~로 테이블의 데이터 가져옴. 커서가 제일 윗 칼럼에서 머무르는 상태

			while (rs.next()/* 결과값이 있는 레코드는 true.다음줄로 가는... */) {
				TeamBean bean = new TeamBean();
				// int num = rs.getInt("num"); //매개변수 num
				// bean.setNum(num);
				// string 만 덮어쓰기 됨.
				bean.setNum(rs.getInt("num"));
				bean.setName(rs.getString("name"));
				bean.setCity(rs.getString("city"));
				bean.setAge(rs.getInt("age"));
				bean.setTeam(rs.getString("team"));
				vlist.addElement(bean);
				// add : boolean. addElement :...
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs); // con : 반납, pstmt : close
		}
		return vlist;
	}

	// Get
	public TeamBean getSelect(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		
		TeamBean bean = new TeamBean();
		
		try {
			con = pool.getConnection();
			sql = "select * from tblTeam where num=?";  //pk 값
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				bean.setNum(rs.getInt("num"));
				bean.setName(rs.getString("name"));
				bean.setCity(rs.getString("city"));
				bean.setAge(rs.getInt("age"));
				bean.setTeam(rs.getString("team"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}
	
	// Update
	public boolean updateTeam(TeamBean bean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "update tblTeam set name=?, city=?, age=?, team=? where num=? ";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, bean.getName());
			pstmt.setString(2, bean.getCity());
			pstmt.setInt(3, bean.getAge());
			pstmt.setString(4, bean.getTeam());
			pstmt.setInt(5, bean.getNum());			
			int cnt = pstmt.executeUpdate();
			if(cnt==1) {
				flag = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return flag;
	}
	
	// Delete
	public void deleteTeam(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		
		try {
			con = pool.getConnection();
			sql = "delete from tblTeam where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}

//	public static void main(String[] args) {
//		new TeamMgr();
//	system.out.println의 성공 확인 후 메인 부분은 주석
//	}

}

 

 

teamInsertProc.jsp

<%@page import="ch07.TeamBean" %>  
<%@page import="ch07.TeamMgr"%>
<%@page contentType="text/html; charset=EUC-KR" %>
<%
//ctrl + space	
	request.setCharacterEncoding("EUC-KR"); //post방식 한글처리
	//ctrl + alt + 방향키 : 복사됨 그러나 ctrl + c 저장과 별개
	String name= request.getParameter("name"); //String aaa도 가능. 뒤에만 같아야함
	String city = request.getParameter("city");
	int age = Integer.parseInt(request.getParameter("age"));
	String team = request.getParameter("team");
	
	//요청한 값을 DB에 저장하기 위한 타입 TeamBean 객체를 먼저 생성시킨 후 
	TeamBean bean = new TeamBean();
	bean.setName(name);
	bean.setCity(city);
	bean.setAge(age);
	bean.setTeam(team);
	
	//DB저장
	TeamMgr mgr= new TeamMgr();
	boolean result = mgr.insertTeam(bean);
	String msg = "가입실패";
	String location = "teamInsert.html";
	
	if (result) {
		msg = "가입성공";
		location = "teamList.jsp";
	}
%>
<%-- <%=result%> --%>
<script>
	alert("<%=msg%>");
	location.href = "<%=location%>";
</script>

 

 

teamInsertProc2.jsp

<%@page contentType="text/html; charset=EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); %>

<jsp:useBean id="mgr" class="ch07.TeamMgr" />
<%-- <% TeamMgr mgr = new TeamMgr() %> 7줄과 같다 --%>
<!-- 1.객체생성    2.scope:데이터를 공유하기 위해서 저장하는데 스코프에 담는 기능이 유즈빈에 있다. 3. 레퍼런스 변수.mgr-->
<jsp:useBean id="bean" class="ch07.TeamBean" />
 <jsp:setProperty property="*" name="bean"/>

<%
	boolean result = mgr.insertTeam(bean);

String msg = "가입실패";
String location = "teamInsert.html";

if (result) {
	msg = "가입성공";
	location = "teamList.jsp";
}

%>
 
<%--
<% 
	String name = request.getParameter("name");
	bean.setName(name);
%>
<jsp:setProperty property="age" name="bean"/>

<% 
	int age = Integer.parseInt(request.getParameter("age"));
	bean.setAge(age);
%> --%>

<script>
	alert("<%=msg%>");
	location.href = "<%=location%>";
</script>

 

 

server.xml 아래 부분 workDir 부분을 추가해준다. 

<Context docBase="myapp" path="/myapp" workDir="C:\Jsp\myapp\work" reloadable="true" source="org.eclipse.jst.jee.server:myapp"/></Host>

 

teamInsert.html 실행 후 Project Explorer 목록을 새로고침 해 준다.

 

 

 


목록


 

teamList.jsp

<%@page import="java.util.Vector"%>
<%@page import="ch07.TeamBean"%>
<%@page contentType="text/html; charset=EUC-KR" %>
<jsp:useBean id="mgr" class="ch07.TeamMgr" />
<%
	request.setCharacterEncoding("EUC-KR");
	//반드시 배열 및 Vector 밑에는 for가 있다.
	Vector<TeamBean> vlist=mgr.listTeam();
%>

<body>
<div align="center"><p/>
<h1>Team List</h1>
<table border="1">
	<tr>
		<th>번호</th>
		<th>이름</th>
		<th>사는곳</th>
		<th>나이</th>
		<th>팀명</th>
	</tr>
	<%
		for(int i=0; i<vlist.size(); i++)
		{
			TeamBean bean = vlist.get(i);
			int num = bean.getNum();
	
	%>
	<tr align = "center">
	<td><a href="teamSelect.jsp?num=<%=num%>"><%=i+1%></a></td>
	<td><%=bean.getName()%></td>
	<td><%=bean.getCity()%></td>
	<td><%=bean.getAge()%></td>
	<td><%=bean.getTeam()%></td>
	</tr>
	<%
	//for
		}
	%>
	</table><p/>
	<a href="teamInsert.html">INSERT</a>
	</div>	
</body>

 

 

teamSelect.jsp

<%@page import="ch07.TeamBean"%>
<%@page contentType="text/html; charset=EUC-KR" %>
<jsp:useBean id="mgr" class="ch07.TeamMgr" />

<%
	request.setCharacterEncoding("EUC-KR");
	int num=0;
	if(request.getParameter("num")!=null){
		num= Integer.parseInt(request.getParameter("num"));
	}else{
		response.sendRedirect("teamList.jsp");
	}
	TeamBean bean = mgr.getSelect(num);
	//방금 읽어온 회원정보를 세션에 저장
	session.setAttribute("bean", bean);
%>
<body>
<div align="center">
<h1>Team Select</h1>
<table border="1">
	<tr>
		<td width="50">번호</td>
		<td width="100"><%=bean.getNum()%></td>
	</tr>
	<tr>
		<td>이름</td>
		<td><%=bean.getName()%></td>
	</tr>
	<tr>
		<td>사는곳</td>
		<td><%=bean.getCity()%></td>
	</tr>
	<tr>
		<td>나이</td>
		<td><%=bean.getAge()%></td>
	</tr>
	<tr>
		<td>팀명</td>
		<td><%=bean.getTeam()%></td>
	</tr>
</table><p/>
<a href="teamList.jsp">LIST</a>&nbsp;&nbsp;
<a href="teamInsert.html">INSERT</a>&nbsp;&nbsp;
<a href="teamDelete.jsp?num=<%=num%>">DELETE</a>&nbsp;&nbsp;
<a href="teamUpdate.jsp?num=<%=num%>">UPDATE</a>&nbsp;&nbsp;
<a href="teamUpdate2.jsp">UPDATE2</a>&nbsp;&nbsp;
</div>
</body>

 

 

teamUpdate.jsp

<%@page import="ch07.TeamBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="mgr" class="ch07.TeamMgr" />

<%
	request.setCharacterEncoding("EUC-KR");
	int num=0;
	TeamBean bean = null;
	if(request.getParameter("num")==null){
		response.sendRedirect("teamList.jsp");
	}else { 
		num = Integer.parseInt(request.getParameter("num"));
		bean = mgr.getSelect(num);
	
%>

<body>
<div align="center">
<h1>Team Update</h1>
<form method="post" action="teamUpdateProc.jsp">
<table border="1">
<tr>
	<td width="50" align="center">번호</td>
	<td width="150">
		<input name="num" readonly value="<%=bean.getNum()%>">
	</td>
</tr>
<tr>
	<td  align="center">이름</td>
	<td>
		<input name="name" value="<%=bean.getName()%>">
	</td>
</tr>
<tr>
	<td align="center">사는곳</td>
	<td>
		<input name="city" value="<%=bean.getCity()%>">
	</td>
</tr>
<tr>
	<td align="center">나이</td>
	<td >
		<input name="age" value="<%=bean.getAge()%>">
	</td>
</tr>
<tr>
	<td align="center">팀명</td>
	<td>
		<input name="team" value="<%=bean.getTeam()%>">
	</td>
</tr>	
<tr>
	<td colspan="2" align="center">
		<input type="submit" value="UPDATE">
	</td>
</tr>
</table><p/>
</form>
<a href="teamSelect.jsp?num=<%=num%>">SELECT</a>
</div>
<% } %>
</body>

 

 

teamUpdateProc.jsp

<%@page contentType="text/html; charset=EUC-KR"%>
<%
	request.setCharacterEncoding("EUC-KR");
%>

<jsp:useBean id="mgr" class="ch07.TeamMgr" />
<%-- <% TeamMgr mgr = new TeamMgr() %> 7줄과 같다 --%>
<!-- 1.객체생성    2.scope:데이터를 공유하기 위해서 저장하는데 스코프에 담는 기능이 유즈빈에 있다. 3. 레퍼런스 변수.mgr-->
<jsp:useBean id="bean" class="ch07.TeamBean" />
<jsp:setProperty property="*" name="bean" />

<%
	boolean result = mgr.updateTeam(bean);

	String msg = "수정실패";
	String location = "teamList.jsp";

	if (result) {
		msg = "수정성공";
		location = "teamSelect.jsp?num=" + bean.getNum();
	}
%>

<script>
	alert("<%=msg%>");
	location.href = "<%=location%>";
</script>

 

 

teamUpdate2.jsp

<%@page import="ch07.TeamBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- 기능 두개. 세션에 bean이라는 이름으로 객체를 생성.그러나 이미 있다면 그걸 가져옴 -->
<!--스코프의 범위는 총 4개 : page(같은페이지)<request(요청한페이지까지)<session(모든페이지)<app(서버삭제전까지유지)  저장공간-->
<jsp:useBean id="bean" scope="session" class="ch07.TeamBean" />
<%
	TeamBean bean1 = (TeamBean)session.getAttribute("bean"); //똑같은거지만 기능하나
%>
<body>
<div align="center">
<h1>Team Update2</h1>
<form method="post" action="teamUpdateProc.jsp">
<table border="1">
<tr>
	<td width="50" align="center">번호</td>
	<td width="150">
		<input name="num" readonly value="<%=bean.getNum()%>">
	</td>
</tr>
<tr>
	<td  align="center">이름</td>
	<td>
		<input name="name" value="<%=bean.getName()%>">
	</td>
</tr>
<tr>
	<td align="center">사는곳</td>
	<td>
		<input name="city" value="<%=bean.getCity()%>">
	</td>
</tr>
<tr>
	<td align="center">나이</td>
	<td >
		<input name="age" value="<%=bean.getAge()%>">
	</td>
</tr>
<tr>
	<td align="center">팀명</td>
	<td>
		<input name="team" value="<%=bean.getTeam()%>">
	</td>
</tr>	
<tr>
	<td colspan="2" align="center">
		<input type="submit" value="UPDATE">
	</td>
</tr>
</table><p/>
</form>
<a href="teamSelect.jsp?num=<%=bean.getNum()%>">SELECT</a>
</div>
</body>
728x90
728x90

'SQL > MySQL' 카테고리의 다른 글

mysql (3) 세션  (0) 2019.07.09
mysql (1) 설치 및 이클립스 환경 구축  (0) 2019.07.08
블로그 이미지

coding-restaurant

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

,

v