1. Template

1) WebContent - view - template - sidebar.jsp 수정

22
<p><a href="${pageContext.request.contextPath}/DispatcherServlet?command=updatePage">회원수정</a></p>          

 

2. View

1) WebContent - view - member - update.jsp 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="card">
    <form action="DispatcherServlet" method="post">
        <input type="hidden" name="command" value="update">
        <table>      
            <tr>
                <td>아이디</td>
                <td><input type="text" name="clientId" value="${clientDTOinfo.clientId}" readonly></td>
            </tr>
            <tr>
                <td>비밀번호</td>
                <td><input type="password" name="clientPassword" ></td>
            </tr>
            <tr>
                <td>이름</td>
                <td><input type="text" name="clientName" value="${clientDTOinfo.clientName}" ></td>
            </tr>
            <tr>
                <td>이메일</td>
                <td><input type="text" name="clientEmail" value="${clientDTOinfo.clientEmail}" ></td>
            </tr>
            <tr>
                <td>전화번호</td>
                <td><input type="text" name="clientPhone" value="${clientDTOinfo.clientPhone}" ></td>
            </tr>
            <tr>
                <td>주소</td>
                <td><input type="text" name="clientAddress" value="${clientDTOinfo.clientAddress}" ></td>
            </tr>
            <tr rowspan="2">
                <td><input type="submit" value="수정"/></td>
            </tr>
        </table>
    </form>
 </div>

2) WebContent - view - member - update_result.jsp 추가

1
2
3
4
5
6
7
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <script>
        alert("수정이 완료되었습니다.");
    </script>

 

3. Model

1) src - model.ClientDAO.java에 getClientInfo 메소드 추가(회원 수정페이지에 정보 띄우기 위해)

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//3. 아이디로 회원정보 찾기(패스워드 제외)
public ClientDTO getClientInfo(String clientId) throws SQLException {
     Connection con = null;
     PreparedStatement pstmt = null;
     ResultSet rs=null;
     ClientDTO resultDTO=null;
     try {
         con = getConnection();
         String sql="select * from client where clientId=?";
         pstmt = con.prepareStatement(sql);
         pstmt.setString(1, clientId);
         rs=pstmt.executeQuery();
         if(rs.next())
             resultDTO =new ClientDTO(rs.getString(1), null, rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6));           
     } catch (SQLException e) {
         e.printStackTrace();
     } finally {
         closeAll(rs,pstmt, con);
     }
     return resultDTO;
}

2) src - test.TestGetClientInfo.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package test;
 
import java.sql.SQLException;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class TestGetClientInfo {
    public static void main(String[] args) {
        String clientId="xiumin";
        try {
            ClientDTO clientDTOinfo=ClientDAO.getInstance().getClientInfo(clientId);
            System.out.println(clientDTOinfo);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3) src - model.ClientDAO.java에 updateMemberInfo 메소드 추가

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
public void updateMemberInfo(ClientDTO clientDTO) throws SQLException {
     Connection con = null;
     PreparedStatement pstmt = null;
     try {
         con = getConnection();
         String sql = "update client set clientPassword=?, clientName=?, clientEmail=?,clientPhone=?,clientAddress=? where clientId=?";
         pstmt = con.prepareStatement(sql);
         pstmt.setString(1, clientDTO.getClientPassword());
         pstmt.setString(2, clientDTO.getClientName());
         pstmt.setString(3, clientDTO.getClientEmail());
         pstmt.setString(4, clientDTO.getClientPhone());
         pstmt.setString(5, clientDTO.getClientAddress());
         pstmt.setString(6, clientDTO.getClientId());
         pstmt.execute();
  
     } catch (SQLException e) {
         e.printStackTrace();
     } finally {
         closeAll(pstmt, con);
     }
 }

4) src - test.TestUpdateMemberInfo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package test;
 
import java.sql.SQLException;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class TestUpdateMemberInfo {
    public static void main(String[] args) {
        try {
            ClientDTO oldInfo=ClientDAO.getInstance().getClientInfo("suman");
            System.out.println("예전정보 : "+oldInfo);
            ClientDTO newInfo=new ClientDTO("suman", "sm1234", "이수만", "smNo1@smtown.com", "010-0000-0000", "SM공화국");
            System.out.println("변경정보 : "+newInfo);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

4. Controller

1) src - controller.HandlerMapping.java 에 updatePage,update 추가

23
24
25
26
else if(command.equals("updatePage"))   // 회원수정 페이지 이동
    c=new UpdatePageController();
else if(command.equals("update"))   //회원수정 처리
    c=new UpdateController();

2) src - controller.UpdatePageController.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class UpdatePageController implements Controller {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        ClientDTO clientDTO=(ClientDTO) session.getAttribute("clientDTO");
        if(session==null||session.getAttribute("clientDTO")==null){
            return "redirect:index.jsp";
        }
        ClientDTO clientDTOinfo=ClientDAO.getInstance().getClientInfo(clientDTO.getClientId());
        request.setAttribute("clientDTOinfo", clientDTOinfo);
        request.setAttribute("url", "/view/member/update.jsp");
        return "/view/template/home.jsp";
    }
}

3) src - controller.update.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class UpdateController implements Controller {
 
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        if(session==null||session.getAttribute("clientDTO")==null){
            return "redirect:index.jsp";
        }
        String clientId=request.getParameter("clientId");
        String clientPassword=request.getParameter("clientPassword");
        String clientName=request.getParameter("clientName");
        String clientEmail=request.getParameter("clientEmail");
        String clientPhone=request.getParameter("clientPhone");
        String clientAddress=request.getParameter("clientAddress");
        ClientDTO dto = new ClientDTO(clientId, clientPassword, clientName, clientEmail, clientPhone, clientAddress);
        ClientDAO.getInstance().updateMemberInfo(dto);
        return "redirect:view/member/update_result.jsp";
    }
}

