728x90

 

수업내용 정리 (Eclipse)

 

선생님이 과제로 관리자로 로그인하면 회원 목록+회원 정보를 띄우고, 일반 회원으로 로그인하면 로그인 한 회원 정보를 띄우는 것을 내주셔서 밑의 코드가 불완전하다.

 

1. wepapp

  • WEB-INF (jsp 넣는 공간 아님!!!!!!!)

 

  • jsp ㄱ 
더보기
  • index
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>index.html - 시작 페이지</h1>
	<a href="loginfrm">로그인</a>
	<a href="joinfrm">회원가입</a>
	<c:if test="${1222<2}"> 1보다 2가 크다.</c:if>
</body>
</html>

 

  • joinFrm
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	let m = '${msg}'
	if (m != '') {
		alert(m);
	}
</script>
</head>
<body>
	<h1>joinFrm.jsp - 회원가입 양식</h1>
	<form action="join" method="post" name="joinfrm">
		<table>
			<tr>
				<td>아이디</td>
				<td><input type="text" name="id"></td>
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type="password" name="pw"></td>
			</tr>
			<tr>
				<td>이름</td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<td>성별</td>
				<td align="center"><input type="radio" name="gender" value="남자">남자
					&nbsp; <input type="radio" name="gender" value="여자">여자</td>
			</tr>
			<tr align="right">
				<td colspan="2"><button>회원가입</button>&nbsp;
					<button type="reset">취소</button></td>
			</tr>
		</table>
	</form>
</body>
</html>

 

  • loginFrm
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>loginFrm.jsp - 로그인 화면</h1>
	<form action="login" method="post">
		<table>
			<tr>
				<td>아이디</td>
				<td><input type="text" name="id"></td>
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type="password" name="pw"></td>
			</tr>
			<tr align="right">
				<td colspan="2"><button>로그인</button></td>
			</tr>
		</table>
	</form>
	<form action="joinfrm" method="post">
		<button>회원가입</button>
	</form>
</body>
</html>

 

  • main
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	let m = '${msg}'
	if (m != '') {
		alert(m);
	}
</script>
</head>
<body>
	<h1>main.jsp - 메인 화면</h1>
	<table>
		<tr>
			<td colspan="2">${accessResult}</td>
		</tr>
		<tr>
			<td colspan="2" align="right">${logout}</td>
		</tr>
	</table>
</body>
</html>

 

  • memberList
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	console.log('${mList}');
</script>
</head>
<body>
	<h1>memberList.jsp</h1>
	<table>
		<tr>
			<th colspan="2">회원 목록</th>
		</tr>
		<tr>
			<td>회원 아이디</td>
			<td>삭제</td>
		</tr>
		<tr>
			<td></td>
			<td></td>
		</tr>
	</table>
</body>
</html>

 

 

2. Java - controller

  • HomeContoller
package controller;

import java.io.IOException;

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 common.Forward;
import service.MemberMM;
import service.MovingPage;

