note

MVC 회원관리 프로그램 Model2 본문

JSP/기본

MVC 회원관리 프로그램 Model2

투한 2012. 2. 15. 14:17







패턴

mvc2Main2
dr.mini.controller
Action
Controller 
dr.mini.action
InsertFormAction 
dr.mini.dao
MemberDao
dr.mini.domain
Member

WebContent
view
insertForm.jsp 
META-INF
context.xml
META-INF
commandMap.properties

 



자바빈 구성
DAO 생성
InsertFormAction
commandMap.properties
web.xml 

 
commandMap.properties
/insertForm.do=dr.mini.action.InsertFormAction
/insert.do=dr.mini.action.InsertAction
/selectList.do=dr.mini.action.SelectListAction
/selectDetail.do=dr.mini.action.SelectDetailAction
/updateForm.do=dr.mini.action.UpdateFormAction
/update.do=dr.mini.action.UpdateAction
/deleteForm.do=dr.mini.action.DeleteFormAction
/delete.do=dr.mini.action.DeleteAction

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>mvcMain2</display-name>
  
  <!-- Controller Start -->
  <servlet>
  	<servlet-name>Controller</servlet-name>
  	<servlet-class>dr.mini.controller.Controller</servlet-class>
  	<init-param>
  		<param-name>configFile</param-name>
  		<param-value>/WEB-INF/commandMap.properties</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>Controller</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- Controller End -->
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Member.java
package dr.mini.domain;

import java.sql.Timestamp;

public class Member {

	private String id;
	private String passwd;
	private String name; 
	private Timestamp register;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}
}


MemberDao.java
package dr.mini.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import dr.mini.domain.Member;

public class MemberDao {
	private static MemberDao instance = 
			new MemberDao();

	public static MemberDao getInstance() {
		return instance;
	}

	private MemberDao(){}

	//회원 가입
	public void insertMember(Member member)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = "";
		int cnt = 0;

		try{
			//커넥션 풀로부터 커넥션 할당
			conn = getConnection();
			sql = "insert into MEMBER1 (id,passwd,name,register) values(?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(++cnt, member.getId());
			pstmt.setString(++cnt, member.getPasswd());
			pstmt.setString(++cnt, member.getName());
			pstmt.setTimestamp(++cnt, member.getRegister());

			pstmt.executeUpdate();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(null,pstmt,conn);
		}
	}
	//회원 목록 보기
	public List<Member> getMemberList()throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Member> list = null;
		String sql = "";
		try{
			conn=getConnection();
			sql="select * from MEMBER1 order by register desc";
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();

			if(rs.next()){
				list = new ArrayList<Member>();
				do{
					Member member = new Member();
					member.setId(rs.getString("id"));
					member.setPasswd(rs.getString("passwd"));
					member.setName(rs.getString("name"));
					member.setRegister(rs.getTimestamp("register"));

					list.add(member);
				}while(rs.next());
			}else{
				//데이터가 없을 경우 비어있는 List 생성(이게 없으면 NullpointException발생)
				list =Collections.emptyList();
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(rs,pstmt,conn);
		}
		return list;
	}
	//회원 상세 정보 보기
	public Member getMember(String id)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Member member =null;
		String sql = "";
		try{
			conn=getConnection();
			sql = "select * from MEMBER1 where id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();

			//rs ResultSet의 커서 위치는 행밖의 위치해 있기때문에 한건의 레코드를 가져오더라도
			//next()메소드를 사용해서 빼낸다
			if(rs.next()){
				member = new Member();

				member.setId(rs.getString("id"));
				member.setPasswd(rs.getString("passwd"));
				member.setName(rs.getString("name"));
				member.setRegister(rs.getTimestamp("register"));
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(rs,pstmt,conn);
		}
		return member;
	}
	//회원 인증
	public int userCheck(String id,String passwd)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		String dbpasswd="";
		int x=-1;
		try{
			conn=getConnection();
			sql="select passwd from MEMBER1 where id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,id);
			rs=pstmt.executeQuery();

			if(rs.next()){
				dbpasswd= rs.getString("passwd");
				if(dbpasswd.equals(passwd))
					x=1;//인증 성공
				else
					x=0;//비밀번호 틀림
			}else
				x= -1;//해당아이디 없음
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(rs,pstmt,conn);
		}
		return x;
	}
	//회원 정보 수정
	public void updateMember(Member member)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql="";
		try{
			conn = getConnection();
			sql = "update MEMBER1 set name=? where id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,member.getName());
			pstmt.setString(2,member.getId());

			pstmt.executeUpdate();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(null,pstmt,conn);
		}
	}
	//회원 탈퇴(삭제)
	public void deleteMember(String id)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try{
			conn=getConnection();
			sql = "delete from MEMBER1 where id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,id);
			pstmt.executeUpdate();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			execClose(null,pstmt,conn);
		}
	}
	private Connection getConnection()throws Exception {
		Context initCtx = new InitialContext();
		Context envCtx = 
				(Context)initCtx.lookup("java:comp/env");
		DataSource ds = 
				(DataSource)envCtx.lookup("jdbc/orcl");
		return ds.getConnection();
	}
	//자원정리
	private void execClose(ResultSet rs, PreparedStatement pstmt,
			Connection conn)throws Exception {
		if (rs != null) try { rs.close(); } catch(SQLException ex) {}
		if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
		if (conn != null) try { conn.close(); } catch(SQLException ex) {}
	}
}
 