1. Template

1) WebContent - view - template - sidebar.jsp 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:choose>
    <c:when test="${sessionScope.clientDTO==null}">
    <!-- 로그인 부분 -->
        <div class="card">
            <h3>로그인</h3>
            <form method="post" action="${pageContext.request.contextPath}/DispatcherServlet">
                <input type="hidden" name="command" value="login">
                <p>아이디 <input type="text" name="clientId" placeholder="아이디" size="12"></p>
                <p>패스워드 <input type="password" name="clientPassword" placeholder="비밀번호" size="12"></p>
                <input type="submit" value="로그인">
                <a href="${pageContext.request.contextPath}/DispatcherServlet?command=registerPage">회원가입</a></p>
            </form>
        </div>           
    </c:when>
    <c:otherwise>
        <div class="card">       
            <p>${sessionScope.clientDTO.clientName}님    반갑습니다.</p>
            <p><a href="${pageContext.request.contextPath}/DispatcherServlet?command=logout">로그아웃</a></p>
            <p><a href="#">회원수정</a></p>        
            <p><a href="#">회원탈퇴</a></p>
            <p><a href="${pageContext.request.contextPath}/index.jsp">홈으로</a>  </p>
        </div>
        <!-- 메뉴부분 -->
        <div class="card">
            <h3>게시판</h3>
            <a href="#">게시판 보기</a
        </div>
    </c:otherwise>
</c:choose>

 

2. View

1) WebContent - view - member - login_result.jsp 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!-- 로그인 실패 : 세션 없음 -->
<c:if test="${sessionScope.clientDTO==null}">
    <script lang="javascript">
        alert('아이디가 없거나 패스워드가 맞지 않아 로그인에 실패하셨습니다.');
        location.href='http://localhost:8080/webstudy-board/'; 
    </script>
</c:if>
<!-- 로그인 성공 : 세션 있음 -->
<c:if test="${sessionScope.clientDTO!=null}">
    <script lang="javascript">
        var name='${sessionScope.clientDTO.clientName}';
        alert(name+'님 안녕하세요');
        location.href='http://localhost:8080/webstudy-board/';
    </script>
</c:if>

 

3. Model 

1) src - model.ClientDAO.java에 login 로그인 메소드 추가

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public ClientDTO login(ClientDTO clientDTO) throws SQLException {
    ClientDTO resultDTO=null;
    Connection con=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    try {
        con=getConnection();
        String sql="select clientId,clientName from client where clientId=? and clientPassword=?";
        pstmt=con.prepareStatement(sql);
        pstmt.setString(1, clientDTO.getClientId());
        pstmt.setString(2, clientDTO.getClientPassword());
        rs=pstmt.executeQuery();
        if(rs.next())
            resultDTO=new ClientDTO(rs.getString(1), null, rs.getString(2), null, null, null);
    }finally {
        closeAll(rs, pstmt, con);
    }
    return resultDTO;
}

