Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
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
Archives
Today
Total
관리 메뉴

개발자

[JSP 3일차] DTO/useBean/커스텀액션(Custom action)/taglib(<c:set>/<c:if>) 본문

개발자/JSP

[JSP 3일차] DTO/useBean/커스텀액션(Custom action)/taglib(<c:set>/<c:if>)

GoGo개발 2022. 8. 31. 12:13
DTO

 

메소드명에 get무조건 붙여주고 get다음은 대문자 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package chap03;
 
import java.util.Calendar;
 
public class MemberDTO {
 
    private String name; // 성명
    private String jubun; // 주민번호
    
    //2.기본생성자 만들어주기
    
    public MemberDTO() {}
    
    //1. name jubun으로 생성자 만들면 기본생성자 삭제된다 
    public MemberDTO(String name, String jubun) {
        super();
        this.name = name;
        this.jubun = jubun;
    }
 
    //3. getter setter
 
    public String getIrum() {
        return name;
    }
 
 
    public void setIrum(String name) {
        this.name = name;
    }
 
 
    public String getJubun() {
        return jubun;
    }
 
 
    public void setJubun(String jubun) {
        this.jubun = jubun;
    }
    
    ///////////////////////////////////////////////////////
    
    // 1. 성별을 알아오는 메소드 생성하기 //
    public String getGender() { //메소드명에 get무조건 붙여주고 get다음은 대문자 JSP 규격서이다
        
        if( jubun != null) {
            String n = jubun.substring(67);
            
            if("1".equals(n) || "3".endsWith(n)) {
                return "남";
            }
            
            else if("2".equals(n) || "4".endsWith(n)) {
                return "여";
            }
            
            else {
                return"";
            }
            
        }
        
        else {
            return"";
        }
    }//end of public String gender() {}------------------------------------
    
    
    
    // 2. 나이를 알아오는 메소드 생성하기 //
    
    public int getAge() {
        
        // 먼저 현재년도를 알아와야 한다.
        Calendar now = Calendar.getInstance(); // 현재날짜와 시간을 얻어온다.
        int currentYear = now.get(Calendar.YEAR); // 현재년도를 얻어온다.
        
        if(jubun !=null) {
            
            String n =jubun.substring(67); // "1" 또는 "2" 이라면 1900년대 생,
                                             // "3" 또는 "4" 이라면 2000년대 생
            String jubunYear= jubun.substring(02); // 주민번호에서 출생년도 2자를 얻어오는 것
        
            if("1".equals(n) || "2".equals(n)) { // 1900년대 생이라면
                return currentYear - (1900 + Integer.parseInt(jubunYear)) + 1;
                
            }
            
            else if("1".equals(n) || "2".equals(n)) { // 2000년대 생이라면
                return currentYear - (2000 + Integer.parseInt(jubunYear)) + 1;
                
            }
            
            else { 
                return 0;
            }
        
        }
        
        else {
            return 0;
        }
        
    }// end of public int age(){}------------------------------------
    
 
}
cs

 

useBean

:useBean은 JSP표준 액션이고, 객체이다. 

 

1.<jsp:useBean id="mbr3" class=chap03.MemberDTO" /> : 기본 생성자 
   chap03.MemberDTO mbr3 = new chap03.MemberDTO(); 라는 뜻이다
기본생성자 즉, chap03.MemberDTO 클래스의 기본생성자로 mbr3 이라는 객체를 생성하는 것이다.
기본생성자로 만들기 때문에 DTO에 기본생성자가 없으면 안된다.

2. 값 넣어주기 : <jsp:setProperty property="irum" name="mbr3" value="김태희"/>
                                                                                name은 객체명 
      mbr3.setIrum("김태희"); 와 같은 것이다. 

3.값 가져오기 : <jsp:getProperty property="irum" name="mbr3"/>
    .getIrum(); 와 같은 것이다. 

 

<useBean 없이 스크립틀릿을 이용했을 때 : 파라미터 있고, 없고 버전>

useBean. 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
57
58
59
60
61
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ page import="chap03.MemberDTO" %> 
    
