메인 페이지

[경로: src/main/webapp/index.jsp]

1
2
3
4
5
6
7
8
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:include page="/inc/top.jsp" />    
        <!-- content -->
        <div class="container">
            <h1>Index Page</h1>
        </div>
<jsp:include page="/inc/foot.jsp" />
cs

 

include 액션태그 <jsp:include page="포함될 페이지" />를 사용해서 top.jsp와 foot.jsp를 메인 페이지의 top 부분과 foot 부분에 포함시켰다.

 

top.jsp

[경로: src/main/webapp/inc/top.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    //컨텍스트명 구하기
    String ctx = request.getContextPath(); //"/MyWeb" 반환
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyWeb</title>
<link rel="stylesheet" type="text/css" href="<%=ctx %>/css/style.css">
<!-- include하는 jps 파일의 모든 링크는 절대경로(웹 어플리케이션. 컨텍스트를 기준)로 해야 함 -->
</head>
<body>
<%
    String loginId = (String)session.getAttribute("loginId");
    System.out.println("loginId: " + loginId);
%>
<div class="wrap">
    <header>
    <!-- top menu -->
        <ul class="topMenu">
            <li><a href="<%=ctx %>/index.jsp">Home</a></li>
            <% if(loginId==null){ %>
            <li><a href="<%=ctx %>/login/login.jsp">로그인</a></li>
            <% }else%>
            <li><a href="#"><%=loginId %>님 로그인 중...</a></li>
            <li><a href="<%=ctx %>/login/logout.jsp">로그아웃</a></li>
            <% } %>
            <li><a href="<%=ctx %>/member/join.jsp">회원가입</a></li>
            <li><a href="<%=ctx %>/board/input.jsp">게시판 글쓰기</a></li>
            <li><a href="<%=ctx %>/board/list.jsp">게시판 글목록</a></li>
        </ul>
    </header>
</div>
cs

 

foot.jsp

[경로: src/main/webapp/inc/foot.jsp]

1
2
3
4
5
6
7
8
9
10
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!-- footer -->
    <footer class="footer">
        @copyright
    </footer>            
</div>
    <!-- .wrap end -->    
</body>
</html>
cs

 

top.jsp에 <header>를 넣었고, foot.jsp에 <footer>를 넣었다.

HTML 공간을 만들 때 사용하는 태그: header, footer
  • <header>
    주로 웹페이지 상단에서 제목, 로고, 메뉴, 검색 폼, 작성자 이름 등의 요소를 넣을 때 사용한다.
  • <footer>
    주로 구획의 작성자, 저작권 정보, 관련 문서 등의 내용을 담는다.

CSS

[경로: src/main/webapp/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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@charset "UTF-8";
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}
 
header ul li{
    list-style-type:none;
}
a:link{
    text-decoration:none;
}
div.wrap{
    width:100%;
    margin:auto;
}
.container{
    width:80%;
    margin:0 auto;
    padding-top:2em;
    padding-bottom:15em;
    text-align:center;
}
header .topMenu{
    background-color: lavender;
    display:flex;
    flex-flow:row nowrap;
    height:80px;
    line-height:80px;
    justify-content: space-around;
}
.footer{
    width:100%;
    height:50px;
    line-height:50px;
    background-color:#ddd;
    position:fixed;
    left:0;
    bottom:0;
}
table{
    width:90%;
    margin:auto;
 
    border:1px solid #ddd;
    border-collapse:collapse;
}
th, td{
    padding:7px;
}
 
td{
    text-align:left;
}
input{
    width:40%;
}
input, select, textarea, iframe, button{
    padding: 5px;
    border:1px solid #ddd;
}
.m1{
    background-color:#ffccff;
}
.m2{
    background-color:#cc8800;
}
 
body{
    height: 100vh;
}
cs

 

top.jsp에서 css를 link하였다.

<link rel="stylesheet" type="text/css" href="<%=ctx %>/css/style.css">

 

실행 결과