2) src - test.TestLogin.java 추가(login 메소드 테스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package test;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class TestLogin {
    public static void main(String[] args) {
        String clientId="xiumin";
        String clientPassword="exo1234";
        try {
            ClientDTO clientDTO=ClientDAO.getInstance().login(new ClientDTO(clientId,clientPassword,null,null,null,null));
            System.out.println(clientDTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

4. Controller

1) src - controller.HandlerMapping.java에 login, logout command 추가;

1
2
3
4
else if(command.equals("login"))    //로그인
    c=new LoginController();
else if(command.equals("logout"))   //로그아웃
    c=new LogoutController();

2) src - controller.LoginController.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class LoginController implements Controller {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String clientId=request.getParameter("clientId");
        String clientPassword=request.getParameter("clientPassword");
        ClientDTO clientDTO=ClientDAO.getInstance().login(new ClientDTO(clientId,clientPassword,null,null,null,null));
        HttpSession session=request.getSession();
        session.setAttribute("clientDTO", clientDTO);
        return "redirect:view/member/login_result.jsp";
    }
}

3) src - controller.LogoutController.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class LogoutController implements Controller {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        if(session!=null)
            session.invalidate();
        return "redirect:index.jsp";
    }
}

 

1. Template

1) WebContent - view - template - sidebar.jsp 에 회원가입 링크 추가

6
<p><a href="${pageContext.request.contextPath}/DispatcherServlet?command=registerPage">회원가입</a></p>

 

2. View

1) WebContent - view -  member - register.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div class="card">
    <div class="registerClient">
        <h3>회원가입</h3>
        <form method="post" action="DispatcherServlet">
            <input type="hidden" name="command" value="register">
            <table>
                <tr>
                    <td>아이디</td><td><input type="text" name="clientId"></td>
                </tr>
                <tr>
                    <td>패스워드</td><td><input type="password" name="clientPassword"></td>
                </tr>
                <tr>
                    <td>이름</td><td><input type="text" name="clientName"></td>
                </tr>
                <tr>
                    <td>이메일</td><td><input type="email" name="clientEmail"></td>
                </tr>
                <tr>
                    <td>휴대폰</td><td><input type="tel" name="clientPhone"></td>
                </tr>
                <tr>
                    <td>주소</td><td><input type="text" name="clientAddress"></td>
                </tr>
                <tr>
                    <td colspan="2" ><input type="submit" value="등록"></td>
                </tr>
            </table>
        </form>
    </div>
</div>

2) WebContent - view -  member - register_result.jsp

1
2
3
4
5
6
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
  alert("등록이 완료되었습니다.");
  location.href="http://localhost:8080/webstudy-board/";       
</script>

 

3. Model

1) src - mdoel.ClientDAO에 register 메소드 추가

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//1. 회원등록
public void register(ClientDTO clientDTO) throws SQLException{
    Connection con=null;
    PreparedStatement pstmt=null;
    try {
        con=getConnection();
        String sql="insert into client(clientId, clientPassword, clientName, clientEmail, clientPhone, clientAddress) values(?,?,?,?,?,?)";
        pstmt=con.prepareStatement(sql);
        pstmt.setString(1,clientDTO.getClientId());
        pstmt.setString(2,clientDTO.getClientPassword());
        pstmt.setString(3,clientDTO.getClientName());
        pstmt.setString(4,clientDTO.getClientEmail());
        pstmt.setString(5,clientDTO.getClientPhone());               
        pstmt.setString(6,clientDTO.getClientAddress());
        pstmt.execute();
    }finally {
        closeAll(pstmt,con);
    }
}

2) src - test.TestRegister.java (register 메소드를 테스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package test;
 
import java.sql.SQLException;
 
import model.ClientDAO;
import model.ClientDTO;
 
public class TestRegister {
    public static void main(String[] args) {
        ClientDTO newClient=new ClientDTO("test", "test1234", "테스트", "test@test.com", "010-0000-0000", "서울시 종로구");
        try {
            ClientDAO.getInstance().register(newClient);
            System.out.println("추가완료");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

4. Controller

1) src - controller.HandlerMapping.java에 registerPage와 register command 추가

15
16
17
18
else if(command.equals("registerPage")) //회원가입 페이지 이동
    c=new RegisterPageController();
else if(command.equals("register")) //회원가입 처리
    c=new RegisterController();

2) src - controller.RegisterPageController.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class RegisterPageController implements Controller {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("url", "/view/member/register.jsp");
        return "/view/template/home.jsp";
    }
}

3) src - controller.ResgisterController.java 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package controller;
  
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
import model.ClientDAO;
import model.ClientDTO;
  