<%
    // == MemberDTO 객체 생성하기 == //
     MemberDTO mbr1 = new MemberDTO(); //기본생성자
    mbr1.setIrum("이순신");
    mbr1.setJubun("9708311234567"); 
    
    String name1 = mbr1.getIrum();
    String jubun1 = mbr1.getJubun();
    String gender1 = mbr1.getGender();
    int age1 = mbr1.getAge();
    
    /////////////////////////////////////////
    
    MemberDTO mbr2 = new MemberDTO("엄정화" ,"9709102234567"); //파라미터있는 생성자   
    
    String name2 = mbr2.getIrum();
    String jubun2 = mbr2.getJubun();
    String gender2 = mbr2.getGender();
    int age2 = mbr2.getAge();
    
%>    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP 표준액션 중 useBean 에 대해서 알아봅니다.</title>
</head>
<body>
    <div>
         <h2>스크립틀릿을 사용하여 MemberDTO 클래스의 객체정보 불러오기</h2>
         
         <ul>
            <li>성명 : <%= name1%></li>
            <li>주민번호 : <%= jubun1%></li>
            <li>성별 : <%= gender1%></li>
            <li>나이 : <%= age1%></li>
         </ul>
         
         <br>
         
         <ul>
            <li>성명 : <%= name2%></li>
            <li>주민번호 : <%= jubun2%></li>
            <li>성별 : <%= gender2%></li>
            <li>나이 : <%= age2%></li>
         </ul>
         
    </div>
    
    <hr style="border:solid 1px red; margin: 20px 0">
  
</body>
</html>
cs

 

<useBean 사용시 : 파라미터 있고, 없고 버전>

:파라미터 있는버전써도 기본생성자를 삭제하면 구동되지 않는다! 기본생성자는 꼭 남겨두어야 한다.

 

 

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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ page import="chap03.MemberDTO" %> 
    
<%
    // == MemberDTO 객체 생성하기 == //
    MemberDTO mbr1 = new MemberDTO(); //기본생성자
    mbr1.setIrum("이순신");
    mbr1.setJubun("9708311234567");
    
    //MemberDTO mbr1 = new MemberDTO("이순신","9708311234567"); 
    
    String name1 = mbr1.getIrum();
    String jubun1 = mbr1.getJubun();
    String gender1 = mbr1.getGender();
    int age1 = mbr1.getAge();
    
    /////////////////////////////////////////
    
    MemberDTO mbr2 = new MemberDTO("엄정화" ,"9709102234567"); //파라미터있는 생성자   
    
    String name2 = mbr2.getIrum();
    String jubun2 = mbr2.getJubun();
    String gender2 = mbr2.getGender();
    int age2 = mbr2.getAge();
    
%>    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP 표준액션 중 useBean 에 대해서 알아봅니다.</title>
</head>
<body>
    <div>
         <h2>JSP 표준액션 중 useBean 을 사용하여 MemberDTO 클래스의 객체정보 불러오기</h2>
         
         <jsp:useBean id="mbr3" class="chap03.MemberDTO" />
         <%--
               위의 것은 아래의 뜻이다.
               
               chap03.MemberDTO mbr3 = new chap03.MemberDTO(); // 기본생성자 
               즉, chap03.MemberDTO 클래스의 기본생성자로 mbr3 이라는 객체를 생성하는 것이다. 
               파라미터가 있는 생성자를 사용해도 기본생성자 삭제시 구동되지 않기때문에 기본생성자를 반드시 남겨두어야 한다.
         --%>
         
         <jsp:setProperty property="irum" name="mbr3" value="김태희" />
         <%--
               위의 것은 아래의 뜻이다.
               mbr3.setIrum("김태희"); 와 같은 것이다.
         --%>
         <%--set 해오기 DTO의 set다음에나오는 메소드명가져오기 하지만 첫글자는 무조건 소문자 name이지만 
            필드명 X(아니다) set메소드 setName의 Name을 가져온거다--%>
         
         <jsp:setProperty property="jubun" name="mbr3" value="8904062234567" />
         <%--
               위의 것은 아래의 뜻이다.
               mbr3.setJubun("8904062234567"); 와 같은 것이다.
         --%>
         
         <ul>
            <li>성명 : <jsp:getProperty property="irum" name="mbr3"/> </li>
            <%--
                 위의 것은 아래의 뜻이다.
                 mbr3.getIrum(); 와 같은 것이다.
             --%>
            
            <li>주민번호 : <jsp:getProperty property="jubun" name="mbr3"/> </li>
            <%-- 
                 위의 것은 아래의 뜻이다.
                 mbr3.getJubun(); 와 같은 것이다.
             --%>
            <li>성별 : <jsp:getProperty property="gender" name="mbr3"/> </li>
            <%-- 
                 위의 것은 아래의 뜻이다.
                 mbr3.getGender(); 와 같은 것이다.
             --%>
            
            <li>나이 : <jsp:getProperty property="age" name="mbr3"/></li>
            <%-- 
                 위의 것은 아래의 뜻이다.
                 mbr3.getAge(); 와 같은 것이다.
             --%>
            
         </ul>
    </div>
    
 
