toggle menu

JSP 정리 - Beans

2012. 8. 20. 09:06 JAVA/JSP
자바 클래스들을 모아 놓은 패키지.


Mdel
Control
View
를 나누어서 

빈즈는 순수 자바로 만들어져 있다. HttpServlet을 상속받지 않았다.


객체를 생성해서 사용할 수도 있지만,

<jsp:useBean class="패키지명.클래스" id="아이디값" scope="범위?" />

위의 태그는 아래와 동일하다.

<% 클래스명 아이디값 = new 클래스명(); %>


BoardVO 처럼 getter, setter가 있을텐데,

<jsp:setProperty name="위의 아이디값" property="변수명">

이런식으로 지정한다.


FORM과 JAVA 안의 변수명과 빈즈에서의 set,get의 프로퍼티이름은 모두 같아야 한다.
대소문자를 구분하는 것을 주의!!

만약 property에 *을 넣으면 모두 넣을 수 있다!!


꺼낼때는
<jsp:getProperty name="위의 아이디값" property="변수명">
이렇게 하나씩만 가져오게 되고 해당 위치에 출력된다.




데이터베이스에 접속할 때는 마찬가지로ㅡ
<jsp:useBean class="클래스명~"  id="dao블라~" >



scope의 기본값은 page -> 현재 페이지에서 종료
request, session, application

session -> 세션이 유지되는 동안 유지
request -> 리퀘스트로 요청되는 동안. FORM으로 넘어오는..
application -> 내내..







클라이언트 - 컨트롤러 - 모델
MVC

되도록 다양한 개발자가 개발하더라도 통일성을 갖을 수 있도록 틀을 만들어놓을 것을 프레임웍!!







간단한 회원 등록, 검색, 삭제 관련 예제


JOIN.HTML
<!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>
<script type="text/javascript">
	function input_check()
	{
		if(document.joinForm.id.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.id.focus();
		}
		else if(document.joinForm.pw.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.pw.focus();
		}
		else if(document.joinForm.name.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.name.focus();
		}
		else if(document.joinForm.age.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.age.focus();
		}
		else if(document.joinForm.addr.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.addr.focus();
		}
		else if(document.joinForm.jumin1.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.jumin1.focus();
		}
		else if(document.joinForm.jumin2.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.joinForm.jumin2.focus();
		}
		else
		{
			return true;
		}
		
		return false;
	}
</script>

</head>
<body>
<h2> 회원 가입</h2>

<form name="joinForm" method="post" action="/jspExam/memberProServlet" OnSubmit="return input_check()">
  ID : <input type="text" name="id" /><br/>
  PWD : <input type="password" name="pw" /></br/>
  NAME : <input type="text" name="name" /></br/>
  AGE : <input type="text" name="age" /></br/>
  ADDR : <input type="text" name="addr" /></br/>
  JUMIN1 : <input type="text" name="jumin1" /></br/>
  JUMIN2 : <input type="text" name="jumin2" /></br/>
  
  <input type="submit" value="가입" />
</form>

</body>
</html>




JOIN 폼에서 넘어온 값을 처리하는 memberPro.jsp
<%@page import="ex0820.model.memberDAO"%>
<%@ 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></title>
		<style></style>
		<script type="text/javascript"></script>
	</head>

	<body>
<%
	request.setCharacterEncoding("UTF-8");
%>
	
	<jsp:useBean id="memberVO" class="ex0820.model.memberVO" scope="request"/>
	<jsp:setProperty property="*" name="memberVO"/>
	
<%
	if( new memberDAO().userInsert(memberVO) )
	{
		out.write("<script> window.alert('멤버를 성공적으로 추가했지 말입니다.'); location.href = 'memberSelect.jsp'; </script>");
	}
	else
	{
		out.write("<script> window.alert('멤버 추가에 실패했습니다.'); history.back(); </script>");		
	}
%>
	</body>
</html>





memberPro.jsp와 같은 기능을 수행하는 자바서블릿 파일
package ex0820.model;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class memberProServlet
 */
