개발자가 되고 싶은 조안나

[JAVA] 로그인 기능 본문

코드 정리

[JAVA] 로그인 기능

햇병아리개발자 2019. 8. 14. 10:06

벌써 두 번째 프로젝트. 

이번에 맡은 기능은 관리자 로그인/ 게시판/ 오시는길을 맡았다. 

막상 해 놓고 보니 여전히 부족한게 많이 보이지만

그래도 첫 프로젝트 때를 생각하면 조금은 나아졌지 않나 싶고 

정말 개발자 될 수 있을까..

 

// -View -> Controller -> Service -> Dao  

cmn.DTO

package cmn;

/**
 * @author SIST
 *
 */
public class DTO {
	private int    total     ;   //총글수 
	private int    num       ;   //글번호
	private int wFlag; //flag  
	
	
	public DTO(){}

AdminVO

package admin;

import cmn.DTO;

public class AdminVO  extends DTO{
	/**관리자 계정*/
	private String admin;
	/**관리자 비번*/
	private String pw;
	
	public AdminVO(){
		   
	   }

AdminDao

package admin;

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

import org.apache.log4j.Logger;

import cmn.ConnectionMaker;
import cmn.DTO;
import cmn.JDBCReturnReso;
import cmn.MessageVO;
import cmn.WorkDiv;

public class AdminDao implements WorkDiv {

	private final Logger LOG = Logger.getLogger(AdminDao.class);
	private ConnectionMaker  connectionMaker;
	
	private static AdminDao instance =new AdminDao();
	
	public static AdminDao getInstance(){
	return instance;
	}

	public AdminDao(){
		connectionMaker = new ConnectionMaker();
	}
    //패스워드
	public MessageVO passCheck(DTO dto) {
		AdminVO adminVO= (AdminVO) dto;
		MessageVO outVO= new MessageVO();
        int result =0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		
		try{
			StringBuilder sb=new StringBuilder();
			 sb.append(" SELECT COUNT(*) cnt		\n");
			 sb.append(" FROM admin                 \n");
			 sb.append(" WHERE admin = ?            \n");
			 sb.append(" AND PW= ?                  \n");
			
			 conn = connectionMaker.getConnection();
				LOG.debug("1. conn:"+conn);
				LOG.debug("2. sql:\n"+sb.toString());
			
				pstmt = conn.prepareStatement(sb.toString());
				pstmt.setString(1, adminVO.getAdmin());
				pstmt.setString(2, adminVO.getPw());
				LOG.debug("3. param:"+adminVO.getAdmin());
				LOG.debug("3. param:"+adminVO.getPw());
			
			rs = pstmt.executeQuery();
			if(rs.next()){
				result = rs.getInt("cnt");
				if(result==0){//비밀번호를 확인
					outVO.setMsgId("20");
					outVO.setMsgContents("비밀번호를 확인하세요");
				}else{
					outVO.setMsgId("1");
					outVO.setMsgContents("비번ok.");
				}
			}
			
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			JDBCReturnReso.close(rs);
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);		
		}
		
		
		return outVO;
	}
	
	/**Admin 단건조회*/
	@Override
	public AdminVO do_selectOne(DTO dto) {
		AdminVO adminVO= (AdminVO) dto;
		AdminVO outVO = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		
		try{
			StringBuilder sb=new StringBuilder();
			sb.append(" SELECT		   \n");
			sb.append("     admin,     \n");
			sb.append("     pw         \n");
			sb.append(" FROM           \n");
			sb.append("     admin      \n");
			sb.append(" WHERE admin = ?  \n");
			
			conn = connectionMaker.getConnection();
			LOG.debug("1.============================");
			LOG.debug("1.query: \n"+sb.toString());
			LOG.debug("1.============================");
			
			pstmt=conn.prepareStatement(sb.toString());
			//query param
			pstmt.setString(1,adminVO.getAdmin());
			LOG.debug("2.============================");
			LOG.debug("2.param getAdmin="+adminVO.getAdmin());
			LOG.debug("2.============================");	
	
			rs = pstmt.executeQuery();
			if(rs.next()){
				outVO = new AdminVO();
				outVO.setAdmin(rs.getString("Admin"));
				outVO.setPw(rs.getString("Pw"));
		}
		}catch(SQLException e){
			LOG.debug("===================");
			LOG.debug("SQLException="+e.getMessage());
			LOG.debug("===================");
		}finally{
			JDBCReturnReso.close(rs);
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);
		}
		return outVO;
	}
	
	
	//아이디
	public MessageVO idCheck(DTO dto) {
		AdminVO adminVO= (AdminVO) dto;
		MessageVO outVO= new MessageVO();
        int result =0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		
		try{
			StringBuilder sb=new StringBuilder();
			 sb.append(" SELECT COUNT(*) cnt		\n");
			 sb.append(" FROM admin                 \n");
			 sb.append(" WHERE admin = ?            \n");
			
			 conn = connectionMaker.getConnection();
				LOG.debug("1. conn:"+conn);
				LOG.debug("2. sql:\n"+sb.toString());
			
			pstmt=conn.prepareStatement(sb.toString());
			pstmt.setString(1,adminVO.getAdmin());
			LOG.debug("3. param:"+adminVO.getAdmin());
			
			rs = pstmt.executeQuery();
			if(rs.next()){
				result = rs.getInt("cnt");
				if(result==0){//id가 0이면 '아이디를 확인하세요'
					outVO.setMsgId("10");
					outVO.setMsgContents("id를 확인하세요");
				}else{
					outVO.setMsgId("1");
					outVO.setMsgContents("id가 있습니다.");
				}
			}
			
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			JDBCReturnReso.close(rs);
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);		
		}
		
		
		return outVO;
	}