</body>
</html>
cs

 

  <jsp:useBean id="mbr3" class="chap03.MemberDTO" />:

이 부분은 기본생성자로 만들기 때문에 DTO에 기본생성자가 없으면 안된다

 

.form 태그를 이용한 useBean

 

1.<jsp:useBean id="psdto" class="chap03.PersonDTO"/>
위의 것은 jsp 표준 액션 에서
chap03.PersonDTO psdto_2 = new chap03.PersonDTO();
와 같다 -

2. 값 넣어주기(set)
<jsp:setProperty property="name" name="psdto" value="${Param.name}"/>
                                                            name 은 객체명  value에서 name 은 form태그의 name 
-위의 것은
jsp 표준 액션 에서
String name = request.getParameter("name");
psdto_2.setName(name);
와 같다 

3. 배열일때는 
<jsp:setProperty property="Food" name="psdto" value="${ParamValues.food}"/> 
                                                      name 은 객체명 value에서 food는 form태그의 name 

위의 것은 name 은 객체명 jsp 표준 액션 에서
String[] arr_food = request.getParameterValues("food");
psdto_2.setFood(arr_food);
와 같다 -

4. 값 가져오기(get)
<jsp:getProperty property="name" name="psdto"/>
<배열은 메소드도 만들어주어야해서 아래에서 확인하자>

 

<form 태그에서 jsp로 보내고 ㅡ> jsp에서 DTO로 set, DTO에서 jsp로 get 해준다 >

 

1. form 태그 <06_useBean_form_execute_01.jsp> 실행페이지

:  action="06_useBean_form_register_02.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
    // 컨텍스트 패스명(context path name)을 알아오고자 한다.
    String ctxPath = request.getContextPath();
    // ctxPath => /JSPServletBegin 
%>    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>POST 방식으로 데이터 전송하기</title>
 
<style type="text/css">
    ul {list-style-type: none;}
    li {line-height: 200%;}
</style>
 