[http://localhost:9090/MyWeb/index.jsp]

메인 페이지 완성

 


회원가입 페이지

[경로: src/main/webapp/member/join.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:include page="/inc/top.jsp" />
 
<div class="container">
    <form name="mf" method="post" action="../Signup">
    <!-- SignupServlet.java에 @WebServlet("/Signup")으로 전송됨 -->
    <!-- ../ => 상대경로: 지금 작업중인 파일인 join.html 파일에서 한 번 상위(밖으로) 나와
    java 폴더 내의 SignupServlet으로 form을 전송-->
        <table border="1" style="width:80%; margin:3em auto">
            <tr>
                <th colspan="2">Signup-회원가입</th>
            </tr>
            <tr>
                <th>
                    이 름
                </th>
                <td>
                    <input type="text" name="name">
                </td>
            </tr>
            <tr>
                <th>
                    아이디
                </th>
                <td>
                    <input type="text" name="id">
                </td>
            </tr>
            <tr>
                <th>
                    비밀번호
                </th>
                <td>
                    <input type="password" name="pw">
                </td>
            </tr>
            <tr>
                <th>
                    연락처
                </th>
                <td>
                    <input type="text" name="tel">
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                <button>회원가입</button>
                <button type="reset">다시쓰기</button>
                </td>
            </tr>        
        </table>
    </form>
</div>
 
<jsp:include page="/inc/foot.jsp" />
cs

 

<form name="mf" method="post" action="../Signup">

  • 서블릿에서 어노테이션 방식(@WebServlet)으로 action="../Signup"을 처리하도록 서블릿을 만들 것이다.
  • action이 ../Signup인 이유는 src/main/webapp/member/join.jsp에서 src/main/java/member/servlet/SignupSevlet.java로 가는 데 지금 작업중인 파일에서 상위로 한 번 나와야 하기 때문에 ../을 붙인 것이다.

 

SignupSevlet

[경로: src/main/java/member/servlet/SignupSevlet.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@WebServlet("/Signup")
public class SignupServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html; charset=utf-8");
        PrintWriter out = res.getWriter();
        //0. post방식일 때 한글처리
        req.setCharacterEncoding("UTF-8");
        
        //1. 사용자가 입력한 값 받기
        //doPost()메서드=> getParameter() 메서드를 이용하여 사용자가 입력한 정보들 추출 
        String name = req.getParameter("name"); //input name="name"
        String id = req.getParameter("id"); //input name="id"
        String pw = req.getParameter("pw"); //input name="pw"
        String tel = req.getParameter("tel"); //input name="tel"
        out.println(name+"/"+id+"/"+pw+"/"+tel+"<br>");
        
        //2. 유효성 체크 (name, id, pw)
        if(name==null || name.trim().isEmpty() || id==null || id.trim().isEmpty()
                || pw==null || pw.trim().isEmpty()) {
            out.println("<script>");
            out.println("alert('이름, 아이디, 비밀번호를 모두 입력하세요');");
            out.println("history.back();"); //뒤로가기
            out.println("</script>");
            return;
        }
        //3. 1번에서 받은 값을 MemberVO객체에 담아주기
        MemberVO user = new MemberVO(id, pw, name, tel, null);
        
        //4. MemberDAO객체 생성해서 insertMember()호출하기
        MemberDAO userDao = new MemberDAO();
        try {
        
        //5. 그 결과 메시지 처리 ==> alert()로 보여주기
        int n = userDao.insertMember(user);
        String msg = (n>0)? "회원가입 완료!- 홈페이지로 이동합니다":"회원가입 실패-다시 가입하세요";
        String loc = (n>0)? "index.html":"member/join.html";
            
        //6. 로그인 성공하면 페이지 이동 ==> index.html로
        out.println("<script>");
        out.println("alert('"+msg+"')");
        out.println("location.href='"+loc+"'");
        out.println("</script>");
        }catch (SQLException e) {
            out.println("<b>이미 사용중인 아이디이거나 서버 에러입니다.</b>");
            e.printStackTrace();
        }
        out.close();
    }
 
}
cs

 

join.jsp의 action="../Signup"을 처리하도록 서블릿을 만들었다.

 

회원가입 페이지 완성


게시판 글쓰기 페이지

[경로: src/main/webapp/board/input.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
38
39
40
41
42
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:include page="/inc/top.jsp" />    
 
<!-- bbs관련 js 파일 참조 -->
<script src="../js/bbs.js"></script>
        
<!-- content -->
<div class="container">
    <h1>Board Write Page</h1>
    <br><br>
    <form name="bbsF" method="post" action="insert2.jsp" onsubmit="return bbs_check()">
        <table border="1">
            <tr>
                <th width="20%">글제목</th>
                <td width="80%">
                    <input type="text" name="title" id="title" placeholder="Title">
                </td>
            </tr>
            <tr>
                <th>작성자</th>
                <td>
                    <input type="text" name="writer" id="writer" placeholder="Wrtier">
                </td>
            </tr>
            <tr>
                <th>글내용</th>
                <td>
                    <textarea name="content" id="content" placeholder="Content" rows="7" cols="60"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <button>글쓰기</button>
                    <button type="reset">다시쓰기</button>
                </td>
            </tr>
        </table>
    </form>
</div>
 
<jsp:include page="/inc/foot.jsp" />
cs

 

  1. js 파일을 참조하고 있다.
    <script src="../js/bbs.js"></script>
  2. action="insert2.jsp" => insert2.jsp에서 처리하도록 만들어야 한다.
  3. js 파일에 있는 bbs_check()에서 true를 반환하면 폼이 제출되고, false를 반환하면 폼이 제출되지 않는다.
    <form name="bbsF" method="post" action="insert2.jsp" onsubmit="return bbs_check()">

bbs.js

[경로: src/main/webapp/js/bbs.js]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function bbs_check(){
    var title = document.getElementById('title');
    var writer = document.getElementById('writer');
    var content = document.getElementById('content');
    //document.querySelector('#content')로 해도 됨
    if(!title.value){
        alert('글제목을 입력하세요');
        title.focus();
        return false;
    }
    if(!writer.value){
        alert('작성자를 입력하세요');
        writer.focus();
        return false;
    }
    if(!content.value){
        alert('글내용을 입력하세요');
        content.focus();
        return false;
    }
    return true;
    
}
cs

 

insert2.jsp

[경로: src/main/webapp/board/insert2.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="/error.jsp" %>

<!--BbsVO객체 -->
<jsp:useBean id="vo" class="bbs.model.BbsVO" scope="page" />
    <jsp:setProperty name="vo" property="*" />
 
<!-- BbsDAO객체 -->
<jsp:useBean id="dao" class="bbs.model.BbsDAO" scope="session" />
<%
int n = dao.insertBbs(vo);
response.sendRedirect("list2.jsp");
%>
cs

 

이 코드를 이해하려면 액션 원소에 대한 개념 이해가 필요하다.


액션 원소 - useBean, set/getProperty

useBean

  • 클래스 객체 하나를 생성시켜 놓고 사용하는 개념
  • 클래스를 이용하면 멤버 변수들을 모아서 관리할 수 있는데, useBean을 쓰면 웹 상에서도 id, 비밀번호, 이름 등의 정보들을 클래스의 객체 타입에 묶어서 사용할 수 있다.

▶ 선언범위(scope)

객체가 살아 있는 유효 범위 (page < request < session < application)

  1. page: 하나의 페이지에서만 객체가 유효함 → 주로 VO에서 사용 (개인 정보가 들어있기 때문에)
  2. request: 하나의 요청(request)을 처리하는 동안 객체가 유효함
  3. session: 하나의 브라우저를 사용하는 동안 객체가 유효함 → 주로 DAO에서 사용
  4. application: 서버 시작부터 서버 종료까지 객체가 살아 있음

▶ 형식

<jsp:useBean id="빈이름" class="자바빈 클래스 이름" scope="선언범위" />
    <jsp:setProperty name="자바빈" property="이름" value="값" />
    <jsp:setProperty name="자바빈" property="이름" param="HTML name값" />
    <jsp:setProperty name="자바빈" property="이름" />
    <jsp:setProperty name="자바빈" property="*" />

 

1. <jsp:useBean>

<jsp:useBean id="빈이름" class="자바빈 클래스 이름" scope="선언범위" />

=> 클래스 빈이름 = new 클래스();

  • id: JSP페이지에서 자바빈 객체에 접근할 때 사용하는 이름
    ex) BbsVO vo = new BbsVO();
    → id = "vo"
  • class: 패키지 이름을 포함한 자바빈 클래스의 완전한 이름
    ex) BbsVO의 경로: src/main/java/bbs/model/BbsVO
    → class= "bbs.model.BbsVO"
  • scope: 자바빈 객체가 저장될 범위를 지정. page[default], request, session, application 중 하나를 값으로 갖는다.

2. <jsp:setProperty>

<jsp:setProperty name="자바빈" property="이름" />

=> 자바빈 파일의 setter 메서드 사용 (즉, 데이터의 값을 설정할 때 사용)

=> 빈이름.set필드(값);

  • name: 프로퍼티 값을 변경할 자바빈 객체의 이름. <jsp:useBean> 액션 태그의 id 속성에서 지정한 값을 사용
    ex) <jsp:useBean id="vo">
    → <jsp:setProperty name="vo">
  • property: 값을 지정할 프로퍼티(필드)의 이름
    property 속성에 *을 사용하면 프로퍼티와 동일한 이름의 파라미터를 이용하여 setter 메서드를 생성한 모든 프로퍼티(필드)에 대해 값을 설정할 수 있다.