AdminService

package admin;

import org.apache.log4j.Logger;

import cmn.DTO;
import cmn.MessageVO;



public class AdminService {
	// -View -> Controller -> Service -> Dao  
	private final Logger LOG=Logger.getLogger(AdminService.class);
	
	private AdminDao adminDao;
	
	public AdminService(){
		LOG.debug("0-------------------");
		adminDao = new AdminDao();
		LOG.debug("-adminDao-"+adminDao);
		LOG.debug("0-------------------");	
		
	}
	public MessageVO loginCheck(DTO dto){
		MessageVO outVO =new MessageVO();
		//01:ID CHECK
		outVO = adminDao.idCheck(dto);
		if(!outVO.getMsgId().equals("1")){
			return outVO;
		}
		//O2: 비밀번호 체크
		outVO = adminDao.passCheck(dto);
		if(!outVO.getMsgId().equals("1")){
			return outVO;
		}
		return outVO;
	}
	
	public AdminVO do_selectOne(DTO dto){
		return adminDao.do_selectOne(dto);
	}
}

AdiminCtrl (workDiv : 기능 분기)

package admin;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import cmn.MessageVO;
import cmn.StringUtil;


@WebServlet(description = "로그인", urlPatterns = { "/admin/admin.do","/admin/admin.json" })
public class AdiminCtrl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final Logger LOG=Logger.getLogger(AdminService.class);
	
	private AdminService adminService;
	
	public AdiminCtrl(){
		LOG.debug("0-------------------");
		adminService = new AdminService();
		LOG.debug("-adminService-"+adminService);
    	LOG.debug("0-------------------");
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("01 doGet()");
		LOG.debug("01.1 adminService:"+adminService);
		doServiceHandler(request,response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("01 doPost()");
		LOG.debug("01.1 adminService:"+adminService);
		doServiceHandler(request,response);
	}

	public void doServiceHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	//기능 : do_retrieve,do_insert,do_update,do_selectone,do_retrieve
    	//work_div
    	LOG.debug("02 doServiceHandler()");
    	request.setCharacterEncoding("UTF-8");
    	//work_div:read
    	String workDiv = StringUtil.nvl(request.getParameter("work_div"),"");
    	LOG.debug("02.1 workDiv:"+workDiv);
    	
    	/* do_retrieve:목록
    	 * do_insert:등록
    	 * do_update:수정
    	 * do_selectone:단건조회
    	 * do_delete:
    	 */
    	switch(workDiv){
    		case "do_logout":
    			do_logout(request,response);
    		break;
    	    case "do_login":
    	    	do_login(request,response);
    		break;
    	    case "do_move_to_main":
    	    	do_move_to_main(request,response);
    		break;   
    		     		
    	}
	}

AdiminCtrl (로그인)

//do_login
	protected void do_login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  LOG.debug("03.1 do_login");
	  
	  //param 세팅
	  AdminVO inVO = new AdminVO();
	  
	  String admin =StringUtil.nvl(request.getParameter("user_id"),"");
      String pw =StringUtil.nvl(request.getParameter("passwd"),"");
      
      inVO.setAdmin(admin);
      inVO.setPw(pw);
      LOG.debug("03.2 inVO:"+inVO);
      
      MessageVO checkMsg = adminService.loginCheck(inVO);
      AdminVO outVO = new AdminVO();
      if(checkMsg.getMsgId().equals("1")){
    	  outVO = adminService.do_selectOne(inVO);
    	//session:
      	HttpSession session = request.getSession();
      	session.setAttribute("user", outVO);
      	session.setAttribute("admin", outVO.getAdmin()); 
    	LOG.debug("03.3 OutVO:"+outVO); 
      }
	    //JSON
	  	Gson gson=new Gson();
	  	response.setContentType("text/html;charset=utf-8");
	  	PrintWriter out =response.getWriter();
	  	String gsonString = "";
	  	gsonString = gson.toJson(checkMsg);
	  	LOG.debug("03.4 gsonString:"+gsonString);
	  	out.print(gsonString);
        
     }
	

AdiminCtrl (로그아웃)

//LOGOUT
	protected void do_logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	LOG.debug("03.1 do_logout");
    	//1.session삭제
    	HttpSession  httpSession = request.getSession();
    	if(null !=httpSession ){
    		LOG.debug("03.2 httpSession"+httpSession);
    		httpSession.removeAttribute("admin");
    		httpSession.removeAttribute("id");
    		
    		httpSession.invalidate();
    		LOG.debug("03.3 httpSession"+httpSession);
    	}
    	//2.login.jsp이동
		RequestDispatcher dispatcher =request.getRequestDispatcher("/villa/index.jsp");
		dispatcher.forward(request, response);     	
    }	

AdiminCtrl (do_move_to_main)

private void do_move_to_main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("03.1 do_move_to_main");
		RequestDispatcher dispatcher =request.getRequestDispatcher("/villa/index.jsp");
		dispatcher.forward(request, response);	
	}
	
Comments