@WebServlet({"/login","/loginfrm","/joinfrm","/join","/logout","/main", "/memberlist", "/memberinfo"})
public class HomeContoller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String cmd=request.getServletPath();
		System.out.println("cmd="+cmd);
		//회원관리 서비스클래스
		MemberMM mm=new MemberMM(request,response);
		//게시판관리 서비스클래스
		MovingPage mp=new MovingPage(request,response);
		
		Forward fw=null;
		if(cmd.equals("/loginfrm")) {
			fw=mp.showLoginFrm();			
		}else if(cmd.equals("/login")) {
			fw=mm.login();
		}else if(cmd.equals("/logout")) {
			fw=mm.logout();
		}else if(cmd.equals("/joinfrm")) {
			fw=mp.showJoinFrm();
		}else if(cmd.equals("/join")) {
			fw=mm.join();
		}else if(cmd.equals("/memberlist")) {
			fw=mm.getMemberlist();
		}else if(cmd.equals("/memberinfo")) {
			fw=mm.getMemberinfo();
		}
		
		if(fw!=null) {
			if(fw.isRedirect()) { //true: redirect
				response.sendRedirect(fw.getPath()); // 새로운 req, res 객체 생성 + 주소창 새 url 생성
			}else {
				request.getRequestDispatcher(fw.getPath()).forward(request, response); // 기존 req, res 객체 사용 + 주소창 갱신X
			}
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

 

3. Java - service (MP, MM)

더보기
  • MovingPage (MP)
package service;

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

import common.Forward;

public class MovingPage {
	HttpServletRequest request;
	HttpServletResponse response;

	public MovingPage(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	public Forward showLoginFrm() {
		Forward fw = new Forward();
		// 로그인여부 판단
		if (request.getSession().getAttribute("id") != null) {
			fw.setPath("main.jsp");
			fw.setRedirect(true);
		} else {
			fw.setPath("loginFrm.jsp");
			fw.setRedirect(true);
		}
		return fw;
	}

	public Forward showJoinFrm() {
		Forward fw = new Forward();
		// 로그인여부 판단
		if (request.getSession().getAttribute("id") != null) {
			fw.setPath("main.jsp");
			fw.setRedirect(true);
		} else {
			fw.setPath("joinFrm.jsp");
			fw.setRedirect(true);
		}
		return fw;
	}

}

 

  • MemberMM (MM)
package service;

import java.util.ArrayList;
import java.util.HashMap;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import common.Forward;
import dao.MemberDao;

public class MemberMM {
	HttpServletRequest request;
	HttpServletResponse response;

	public MemberMM(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	public Forward login() {
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		MemberDao mDao = new MemberDao();
		Forward fw = new Forward();
		HttpSession session = request.getSession();
		HashMap<String, String> hMap = new HashMap<>();
		hMap.put("id", id);
		hMap.put("pw", pw);
		if (mDao.login(hMap)) {
			session.setAttribute("id", id);
			;
			session.setAttribute("logout", makeLogoutHtml());
			session.setAttribute("accessResult", makeResultHtml());
			request.setAttribute("msg", "로그인 성공");
			fw.setPath("main.jsp");
			fw.setRedirect(true);
		} else {
			request.setAttribute("msg", "로그인 실패");
			fw.setPath("loginFrm.jsp");
			fw.setRedirect(false);
		}
		mDao.close();
		return fw;
	}

	private String makeLogoutHtml() {
		StringBuffer sb = new StringBuffer();
		sb.append("<div>");
		sb.append("<a href='logout'>로그아웃");
		sb.append("</div>");
		return sb.toString();
	}

	private String makeResultHtml() {
		// 관리자: admin /////// 임의의 아이디에 권한 1, 0 으로 판단
		StringBuilder sb = new StringBuilder();
		String id = request.getSession().getAttribute("id").toString();
		if (id.equals("admin")) {
			sb.append("<a href='/memberlist'>(관리자)회원목록</a>");
		} else {
			sb.append("<a href='/memberinfo?id=" + id + "'>내 정보</a>");
		}
		return sb.toString();
	}

	public Forward logout() {
		request.getSession().invalidate();
		Forward fw = new Forward();
		fw.setPath("./"); // index.jsp
		fw.setRedirect(true);
		return fw;
	}

	public Forward join() {
		// 비지니스(업무) 로직
		// Dao: Data Access Object
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String name = request.getParameter("name");
		String gender = request.getParameter("gender");
		System.out.printf("%s,%s,%s,%s\n", id, pw, name, gender);
		// Member Bean or HashMap<k,v>
		HashMap<String, String> hMap = new HashMap<>();
		hMap.put("id", id);
		hMap.put("pw", pw);
		hMap.put("name", name);
		hMap.put("gender", gender);

		MemberDao mDao = new MemberDao(); // db접속
		boolean result;
		result = mDao.join(hMap); // db 로직-->-->insert작업--->
		mDao.close();
		Forward fw = new Forward();
		if (result) {
			System.out.println("회원가입 성공");
			request.setAttribute("msg", "회원가입성공");
			fw.setPath("loginFrm.jsp");
			fw.setRedirect(true);
		} else {
			// System.out.println("회원가입 실패");
			request.setAttribute("msg", "회원가입실패");
			fw.setPath("joinFrm.jsp");
			fw.setRedirect(false);
		}
		return fw;
	}

	public Forward getMemberlist() throws JsonProcessingException {
		MemberDao mDao = new MemberDao();
		ArrayList<String> mList = mDao.getMemberList();
		mDao.close();
		Forward fw = new Forward();
		if (mList != null) {
			// 1.makeHtml 으로 반복문?
			// 2.javaScript 로 반복문? <<- java 객체를 json 으로 변환
			// 3.jstl 으로 반복문?
			ObjectMapper om = new ObjectMapper();
			// / java 객체 -->> json 변환
			String json = om.writeValueAsString(mList);
			System.out.println("json: " + json);
			request.setAttribute("mList", json);
			fw.setPath("memberList.jsp");
			fw.setRedirect(false);
		} else {
			fw.setPath("main.jsp");
			fw.setRedirect(true);
		}
		return fw;
	}

	public Forward getMemberinfo() {
		return null;
	}

}

 

 

4. Java - dao

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import common.JdbcUtil;

public class MemberDao {
	Connection con;
	PreparedStatement pstmt;
	ResultSet rs;

	public MemberDao() {
		// db 접속
		con = JdbcUtil.getConnection();
	}

	public boolean join(HashMap<String, String> hMap) {
		String sql = """
				insert into member(id,pw,name,gender)
				 value(?,?,?,?)
				""";
		int result = 0;
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, hMap.get("id"));
			pstmt.setString(2, hMap.get("pw"));
			pstmt.setString(3, hMap.get("name"));
			pstmt.setString(4, hMap.get("gender"));
			result = pstmt.executeUpdate();
			if (result > 0) {
				System.out.println("DB 회원가입 성공");
				return true;
			} else {
				System.out.println("DB 회원가입 성공");
				return false;
			}
		} catch (SQLException e) {
			System.out.println("join 예외 발생");
			e.printStackTrace();
			return false;
		}
	}

	public void close() {

	}

	public boolean login(HashMap<String, String> hMap) { // login 구문
		String sql = "select * from member where id =? ";
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, hMap.get("id"));
			rs = pstmt.executeQuery();
			if (rs.next()) {
				// 아이디 일치
				if (rs.getString("pw").equals(hMap.get("pw"))) {
					return true;
					// 비번 일치
				}
			}
		} catch (SQLException e) {
			System.out.println("dao login 예외 발생");
			e.printStackTrace();
		}
		return false;
	}

	public ArrayList<String> getMemberList() {
		ArrayList<String> mList = null;
		String sql = "select id from member";
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			mList = new ArrayList<>();
			while (rs.next()) {
				mList.add(rs.getString("id"));
			}
		} catch (SQLException e) {
			System.out.println("dao memberList 예외");
			e.printStackTrace();
		}
		return mList;
	}
}

 