public class RegisterController implements Controller {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String clientId=request.getParameter("clientId");
        String clientPassword=request.getParameter("clientPassword");
        String clientName=request.getParameter("clientName");
        String clientEmail=request.getParameter("clientEmail");
        String clientPhone=request.getParameter("clientPhone");
        String clientAddress=request.getParameter("clientAddress");
        ClientDAO.getInstance().register(new ClientDTO(clientId, clientPassword, clientName, clientEmail, clientPhone, clientAddress));
        return "redirect:view/member/register_result.jsp";
    }
}

 

5.CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
table {
  border-collapse: collapse;
  width: 100%;
}
  
th, td {
  text-align: left;
  padding: 8px;
}
  
 tr:nth-child(even) {background-color: #f2f2f2;}
 input[type=submit] {
  width: 20%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
    
}
  
 input[type=submit]:hover {
  background-color: #45a049;
}

1. webstudy-board 폴더 구조

1. index 페이지와  error 페이지

1) WebContent-index.jsp

1
2
3
4
5
6
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:forward page="DispatcherServlet">
    <jsp:param name="command" value="mainPage"/>
</jsp:forward>

2) WebContent-error.jsp

에러페이지 이동하기

3) WebContent - view - template - home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원관리 & 게시판</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
    <div class="header">
        <c:import url="/view/template/header.jsp"></c:import>
    </div>
    <div class="row">
        <div class="leftcolumn">
            <c:import url="/view/template/sidebar.jsp"></c:import>
        </div>
        <div class="rightcolumn">
            <c:import url="${url}"></c:import>
        </div>
    </div>
    <div class="footer">
        <c:import url="/view/template/footer.jsp"></c:import>
    </div>
</body>
</html>

4) WebContent - view - template - header.jsp

1
2
3
4
5
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <h1>게시판 테스트</h1>
  <p>게시판 테스트 중입니다. 나중에 페이징빈도 할 것 입니다.</p>

5) WebContent - view - template - sidebar.jsp

1
2
3
4
5
6
7
8
9
10
11
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 회원 -->
<div class="card">
회원부분
</div>
<!-- 메뉴부분 -->
<div class="card">
메뉴부분
</div>

6) WebContent - view - template - footer.jsp

1
2
3
4
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <h2>푸터임</h2>

7) WebContent - view - template - mainPage.jsp

1
2
3
4
5
6
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="card">
    <img src="./mainPage_Img.jpg"/>
</div>

- mainPage 이미지

2. Controller

1) src - controller.HandlerMapping.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package controller;
 
public class HandlerMapping {
    private static HandlerMapping instance=new HandlerMapping();
    private HandlerMapping() {}
    public static HandlerMapping getInstance() {
        return instance;
    }
    public Controller create(String command) {
        Controller c=null;
        //메인
        if(command.equals("mainPage"))
            c=new MainPageController();
        //회원관리
        //게시판
        return c;
    }
}

2) src - controller.MainPageController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class MainPageController implements Controller {
 
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("url", "/view/template/mainPage.jsp");
        return "/view/template/home.jsp";
         
    }
}

 

3.CSS

1) WebContent - css - style.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@charset "UTF-8";
* {
  box-sizing: border-box;
}
 
body {
  font-family: Arial;
  padding: 10px;
  background: #f1f1f1;
}
.header {
  padding: 30px;
  text-align: center;
  background: white;
}
.main{
    height:60px;
    width: 100%;
    background-color: green;
    float: left;
}
.leftcolumn {  
  float: left;
  width: 25%;
}
.rightcolumn {
  float: left;
  width: 75%;
  background-color: #f1f1f1;
  padding-left: 20px;
}
.card {
  background-color: white;
  padding: 20px;
  margin-top: 20px;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}
 
.footer {
  padding: 20px;
  text-align: center;
  background: #ddd;
  margin-top: 20px;
}

