controller : 웹 서버에서 요청 처리자
service : 클라이언트의 요청에 대한 응답을 한다 >> 서비스 한다
DAO : Data Access Object
>> 데이터베이스와 관련된 코드만 있다.
롬복 적용법
롬복이 안될때는 롬복 저장 경로를 cmd로 찾아주면
이렇게 뜰 경우 롬복이 설치 안되어있다!
그럴때는 java -jar "lombok (1).jar" 라고 입력하면 고추화면이 뜬다!!
Specify locationi.. 을 누르고 eclipse.exe 선택하면
고추 모양 아이콘이 없을거에요!! (전 이미 설치를 했기에 있지요)
install / update 하면 끝!
회원가입 및 목록 출력
member.controller
> MemberList.java
> Register.java
> Remove.java
package member.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 member.service.MemberService;
import member.service.MemberServiceImpl;
@WebServlet("/member/list")
public class MemberList extends HttpServlet{
private MemberService memberService = MemberServiceImpl.getInstatnce();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(memberService.list());
req.setAttribute("members", memberService.list());
req.getRequestDispatcher("/WEB-INF/jsp/member/list.jsp").forward(req, resp);
}
}
package member.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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 member.service.MemberService;
import member.service.MemberServiceImpl;
import member.vo.MemberVo;
@WebServlet("/member/register")
public class Register extends HttpServlet{
private MemberService memberService = MemberServiceImpl.getInstatnce();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 화면 (회원등록)
req.getRequestDispatcher("/WEB-INF/jsp/member/register.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 로직 (회원등록)
req.setCharacterEncoding("utf-8");
String id = req.getParameter("id");
String pwd = req.getParameter("pwd");
String name = req.getParameter("name");
String email = req.getParameter("email");
MemberVo memberVo = new MemberVo(id, pwd, name, email, null);
memberService.register(memberVo);
resp.sendRedirect("list"); // list.jsp으로 이동
}
}
package member.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 member.service.MemberService;
import member.service.MemberServiceImpl;
import member.vo.MemberVo;
@WebServlet("/member/remove")
public class Remove extends HttpServlet{
private MemberService memberService = MemberServiceImpl.getInstatnce();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
System.out.println(id);
memberService.remove(id);
resp.sendRedirect("list"); // list.jsp로 이동
}
}
member.dao
> MemberDao.java
package member.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import member.vo.MemberVo;
import utils.DBConn;
public class MemberDao {
/*
* singleton
*/
private static MemberDao dao = new MemberDao();
public static MemberDao getInstance() {
return dao;
}
private MemberDao() {}
/*
*
*/
private Statement stmt;
private PreparedStatement pstmt;
private Connection conn;
public List<MemberVo> list() {
List<MemberVo> list = new ArrayList<>();
try {
conn = DBConn.getConnection();
String query = "SELECT * FROM T_MEMBER";
// query = "INSERT INTO(ID, PWD, NAME, EMAIL) VALUES ('" + memberVo.getId() + "')";
// stmt = conn.createStatement();
// System.out.println(stmt);
// ResultSet rs = stmt.executeQuery(query);
//NullPointerException 뜨는 이유 stmt가 Null이기 때문에
pstmt = conn.prepareStatement(query); // 전처리 시킴
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
int idx = 1;
MemberVo vo = new MemberVo(
rs.getString(idx++),
rs.getString(idx++),
rs.getString(idx++),
rs.getString(idx++),
rs.getDate(idx++)
);
list.add(vo);
}
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public void register(MemberVo memberVo) {
try {
conn = DBConn.getConnection();
pstmt = conn.prepareStatement("INSERT INTO T_MEMBER VALUES(?, ?, ?, ?, SYSDATE)");
int idx = 1;
pstmt.setString(idx++, memberVo.getId());
pstmt.setString(idx++, memberVo.getPwd());
pstmt.setString(idx++, memberVo.getName());
pstmt.setString(idx++, memberVo.getEmail());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void remove(String id) {
try {
conn = DBConn.getConnection();
pstmt = conn.prepareStatement("DELETE FROM T_MEMBER WHERE ID = '"+ id +"'");
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new MemberDao().list().forEach(System.out::println);
}
}
member.service
> MemberService.java
> MemberServiceImpl.java
package member.service;
import java.util.List;
import member.vo.MemberVo;
public interface MemberService {
List<MemberVo> list();
void register(MemberVo memberVo);
void remove(String id);
}
package member.service;
import java.util.List;
import member.dao.MemberDao;
import member.vo.MemberVo;
public class MemberServiceImpl implements MemberService{
private static final MemberService memberService = new MemberServiceImpl();
public static MemberService getInstatnce() {
return memberService;
}
private MemberServiceImpl() {}
private MemberDao memberDao = MemberDao.getInstance();
@Override
public List<MemberVo> list() {
// TODO Auto-generated method stub
return memberDao.list();
}
@Override
public void register(MemberVo memberVo) {
memberDao.register(memberVo);
}
@Override
public void remove(String id) {
memberDao.remove(id);
}
}
member.vo
> MemberVo.java
package member.vo;
import java.sql.Date;
import lombok.Data;
@Data
public class MemberVo {
private final String id;
private final String pwd;
private final String name;
private final String email;
private final Date joinDate;
}
utils
> DBConn.java
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConn {
public static Connection getConnection() throws SQLException, ClassNotFoundException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@np.uhducom.com:1521/xe", "jsp", "1234");
return conn;
}
}
WEB-INF
> jsp
> member
list.jsp
register.jsp
<%@ 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>
<table>
<tr>
<th>아이디</th>
<th>비밀번호</th>
<th>이름</th>
<th>이메일</th>
<th>가입일</th>
</tr>
<c:forEach items="${members}" var="member">
<tr>
<td>${member.id}</td>
<td>${member.pwd}</td>
<td>${member.name}</td>
<td>${member.email}</td>
<td>${member.joinDate}</td>
<td><a href="remove?id=${member.id}">삭제</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
<%@ 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>
// 유효성 검증 예정
window.onload = function(){
document.frm.onsubmit = function(){
var id = documnent.frm.id;
var pwd = document.frm.pwd;
var pwdChk = document.frm.pwdChk;
var name = document.frm.name;
var email = document.frm.email;
if(id.value.length == 0){
alert("아이디를 입력하세요");
}
else if(id.value.length<5){
alert("아이디를 5자 이상 입력해주세요")
}
else if(!pwd.value){
alert("비밀번호를 입력하세요");
}
else if(pwd.value.length<5){
alert("비밀번호를 5자 이상 입력해주세요");
}
else if(!pwdChk.value){
alert("비밀번호 확인을 입력하세요");
}
else if(pwd.value !== pwdChk.value){
alert("비밀번호 일치여부를 확인하세요오오옹");
}
else if(!name.value){
alert("이름을 입력해주세요")
}
else if(!email.value){
alert("이메일을 입력해주세요")
}
return false;
}
}
</script>
</head>
<body>
<form class="form" name="frm" method="post">
<label for="userId" class="form-label">아이디</label>
<input type="text" name="id" id="userId" class="form-control">
<label for="userPwd" class="form-label">비밀번호</label>
<input type="text" name="pwd" id="userPwd" class="form-control">
<label for="userPwdChk" class="form-label">비밀번호 확인</label>
<input type="text" name="pwdChk" id="userPwdChk" class="form-control">
<label for="userName" class="form-label">이름</label>
<input type="text" name="name" id="userName" class="form-control">
<label for="userEmail" class="form-label">이메일</label>
<input type="text" name="email" id="userEmail" class="form-control">
<div class="d-grid">
<button>회원가입</button>
</div>
</form>
</body>
</html>
'자바 풀스택 공부' 카테고리의 다른 글
Day 49. [JSP/Servlet] useBean (0) | 2022.03.16 |
---|---|
Day 49. [JSP/Servlet] 쿠키 & 세션 (0) | 2022.03.16 |
Day 47. [Java] InputStream, OutputStream (0) | 2022.03.14 |
Day 46. [JSP/Servlet] 라이프 사이클 (0) | 2022.03.14 |
Day 45. [Oracle SQL] 데이터 무결성 제약조건 (0) | 2022.03.10 |
댓글