public class memberProServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8"); //POST로 넘어오는 값의 인코딩을 설정
		response.setContentType("text/html; charset=UTF-8"); //출력할 페이지의 인코딩을 설정
		PrintWriter out = response.getWriter(); //출력 스트림 가져오기
		
		memberVO temporaryVO = new memberVO();

		try
		{
			temporaryVO.setId(new String(request.getParameter("id").trim()));
			temporaryVO.setName(new String(request.getParameter("name").trim()));
			temporaryVO.setPw(new String(request.getParameter("pw").trim()));
			temporaryVO.setAge(new Integer(request.getParameter("age").trim()));
			temporaryVO.setAddr(new String(request.getParameter("addr").trim()));
			temporaryVO.setJumin1(new String(request.getParameter("jumin1").trim()));
			temporaryVO.setJumin2(new String(request.getParameter("jumin2").trim()));
			
			if( new memberDAO().userInsert(temporaryVO) )
			{
				out.write("<script> window.alert('멤버를 성공적으로 추가했지 말입니다.'); location.href = 'http://localhost:8080/jspExam/ex0820/memberSelect.jsp'; </script>");
			}
			else
			{
				out.write("<script> window.alert('멤버 추가에 실패했습니다.'); history.back(); </script>");		
			}

		}
		catch(Exception e)
		{
			out.write("<script> window.alert('멤버 추가에 실패했습니다.'); history.back(); </script>");
		}
	}
}








데이터베이스에 관련된 기본 상수를 저장한 클래스 파일 DatabaseConstant.java
package ex0820.model;

public class DatabaseConstant
{
	public final static String DRIVERNAME = "oracle.jdbc.driver.OracleDriver";
	public final static String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
	public final static String USER = "scott";
	public final static String PASSWORD = "tiger";
}






데이터베이스 입출력 관련 모든 작업을 관장하는 memberDAO.java

package ex0820.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


public class memberDAO
{
	// *** DB 관련 변수 선언 ***
    
    Connection connection;
    PreparedStatement preparedStatement;
    Statement statement;
    ResultSet resultSet;
    
    

    // *** 상수 선언 ***
    
    public final int SEARCH_ID = 0;
    public final int SEARCH_NAME = 1;
    public final int SEARCH_ADDR = 2;
    public final int SEARCH_ALL = 3;
    public final int SEARCH_NONE = 4;
    
    
    