Action.java
package dr.mini.controller;

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

//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
    public String execute(HttpServletRequest request,
    		            HttpServletResponse response)
    throws Throwable;
}



Controller
package dr.mini.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
           
public class Controller extends HttpServlet {
	
    private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장

    //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
	//명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
    public void init(ServletConfig config) throws ServletException {
		String configFile = config.getInitParameter("configFile");
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			String configFilePath = config.getServletContext().getRealPath(
					configFile);
			fis = new FileInputStream(configFilePath);
			prop.load(fis);
		} catch (IOException e) {
			throw new ServletException(e);
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException ex) {
				}
		}
		Iterator keyIter = prop.keySet().iterator();
		while (keyIter.hasNext()) {
			String command = (String) keyIter.next();
			String handlerClassName = prop.getProperty(command);
			try {
				Class handlerClass = Class.forName(handlerClassName);
				Object handlerInstance = handlerClass.newInstance();
				commandMap.put(command, handlerInstance);
			} catch (ClassNotFoundException e) {
				throw new ServletException(e);
			} catch (InstantiationException e) {
				throw new ServletException(e);
			} catch (IllegalAccessException e) {
				throw new ServletException(e);
			}
		}
	}

    public void doGet(//get방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    protected void doPost(//post방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    //시용자의 요청을 분석해서 해당 작업을 처리
    private void requestPro(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		String view = null;
        Action com=null;
        
		try {
            String command = request.getRequestURI();
            if (command.indexOf(request.getContextPath()) == 0) {
               command = command.substring(request.getContextPath().length());
            }
            com = (Action)commandMap.get(command); 
            view = com.execute(request, response);
        } catch(Throwable e) {
            throw new ServletException(e);
        }   
        RequestDispatcher dispatcher =request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}




추가


insertForm.do 실행



아이디 패스워드 이름 입력
 목록보기

DB에 저장됨


리스트





회원 상세정보



InsertAction.java
package dr.mini.action;

import java.sql.Timestamp;

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

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class InsertAction implements Action{

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Throwable {
		
		request.setCharacterEncoding("UTF-8");
		
		Member member = new Member();
		member.setId(request.getParameter("id"));
		member.setName(request.getParameter("name"));
		member.setPasswd(request.getParameter("passwd"));
		member.setRegister(new Timestamp(System.currentTimeMillis()));
		
		MemberDao manager = MemberDao.getInstance();
		manager.insertMember(member);
		
		return "/view/insert.jsp";
	}

}



InsertFormAction.java
package dr.mini.action;

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

import dr.mini.controller.Action;

public class InsertFormAction implements Action{

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Throwable {
		
		return "/view/insertForm.jsp";
	}

}





수정



수정

수정값 가지고온 모습







aaa.jsp

aa
aaa.jsp
aa
aaa.jsp
aa








삭제












aaa.jsp

aa
aaa.jsp
aa
aaa.jsp
aa
aaa.jsp
aa







 

'JSP > 기본' 카테고리의 다른 글

방명록 프로그램 MODEL2  (0) 2012.02.16
회원관리 프로그램 가입,로그인 MVC MODEL2방식  (1) 2012.02.16
MVC 패턴  (0) 2012.02.15
MVC패턴 model2  (0) 2012.02.14
properties 국제화(에디터)  (0) 2012.02.14