5. Java - common (Forward, JdbcUtil - 이전에 쓰던 것들 복사)

더보기
  • Forward
package common;

//포워딩 정보
public class Forward {
	// true: redirect포워딩
	// false: (dispatcher)포워딩
	private boolean isRedirect; // false
	private String path; // 포워딩할 뷰 페이지 or url

	public boolean isRedirect() {
		return isRedirect;
	}

	public void setRedirect(boolean isRedirect) {
		this.isRedirect = isRedirect;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}

 

  • JdbcUtil
package common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcUtil {
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("드라이버 로딩 성공");
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 로딩 실패");
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		try {
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/workdb", "icia", "1234");
			System.out.println("db 접속 성공");
			return con;
		} catch (SQLException e) {
			System.out.println("db 접속 실패");
			e.printStackTrace();
		}
		return null;
	}

	public static void dbClose(ResultSet rs, PreparedStatement pstmt, Connection con) {
		try {
			if (rs != null)
				rs.close();
			if (pstmt != null)
				pstmt.close();
			if (con != null)
				con.close();
			System.out.println("db연결 종료 성공");
		} catch (SQLException e) {
			System.out.println("db연결 종료 실패");
			e.printStackTrace();
		}
	}

	public static void dbCommit(Connection con) {
		try {
			con.commit();
		} catch (SQLException e) {
			System.out.println("commit fail");
			e.printStackTrace();
		}
	}

	public static void dbRollback(Connection con) {
		try {
			con.rollback();
		} catch (SQLException e) {
			System.out.println("rollback fail");
			e.printStackTrace();
		}
	}
}

 


 

전체 피드백

  • 또 고작 '/' 이 작대기 하나 까먹었다고 오류가 나서 켜지질 않았다. 조장님(특: 옆자리)이랑 열심히 찾다가 먼저 찾으셔서 알려주셨는데 너무 허망했다..

 


728x90