	public memberDAO()
	{
        try
        {
            // ① 로드
            Class.forName(DatabaseConstant.DRIVERNAME);
              
 
            // *** DB 생성 ***
             
            // ② 연결
            connection = DriverManager.getConnection(DatabaseConstant.URL, DatabaseConstant.USER, DatabaseConstant.PASSWORD);
  
            // ② 연결 [Statement]
            statement = connection.createStatement();
  
            // ③ 실행 [CRUD]
            resultSet = statement.executeQuery("SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE TABLE_NAME='MEMBER'");
             
            int result = 0;
             
            if(resultSet.next())
            {
                result = Integer.valueOf(resultSet.getString(1));
            }
             
            // 테이블이 생성되지 않은 경우 생성!
            if( result == 0 )
            {
                statement.executeUpdate("CREATE TABLE MEMBER ( ID VARCHAR2(30) PRIMARY KEY, PW VARCHAR2(20), NAME VARCHAR2(30), AGE INT, ADDR VARCHAR2(100), JUMIN1 VARCHAR2(20), JUMIN2 VARCHAR2(20) )");
            }
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("[로드 오류]\n" + e.getStackTrace());
        }
        catch (SQLException e)
        {
            System.out.println("[연결 오류]\n" +  e.getStackTrace());
        }
         
        finally
        {
            closeDatabase();
        }
         
	
	}
	
	
    public void closeDatabase()
    {
        try
        {
            if( connection != null )
            {
                connection.close();
            }
              
            if( statement != null )
            {
                statement.close();
            }

            if( preparedStatement != null )
            {
                preparedStatement.close();
            }
			
            if( resultSet != null )
            {
                resultSet.close();
            }
        }
        catch (SQLException e)
        {
            System.out.println("[닫기 오류]\n" +  e.getStackTrace());
        }
    }
    
    
    public boolean userInsert(memberVO vo)
    {
        int result = 0;
        
        try
        {
            // ② 연결
            connection = DriverManager.getConnection(DatabaseConstant.URL, DatabaseConstant.USER, DatabaseConstant.PASSWORD);
  
            // ③ 실행 [CRUD]
            preparedStatement = connection.prepareStatement("INSERT INTO MEMBER VALUES(?, ?, ?, ?, ?, ?, ?)");
            preparedStatement.setString(1, vo.getId());
            preparedStatement.setString(2, vo.getPw());
            preparedStatement.setString(3, vo.getName());
            preparedStatement.setInt(4, vo.getAge());
            preparedStatement.setString(5, vo.getAddr());
            preparedStatement.setString(6, vo.getJumin1());
            preparedStatement.setString(7, vo.getJumin2());
             
            // ③ 실행 [CRUD]
            result = preparedStatement.executeUpdate();
              
        }
        catch (SQLException e)
        {
            System.out.println("[연결 오류]\n" +  e.getStackTrace());
        }
         
        finally
        {
            closeDatabase();
        }
         
        return (result > 0) ? true : false;
    }
    
    
    public ArrayList<memberVO> userSearch(int searchMode, String keyWord)
    {
    	ArrayList<memberVO> temporaryList = new ArrayList<memberVO>();
    	
        try
        {
            // ② 연결
            connection = DriverManager.getConnection(DatabaseConstant.URL, DatabaseConstant.USER, DatabaseConstant.PASSWORD);
             
            // ② 연결 [Statement]
            statement = connection.createStatement();
  
            // ③ 실행 [CRUD]
             
            switch( searchMode )
            {
                //아이디
                case SEARCH_ID:
                    resultSet = statement.executeQuery("SELECT * FROM MEMBER WHERE ID LIKE '%" + keyWord + "%'");
                break;
 
                //이름
                case SEARCH_NAME:
                    resultSet = statement.executeQuery("SELECT * FROM MEMBER WHERE NAME LIKE '%" + keyWord + "%'");
                break;
                 
                 
                //주소
                case SEARCH_ADDR:
                    resultSet = statement.executeQuery("SELECT * FROM MEMBER WHERE ADDR LIKE '%" + keyWord + "%'");
                break;
                 
                //이름, 주소, 아이디에서 검색
                case SEARCH_ALL:
                    resultSet = statement.executeQuery("SELECT DISTINCT * FROM MEMBER WHERE ID LIKE '%" + keyWord + "%' OR NAME LIKE '%" + keyWord + "%' OR ADDR LIKE '%" + keyWord + "%'");
                break;
                 
                //검색 안함
                case SEARCH_NONE:
                    resultSet = statement.executeQuery("SELECT * FROM MEMBER");
                break;
                 
            }
             
            while (resultSet.next())
            {
            	temporaryList.add(new memberVO(resultSet.getString(1), resultSet.getString(2), resultSet.getString(3), resultSet.getInt(4), resultSet.getString(5), resultSet.getString(6), resultSet.getString(7)));
            }
        }
        catch (SQLException e)
        {
            System.out.println("[연결 오류]\n" +  e.getStackTrace());
        }
         
        finally
        {
            closeDatabase();
        }
        
        return temporaryList;
    }
    
    
    public boolean memberDelete(String id)
    {
         
        int result = 0;
         
        try
        {
            // ② 연결
            connection = DriverManager.getConnection(DatabaseConstant.URL, DatabaseConstant.USER, DatabaseConstant.PASSWORD);
  
            // ③ 실행 [CRUD]
            preparedStatement = connection.prepareStatement("DELETE FROM MEMBER WHERE ID=?");
            preparedStatement.setString(1, id);
 
            result = preparedStatement.executeUpdate();
              
        }
        catch (SQLException e)
        {
            System.out.println("[연결 오류]\n" +  e.getStackTrace());
        }
         
        finally
        {
            closeDatabase();
        }
         
        return (result > 0) ? true : false;
    }        
    
}