<script type="text/javascript" src="<%= ctxPath%>/js/jquery-3.6.0.min.js"></script> 
<script type="text/javascript">
 
   $(document).ready(function(){
       
   //  $("form[name='registerFrm']").bind("submit", function(){
   //  또는      
   //  $("form[name='registerFrm']").submit(function(){     
   //  또는      
       $("form[name='registerFrm']").submit(() => {                
       
           // === 유효성 검사 === //
           // 1. 성명
           const name_length = $("input:text[name='irum']").val().trim().length;
           if(name_length == 0) {
               alert("성명을 입력하세요!!");
               $("input:text[name='irum']").val("").focus();
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 2. 학력
           const school_val = $("select[name='school']").val();
           if(school_val == "") {
               alert("학력을 선택하세요!!");
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 3. 색상
           const color_length = $("input:radio[name='color']:checked").length
           if(color_length == 0) {
               alert("색상을 선택하세요!!");
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 4. 음식
           const food_length = $("input:checkbox[name='food']:checked").length
           if(food_length == 0) {
               alert("선호하는 음식을 최소한 1개 이상 선택하세요!!");
               return false// submit 을 하지 않고 종료한다.
           }
           
       });// end of $("form#registerFrm").submit(function(){})------------
       
   });// end of $(document).ready()----------------------------
 
</script>
 
</head>
<body>
 
    <form name="registerFrm" action="06_useBean_form_register_02.jsp" method="post">
        <fieldset>
            <legend>개인성향 테스트(POST method)</legend>
            <ul>
                <li>
                    <label for="name">성명</label>
                    <input type="text" name="irum" placeholder="성명입력"/> 
                </li>
                <li>
                    <label for="school">학력</label>
                    <select name="school">
                        <option value="">선택하세요</option>
                        <option>고졸</option>
                        <option>초대졸</option>
                        <option>대졸</option>
                        <option>대학원졸</option>
                    </select>
                </li>
                <li>
                    <label for="">좋아하는 색상</label>
                    <div>
                        <label for="red">빨강</label>
                        <input type="radio" name="color" id="red" value="red" />
                        
                        <label for="blue">파랑</label>
                        <input type="radio" name="color" id="blue" value="blue" />
                        
                        <label for="green">초록</label>
                        <input type="radio" name="color" id="green" value="green" />
                        
                        <label for="yellow">노랑</label>
                        <input type="radio" name="color" id="yellow" value="yellow" />
                    </div>
                </li>
                <li>
                    <label for="">좋아하는 음식(다중선택)</label>
                    <div>
                        <label for="food1">짜짱면</label>
                        <input type="checkbox" name="food" id="food1" value="짜짱면" />
                        &nbsp;
                        
                        <label for="food2">짬뽕</label>
                        <input type="checkbox" name="food" id="food2" value="짬뽕" />
                        &nbsp;
                        
                        <label for="food3">탕수육</label>
                        <input type="checkbox" name="food" id="food3" value="탕수육" />
                        &nbsp;
                        
                        <label for="food4">양장피</label>
                        <input type="checkbox" name="food" id="food4" value="양장피" />
                        &nbsp;
                        
                        <label for="food5">팔보채</label>
                        <input type="checkbox" name="food" id="food5" value="팔보채" />
                    </div>
                </li>
                <li>
                    <input type="submit" value="전송" />
                    <input type="reset" value="취소" />
                </li>
            </ul>
        </fieldset>
    </form>
 
</body>
</html>
cs

 

2.DTO : PersonDTO.java

 

전제조건은 06_useBean_form_execute_01.jsp 파일의 form 태그내의 name 값으로 준 것이
chap03.PersonDTO 의 field명과 같아야만 한다.

 

 

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
package chap03;
 
public class PersonDTO {
 
    private String name;
    private String school;
    private String color;
    private String[] food;
    
    
    public String getIrum() {
        return name;
    }
    public void setIrum(String name) {
        this.name = name;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String[] getFood() {
        return food;
    }
    public void setFood(String[] food) {
        this.food = food;
    }
    
    /////////////////////////////////////////
    
    //food 배열 가져오는 메소드
    public String getStrFood() {
        
        if(food != null) {
            return String.join(",", food);
        }
        else {
            return "";
        }
    }
    
    
}
 
cs

 

 

 

3. 06_useBean_form_register_02.jsp

: DTO에 set 해주고 DTO에서 get 해오기 - 각각 해주는 방법과 *이용해 한번에 하는 방법

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form 태그를 사용한 데이터 전송시 useBean을 사용하여 결과 보여주기</title>
</head>
<body>
    <h2>개인성향 입력 결과 정보(JSP 표준액션 중 useBEan 을 사용한 것)</h2>
    
    <jsp:useBean id="psdto" class="chap03.PersonDTO"/> 
 
    <%--위의 것은
        jsp 표준 액션 에서 
        chap03.PersonDTO psdto_2 = new chap03.PersonDTO(); 
        와 같다 
    --%>
    
    <%-- <jsp:setProperty property="name" name="psdto" value="${param.name}"/> --%>
    <%--위의 것은                        name 은 객체명               form태그의 name
        jsp 표준 액션 에서 
        String name = request.getParameter("name");
        psdto_2.setName(name);
        와 같다
    --%>
    
    <%-- <jsp:setProperty property="school" name="psdto" value="${param.school}"/> --%>
    <%--위의 것은                        name 은 객체명
        jsp 표준 액션 에서 
        String school = request.getParameter("school");
        psdto_2.setSchool(school);
        와 같다
    --%>
    
    <%-- <jsp:setProperty property="color" name="psdto" value="${param.color}"/> --%>
    <%--위의 것은                        name 은 객체명
        jsp 표준 액션 에서 
        String color = request.getParameter("color");
        psdto_2.setColor(color);
        와 같다
    --%>
    
    <%-- <jsp:setProperty property="food" name="psdto" value="${paramValues.food}"/> --%>
    <%--위의 것은            대문자안쓰게 주의  name 은 객체명
        jsp 표준 액션 에서 
        String[] arr_food = request.getParameterValues("food");
        psdto_2.setFood(arr_food);
        와 같다
    --%>
    
    <%-- 또는 위의 것을 아래의 것으로 대체가 가능하다. 
         단, 전제조건은 06_useBean_form_execute_01.jsp 파일의 form 태그내의 name 값으로 준 것이 chap03.PersonDTO 의 field명과 같아야만 한다. --%>
     
    <jsp:setProperty property="*" name="psdto"/>
 
      <%--한방에 하는법 DTO에 있는 모든 set 을 다 쓰겠다는 뜻 --%>
    
    <ul>
        <li>성명 : <jsp:getProperty property="irum"    name="psdto"/></li>
        <li>학력 : <jsp:getProperty property="school"  name="psdto"/></li>
        <li>색상 : <jsp:getProperty property="color"   name="psdto"/></li>
        <li>음식 : <jsp:getProperty property="strFood" name="psdto"/></li>
    </ul>
    
    
 
</body>
</html>
cs

 

위의 하얀박스에 설명 다되어있으니 위의 코드보고 다시 하얀박스가서 다시 봐보자

 

 

 

 커스텀액션(Custom action)

 

커스텀액션(Custom action)
=> 별도의 라이브러리를 설치해야만 사용가능함.
    라이브러리는 인터넷에서 다운로드 받을수도 있고(JSTL), <라이브러리설치함>
    사용자가 직접 만들어 사용할수도 있음.

 

   3-1. 지시어(directive)
     -- 형태 : <%@지시어%>
     
     -- 지시어의 종류 3가지 
     [1] page
     [2] include
     [3] taglib 이걸 써볼것이다 (태그 라이브러리)

 

1. 실행페이지 .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
57
58
59
60
61
62
63
64
65
66
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>두개의 수를 입력받아서 곱셈하기</title>
 
<script type="text/javascript">
 
    //Function Declaration
    function goSubmit() {
        
        // 정규표현식으로 유효성 검사
        const regExp = /^[0-9]{1,5}$//* 숫자 5자리까지? */
        
        const frm = document.myFrm;
        const num1 = frm.firstNum.value.trim();
        const num2 = frm.secondNum.value.trim();
        
        if!(regExp.test(num1) && regExp.test(num2)) ) {
            alert("숫자로만 입력하세요!!");
            frm.firstNum.value ="";
            frm.secondNum.value = "";
            frm.firstNum.focus();
            return//종료             
        }
        
        else { // 둘다 숫자인데 두번째 숫자가 첫번째보다 작을 때 
            
            if(Number(num1) > Number(num2) ) { // 웹은 무조건 String 타입이니까
                alert("첫번째 입력한 숫자가 두번째 입력한 숫자보다 작아야합니다.");
                frm.firstNum.value ="";
                frm.secondNum.value = "";
                frm.firstNum.focus();
                return//종료     
            }                    
        }
        
                
        
        frm.action = "01_multipy_result_02.jsp";
    //    frm.method = "GET"; // method 를 명기하지 않으면 기본은 "GET" 이다. 대소문자 상관 X
        frm.submit();
        
    }// end of function goSubmit()------------------
 
</script>
 
</head>
<body>
    <h2>입력한 2개의 수를 곱한 값 알아보기 </h2>
    
    <form name="myFrm">
        <p>
            첫번째 수 : <input type="text" name="firstNum" size="5" maxlength="5"/><br/>
            두번째 수 : <input type="text" name="secondNum" size="5" maxlength="5"/><br/>
            
            <button type="button" onclick="goSubmit()">계산하기</button>
            <button type="reset">취소하기</button>
        </p>
    
    </form>
 
</body>
</html>
cs

2. 01_multipy_result_02.jsp

: <c:set> 태그사용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%-- === JSTL(JSP Standard Tag Library) 사용하기 ===  --%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%-- 이걸 빼면 아래의 <c:set />을 쓸수가 없다  --%>
 
<%-- == 변수의 선언방법 == --%>
<c:set var="num1" value="${param.firstNum}"/> <!-- form태그에서 넘어온값을 num1에 넣어준다 -->
<c:set var="num2" value="${param.secondNum}"/>
<c:set var="result" value="${num1 * num2}"/>
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    ${num1} 와 ${num2} 의 곱은 ${result} 입니다. <br><br>
    ${param.firstNum} 와 ${param.secondNum} 의 곱은 ${result} 입니다.
 
</body>
</html>
cs

 

<c:if> 태그사용

 

1. 실행페이지 .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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<% 
    String ctxPath = request.getContextPath();
    // /JSPServletBegin 왓스에서 보기
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>두개의 문자열을 입력받아서 같은지 다른지 검사하기</title>
 
<script type="text/javascrip t" src="<%=ctxPath%>/js/jquery-3.6.0.min.js" ></script>
<!-- jquery 쓰겠다 -->
 
<script type="text/javascript">
 
    $(document).ready(function(){
    
    /*
        $("form[name='myFrm']").bind("submit",function(){});
        또는
        $("form[name='myFrm']").submit("submit",function(){});
        
    */
    
        $("form[name='myFrm']").submit(()=>{   /* 화살표함수는 $this.는 못쓴다 */
            
            const first_val = $("input:texxt[name='first']").val().trim();
            const second_val = $("input:texxt[name='second']").val().trim();
            
            if(first_val == "" || second_val=="") {
                alert("문자를 입력하세요!!");
                return false// submit 을 하지 않는다.
            }
                
        });// end of$("form[name='myFrm']").submit(()=>{})--------------------------
    });
 
</script>
 
</head>
<body>
<form name="myFrm" action="02_if_result_02.jsp">
      첫번째 입력란 : <input type="text" name="first" />
      두번째 입력란 : <input type="text" name="second" />
      세번째 입력란 : <input type="text" name="third" />
      <br>
      <input type="submit" value="확인" />
      <input type="reset" value="취소" /> 
   </form>
 
</body>
</html>
cs

<form name="myFrm" action="02_if_result_02.jsp">

 

 

2.   02_if_result_02.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%-- ==== JSTL(JSP Standard Tag Library) 사용하기 ==== --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>     
<%-- <c:if 쓰려면 taglib 있어야 한다 --%>
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>전송되어져 온 값을 if 를 사용하여 비교한 결과물 출력하기</title>
</head>
<body>
 
    <c:if test="${param.first eq param.second}">
       ${param.first} 와 ${param.second} 은 <span style="color: blue;">같습니다.</span> 
    </c:if>
    
    <!-- if는 else 가 없어서 else 를 아래처럼 따로 만들어준다  -->
    <c:if test="${param.first ne param.second}">
       ${param.first} 와 ${param.second} 은 <span style="color: red;">같지 않습니다.</span> 
    </c:if>
    
    <hr style="border: solid 1px red; margin: 20px 0">
    
    <c:if test="${param.first == param.second}">
       ${param.first} 와 ${param.second} 은 <span style="color: blue;">같습니다.</span> 
    </c:if>
    
    <c:if test="${param.first != param.second}">
       ${param.first} 와 ${param.second} 은 <span style="color: red;">같지 않습니다.</span> 
    </c:if>
    
    <hr style="border : solid 1px blue; margin: 20px 0">
    
    <c:if test="${empty param.third}">
      세번째 입력란은 <span style="color: yellow; background-color : black;">입력하지 않으셨습니다.</span> 
    </c:if>
    
    <c:if test="${not empty param.third}">
      세번째 입력란은 <span style="color: green;">입력하셨습니다.</span> 
    </c:if>
    
    <c:if test="${!empty param.third}">
      세번째 입력란은 <span style="color: green;">입력하셨습니다.</span> 
    </c:if>
    
    
    
 
</body>
</html>
cs