코드 설명

1) 자바빈 파일

[경로: src/main/java/bbs/model/BbsVO]

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
49
50
51
52
53
54
55
56
57
58
59
60
61
package bbs.model;
 
//자바빈
public class BbsVO {
    //프로퍼티
    private int no;
    private String title;
    private String writer;
    private String content;
    private java.sql.Date wdate;
    
    //기본생성자
    public BbsVO() {
        super();
        System.out.println("BbsVO()생성됨...");
    }
    //인자생성자
    public BbsVO(int no, String title, String writer, String content, Date wdate) {
        this.no = no;
        this.title = title;
        this.writer = writer;
        this.content = content;
        this.wdate = wdate;
    }
    
    //setter, getter
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getTitle() {
        return title;        
    }
    public void setTitle(String title) {
        this.title = title;
        System.out.println("setTitle(): " + title);
    }
    public String getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
        System.out.println("setWriter(): " + writer);
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
        System.out.println("setContent(): " + content);
    }
    public Date getWdate() {
        return wdate;
    }
    public void setWdate(Date wdate) {
        this.wdate = wdate;
    }    
        
}
cs

 

2) 입력한 값을 전달하는 form

[경로: src/main/webapp/board/input.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
<form name="bbsF" method="post" action="insert2.jsp" onsubmit="return bbs_check()">
    <table border="1">
        <tr>
            <th width="20%">글제목</th>
            <td width="80%">
                <input type="text" name="title" id="title" placeholder="Title">
            </td>
        </tr>
        <tr>
            <th>작성자</th>
            <td>
                <input type="text" name="writer" id="writer" placeholder="Wrtier">
            </td>
        </tr>
        <tr>
            <th>글내용</th>
            <td>
                <textarea name="content" id="content" placeholder="Content" rows="7" cols="60"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center">
                <button>글쓰기</button>
                <button type="reset">다시쓰기</button>
            </td>
        </tr>
    </table>
</form>
cs

 

3) form으로부터 전달된 데이터를 자바빈에 저장하는 jsp 파일