** 표현 언어(EL:Expression Language) **
- 데이터를 웹 페이지에 표시하는데 사용하는 태그
- JSP 출력에 대한 부분을 쉽게 하기 위해 개발한 태그
- 등장배경 : 자바코드로 내장 객체(request, session 등)에 저장된 속성 값에 접근하면 코드가 길어지고 지저분해짐
ex) ${ expr }

* 요청 파마리터 처리
request.getParamter()--->param 객체
- param : request.getParameter()와 동일한 역할로, 파라미터 값을 알려준다
- paramValues : request.getParamterValues()와 동일한 역할로, 동일한 이름으로 전달되는 파라미터 값들(라디오버튼, 체크박스 등)을 배열형태로 얻어온다.

ex)
request.getParameter("id") ---> ${param.id}
request.getParameter("pw") ---> ${param.pw}


* 내장객체 접근
- pageScope : 내장객체 pageContext
- requestScope : 내장객체 request
- sessionScope : 내장객체 session
- applicationScope : 내장객체 application




** JSTL (JSP Standard Tag Library) **

- JSP 표준 태크 라이브러리
- 일관성 없던 커스텀 태그(JSP를 작성할 때 자주 사용되는 자바 코드를 웹에서 사용할 수 있는 태크 형태로 만드는 기술)들을 표준화 한 것


* 태그 라이브러리 사용하기
- JSTL 제공 기능 중 core를 사용하기 위한 taglib
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- uri : 사용할 태그 라이브러리 식별자
- prefix : 태그에서 사용할 접두어

* JSTL core 태그

태그 설명 기본형식
<c:set> 변수에 값을 설정

<c:set var="변수이름" value="저장할 값" [scope="{page|request|session|application}]>

*scope 속성 기본값 : page

<c:remove> 변수에 설정된 값을 제거 <c:remove var="변수 이름" [scope="{page|request|session|application}]>
<c:if> 조건에 따라 처리를 달리 할 때 사용

<c:if test="조건식>

   조건이 참일 경우 실행할 문장

</c:if>

<c:choose> 여러 조건에 따라 처리를 달리 할 때 사용

<c:choose>

 <c:when test="조건1"> 실행 값</c:when>

 <c:when test="조건2"> 실행 값</c:when>

 <c:otherwise> 실행 값</c:when>

</c:choose>

<c:forEach>

구분자로 구분된 각각의 토큰을 처리할 때 사용

집합체에 저장되어 있는 값들을 순차적으로 처리할 떄 사용할 수 있는 태그

<c:forEach [var="변수 이름"] items="배열과 같은 집합체" [varStatus="반복상태정보를 위한 변수"]>

 실행 값

</c:forEach>

 

* varStatus 속성 : 반복 상태에 관련된 정보를 알려줌

- index : 현재 반복중인 항목의 index 알려줌

- count : 현재 몇 번째를 반복 중인지 알려줌

- first : 현재 루프가 처음인지 여부

- last  : 현재 루프가 마지막인지 여부

- begin : 반복에 사용 될 것 중 첫번째 항목의 index

- end : 반복에 사용될 것 중 마지막 항목의 index

<c:forTokens> 구분자로 분리된 각각의 토큰을 처리할 때 사용

<c:forTokens var="토큰을 저장할 변수" items="토큰으로 나눌 문자열" delims="구분자">

 실행 값

</c:forTokens>

<c:import> 외부의 자원을 URL을 지정하여 가져다 사용

<c:import url="URL" [var="변수 이름"] [scope="영역"] [charEncoding="charEncoding"]><c:import>

<c:redirect> 지정된 경로로 이동 <c:redirect url="URL" [context="경로명"]>
<c:url> url 재작성 <c:url value="URL" [var="변수 이름"] [scope="영역"]></c:url>
<c:out> 데이터를 출력할 때 사용하는 태그, <%= %>대체 <c:out value="value" [default="기본값"]>
<c:catch> 예외처리

<c:catch var="변수 이름">

예외가 발생할 수 있는 코드

</c:catch>



1. 공통

1) WebContent - WEB-INF - web.xml

1
내용은 여기에

2) WebContent - Home.html

1
내용은 여기에

 

2. Review

1) WebContent - step1.html

1
내용은 여기에

2) src - ReviewServlet.java

1
내용은 여기에

 

3. LifeCycleServlet