멤버들의 목록을 출력해주는 memberSelect.jsp
<%@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></title>
		<style>
			a:link    {text-decoration:none; color:deeppink;}
			a:visited {text-decoration:none; color:deeppink;}
			a:hover   {text-decoration:none; color:#336699;}
			a:active  {text-decoration:none; color:deeppink;}
			
			body
			{
				font-size:12px;
			}
			
			table
			{
				border-collapse: collapse;
				font: normal 12px 돋움체, verdana, arial, helvetica, sans-serif;
				color: #363636;
				width: 100%;
			}
			tr
			{
				border-bottom:1px dotted #DDDDDD;
			}
			td
			{
				text-align:center;
			}
			.submit
			{
				font-family: Arial, Helvetica, sans-serif;
				font-size: 12px;
				color: #ffffff;
				padding-left: 5px;
				padding-right: 5px;
				padding-top: 2px;
				padding-bottom: 2px;
				background: #000000;
				border: 1px solid #141414;
				width: auto;
				overflow: visible;
			}

			.titleTable { font-family:tahoma; color:white; font-weight:bold;}

			
		</style>
		<script type="text/javascript">
	function input_check()
	{
		if(document.searchForm.keyWord.value.length == 0)
		{
            window.alert('값을 입력해주세요!');
            document.searchForm.keyWord.focus();
		}
		else
		{
			return true;
		}
		
		return false;
	}
	
	function delete_check()
	{
		if(confirm('삭제하시겠습니까?'))
		{
			return true;
		}
		
		return false;
	}
</script>
	</head>

	<body>

<jsp:useBean class="ex0820.model.memberDAO" id="memberDAO" scope="page" />

<P ALIGN="RIGHT">
<a href="JoinForm.html">회원가입SERVLET</a>
<a href="JoinForm2.html">회원가입JSP</a>
</P>

<TABLE>
<TR BGCOLOR="#336699" class="titleTable">
	<TD>아이디</TD>
	<TD>이름</TD>
	<TD>패스워드</TD>
	<TD>나이</TD>
	<TD>주소</TD>
	<TD COLSPAN="3">주민등록번호</TD>
	<TD>삭제</TD>
</TR>
<%
	request.setCharacterEncoding("UTF-8");

	String searchMode = request.getParameter("searchMode");
	String keyWord = request.getParameter("keyWord");
	

	try
	{
		new Integer(searchMode);
		new String(keyWord);
	}
	catch(Exception e)
	{
		searchMode = "4";
	}

	for(ex0820.model.memberVO vo : memberDAO.userSearch(new Integer(searchMode), keyWord) )
	{
		out.write("<TR><TD>" + vo.getId() + "</TD>");
		out.write("<TD>" + vo.getName() + "</TD>");
		out.write("<TD>" + vo.getPw() + "</TD>");
		out.write("<TD>" + vo.getAge() + "</TD>");
		out.write("<TD>" + vo.getAddr() + "</TD>");
		out.write("<TD WIDTH=50>" + vo.getJumin1() + "</TD>");
		out.write("<TD WIDTH=2>-</TD>");
		out.write("<TD WIDTH=50>" + vo.getJumin2() + "</TD>");
		out.write("<TD><FORM METHOD=\"post\" ACTION=\"memberDelete.jsp\" onSubmit=\"return delete_check()\"><INPUT TYPE=\"HIDDEN\" NAME=\"id\" VALUE=\"" + vo.getId() + "\"><INPUT TYPE=\"SUBMIT\" VALUE=\"삭제\" class=\"submit\"></FORM></TD></TR>");
	}

%>
</TABLE>


<DIV ALIGN="CENTER">
<form name="searchForm" method="post" action="memberSelect.jsp" OnSubmit="return input_check()">
<SELECT NAME="searchMode">
     <OPTION VALUE="0" SELECTED>아이디</OPTION>
     <OPTION VALUE="1">이름</OPTION>
     <OPTION VALUE="2">주소</OPTION>
     <OPTION VALUE="3">전체</OPTION>
 </SELECT>
  
<input type="text" name="keyWord" /><input type="submit" value="검색" class="submit"/><input type="button" value="취소" class="submit" onClick="location.href = 'memberSelect.jsp';"/>
</form>
</DIV>


	</body>
</html>






멤버를 삭제할 때 사용되는 memberDelete.jsp
<%@page import="ex0820.model.memberDAO"%>
<%@ 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></title>
		<style></style>
		<script type="text/javascript"></script>
	</head>

	<body>
<%
	request.setCharacterEncoding("UTF-8");
	String id = request.getParameter("id");
	
	if(id == null)
	{
		out.write("<script> window.alert('id값이 존재하지 않습니다.'); history.back(); </script>");
	}
	else
	{
		if( new memberDAO().memberDelete(id) )
		{
			out.write("<script> window.alert('멤버를 성공적으로 삭제했지 말입니다.'); location.href = 'memberSelect.jsp'; </script>");
		}
		else
		{
			out.write("<script> window.alert('멤버 삭제에 실패했습니다.'); history.back(); </script>");		
		}
	}
%>
	</body>
</html>






JAVA/JSP 관련 포스팅 더보기