[경로: src/main/webapp/board/insert2.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="/error.jsp" %>
 
<!--BbsVO객체 생성
BbsVO vo = new BbsVO();와 같은 의미 -->
<jsp:useBean id="vo" class="bbs.model.BbsVO" scope="page" />
 
<!-- form으로부터 전달된 값을 vo 객체의 프로퍼티에 설정
form 태그의 name과 자바빈의 프로퍼티명이 동일한 것에 대응 -->    
<jsp:setProperty name="vo" property="*" />
<!-- 위와 동일한 의미
<jsp:setProperty name="vo" property="title" />
<jsp:setProperty name="vo" property="writer" />
<jsp:setProperty name="vo" property="content" />
-->
 
<!-- BbsDAO객체 생성 
BbsDAO dao = new BbsDAO();와 같은 의미 -->
<jsp:useBean id="dao" class="bbs.model.BbsDAO" scope="session" />
<%
int n = dao.insertBbs(vo);
response.sendRedirect("list2.jsp");
%>
cs

 


 

1
2
3
4
5
6
7
<!-- BbsDAO객체 생성 
BbsDAO dao = new BbsDAO();와 같은 의미 -->
<jsp:useBean id="dao" class="bbs.model.BbsDAO" scope="session" />
<%
int n = dao.insertBbs(vo);
response.sendRedirect("list2.jsp");
%>
cs

이 부분을 보면 form으로부터 전달된 값을 vo 객체의 프로퍼티에 넣어준 뒤, dao 객체에 vo객체를 담아서 executeUpdate()한 결과값을 int n으로 리턴받았고, 그 뒤에 list2.jsp 페이지로 이동하도록 설정했다.

 

[BbsDAO - insertBbs()]

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
//게시글 쓰기 (시퀀스-Bbs_seq : 글번호)
public int insertBbs(BbsVO vo) throws SQLException{
    try {
    //con = DBUtil.getCon(); //드라이버 로드, db연결
    //수정
    con = ds.getConnection();
    String sql = "INSERT INTO bbs(no, title, writer, content, wdate)";
    sql += " VALUES(bbs_seq.NEXTVAL, ?, ?, ?, SYSDATE)";
                
    ps = con.prepareStatement(sql);
    ps.setString(1, vo.getTitle());
    ps.setString(2, vo.getWriter());
    ps.setString(3, vo.getContent());
    //execute
    int re = ps.executeUpdate();
    return re;
    } finally {
        //자원 반납
        close();
    }
cs

 

게시판에 글쓰기를 완료하면 게시판 글목록(list2.jsp)으로 이동

게시판 글쓰기 페이지 완성


게시판 글목록 페이지

[경로: src/main/webapp/board/list2.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
38
39
40
41
42
43
44
45
46
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, bbs.model.*" errorPage="/error.jsp" %>
<jsp:include page="/inc/top.jsp" />
 
<!-- BbsDAO dao = new BbsDAO();와 동일 -->
<jsp:useBean id="dao" class="bbs.model.BbsDAO" scope="session" />    
        <!-- content -->
        <div class="container">
            <h1>Board List Page</h1>
            <br>
            [<a href="input.jsp">글쓰기</a>]
            <br><br>
            <table border="1">
                <tr>
                    <th class="m1" width="10%">글번호</th>
                    <th class="m1" width="50%">글제목</th>
                    <th class="m1" width="20%">작성자</th>
                    <th class="m1" width="20%">작성일</th>
                </tr>
                <!-- 반복문 ----------------- -->
                <% 
                //dao의 listBbs()호출 ==> 반환받은 ArrayList값을 반복문 돌려서 출력
                ArrayList<BbsVO> arr = dao.listBbs();
                if(arr==null || arr.size()==0){
                    %>
                    <tr>
                        <td colspan="4"><b>데이터가 없습니다</b></td>
                    </tr>
                    <%
                }else{
                    for(BbsVO vo:arr){            
                %>
                        <tr>
                            <td><%=vo.getNo() %></td>
                            <td><%=vo.getTitle() %></td>
                            <td><%=vo.getWriter() %></td>
                            <td><%=vo.getWdate() %></td>
                        </tr>
                <%
                    }//for-----
                }//else------
                %>
                <!-- ---------------------- -->
            </table>
        </div>
<jsp:include page="/inc/foot.jsp" />
cs

 

[BbsDAO의 listBbs()]

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
public ArrayList<BbsVO> listBbs() throws SQLException{
    try {
        //con=DBUtil.getCon();
        //수정
        con = ds.getConnection();
        //oracle, mysql
        String sql = "SELECT no, title, writer, content, wdate FROM bbs ORDER BY no DESC";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        return makeList(rs);
    } finally {
        close();
    }
        
}
    
public ArrayList<BbsVO> makeList(ResultSet rs) throws SQLException{
    ArrayList<BbsVO> arr = new ArrayList<BbsVO>();
    while(rs.next()) {
        int no = rs.getInt("no");
        String title = rs.getString("title");
        String writer = rs.getString("writer");
        String content = rs.getString("content");
        java.sql.Date wdate = rs.getDate("wdate");
        BbsVO vo = new BbsVO(no, title, writer, content, wdate); //하나의 record
        arr.add(vo);
    }        
    return arr;
}
cs

게시판 글목록 페이지 완성


에러 페이지 처리

게시판 글쓰기 페이지에서 작성자를 회원이 아닌 다른 아이디로 입력하거나, 로그인을 하지 않은 채 insert2.jsp에 바로 접근하려고 할 경우 에러 페이지가 뜨도록 처리하는 것이 좋다.

 

[경로: src/main/webapp/error.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 import="java.sql.SQLIntegrityConstraintViolationException"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
<!-- 에러 처리 페이지가 되기 위해서는 page지시어에 isErrorPage속성값으로 true를 주어야 한다.
    내장객체 exception을 사용할 수 있다. -->
 
<jsp:include page="/inc/top.jsp" />
 
<div class="container">
    <h2>서버 에러 발생</h2>
    <%
    if(exception instanceof SQLIntegrityConstraintViolationException){
        %>
        <script>
            alert('회원만 글을 쓸 수 있습니다. 로그인을 하세요.');
            history.back();
        </script>
        <%
    }else{
    %>
        <h3 style='color:red'>
            <%=exception.getMessage() %>
            <%
            //디버그용
            exception.printStackTrace();
            %>
        </h3>
        [<a href="../index.jsp">Home으로 가기</a>]
        [<a href="javascript:history.back()">이전 페이지 가기</a>]
    <%//else--------- %>
</div>
 
<jsp:include page="/inc/foot.jsp" />
cs
  • SQLIntegrityConstraintViolationException: 무결성 위배 조건. 비회원이 글을 쓰려고 할 때 발생하는 예외
  • 에러 처리 페이지가 되기 위해서는 page지시어에 isErrorPage 속성값으로 true를 줘야 한다.
  • 에러 처리 페이지는 내장 객체 exception을 사용할 수 있다.

에러 처리 페이지를 동작시키고 싶은 사이트에 <%@ page errorPage="에러페이지 경로" %>를 삽입하면 된다.

1
2
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="/error.jsp" %>
cs

 

에러 페이지 실행 결과

1) 회원이 아닌 아이디로 글을 쓰려고 시도한 경우

 

2) 작성자 id를 너무 길게 쓴 경우

+ Recent posts