1) src - LifeCycleServlet.java.java

1
내용은 여기에

 

4. TestListener

1) WebContent - step2.jsp

1
내용은 여기에

2) src - step4.OneServlet.java

1
내용은 여기에

3) src - step4.TwoServlet.java.java

1
내용은 여기에

4) src - step5.TestListener.java

1
내용은 여기에

'1.JAVA Web Programming > [1주차] Servlet-Basic' 카테고리의 다른 글

Servlet Basic - Servlet Basic  (0) 2019.08.06
Servlet Basic - Servlet 내용정리  (0) 2019.08.06
Servlet Basic - Web basic  (0) 2019.08.03

1. 공통 영역

1) WebContent - WEB-INF - web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee <a href="http://xmlns.jcp.org">http://xmlns.jcp.org</a>/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>webstudy1-servlet-basic</display-name>
  <welcome-file-list>
    <welcome-file>home.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>step1.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

2) WebContent - Home.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start Servlet</title>
</head>
<body>
Start Servlet!!
 
 
 
<a href="http://localhost:8080/webstudy1-servlet-basic/step3.html">step3.RequestTestServlet</a>
 
</body>
</html>

 

2. HelloServlet

1) WebContent - step1.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>step1.HelloServlet</title>
</head>
<body>
#. 서블릿의기본 연습(get방식)
<form action="hello" method="get">
음식명 <input type="text" name="menu">
<input type="submit" value="get요청">
</form>
<hr>
<form action="hello" method="post">
<input type="submit" value="post요청">       
</form>
</body>
</html>

2) src - HelloServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package step1;
  
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;
 
 
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        System.out.print("HelloServlet doGet()");
        //응답시 전송할 컨텐츠 정보 할당
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.println("<html>");
        out.println("<body bgcolor=blue>");
        out.println("HelloServlet 시작 서블릿!");
        out.println("메뉴명은"+request.getParameter("menu"));
        out.println("</body>");
        out.println("</html>");
        out.close();
        }
}

 

3. PostServlet

1) WebContent - Step2.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>step2.PostServlet</title>
</head>
<body>
#. http post 방식 요청 연습
 <form action="PostServlet" method="post">
         닉네임 <input type="text" name="nickName">
         <input type="submit" value="전송">
 </form>
</body>
</html>

2) src - PostServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package step2;
  
import java.io.IOException;
import java.io.PrintWriter;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
/*
 * web.xml에서 기술했던 url-pattern역할을 @WebServlet 어노테이션으로 기술
 */
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    public PostServlet() {
        super();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //post 방식일 때는 request 요청 파라미터를 인코딩 해야함
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.println("PostServlet doPost");
            String nickName=request.getParameter("nickName");
            out.println("당신의 닉네임은 : "+nickName );
            out.println("<a href=http://localhost:8080/webstudy1-servlet-basic/step2.html>step2</a>");
            out.close();           
   }
}

4. RequestTestServlet

1) WebContent - Step3.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>step3.RequestTestServlet</title>
</head>
<body>
<!--
아래와 같은 링크는 get방식 요청,
링크를 클릭했을 때 정보를 전달하고 싶다면 query string 방식으로 전달
 -->
 <a href="requestTest?id=angel&name=조민경">RequestTestServlet</a>
 
 
 <hr>
 <!--
         form에서 별도의 method 즉, 요청방식이 명시되어 있지 않으면 get방식 요청
  -->
  <form action="requestTest">
  아이디 <input type="text" name="id">
  이름 <input type="text" name="name">
  <input type="submit" value="전송">
  </form>
</body>
</html>

2) src - RequestTestServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package step3;
  
import java.io.IOException;
import java.io.PrintWriter;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
/**
 * Servlet implementation class RequestTestServlet
 */
@WebServlet("/requestTest")
public class RequestTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    public RequestTestServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        out.println("RequestTestServlet doGet() 응답");
        out.println("아이디 "+id+"");
        out.println("이름 "+name+"");
        out.close();
    }
}

'1.JAVA Web Programming > [1주차] Servlet-Basic' 카테고리의 다른 글

Servlet Basic - Servlet LifeCycle  (0) 2019.08.06
Servlet Basic - Servlet Basic  (0) 2019.08.06
Servlet Basic - Web basic  (0) 2019.08.03

+ Recent posts