1. DB와 연동하기 위해 환경 Setting 


새로운 프로젝트를 만들기위해 NEW> Spring Legacy Project 클릭

프로젝트 이름은 SpringjdbcTemplate 



자바콘솔에서 볼 경우는 Simple Spring Utility Project를 선택해주고

웹에서 볼 경우는 Spring MVC Project를 선택해주면 된다.


패키지 이름은 com.exe.springjdbctemplate로 해준다.


스프링에서 DB를 사용하는 방법은 대표적으로 두가지가 있다.

1. mybatis

2. Spring dao


-테이블 생성

create table custom

(id number,

name char(10),

age number)


저장소를 제공하면 내가 따로 lib를 추가해줄 필요없이 스프링이 자동으로 가져와준다.

Maven이 그 저장소 역할을 한다.


**maven에 라이브러리 추가

-링크: https://mvnrepository.com/


1. Commons DBCP 검색 > 1.4 클릭

하단에 이부분 복붙해서 pom.xml에 붙여넣는다.(pom.xml이 Maven의 환경설정 파일)


2. pool 검색>Commons Pool 1.6도 똑같이 넣어준다.


-pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">    
    <dependencies>
        <!-- 생략 -->
        
        <!-- commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        
        <!-- commons-pool -->
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
 
    </dependencies>
</project>
cs

: dbcp와 pool을 추가해주었다.


-설치된 라이브러리 파일 확인

C:\Users\itwill\.m2\repository 여기 경로에 lib파일 확인 할수 있다.



2. 스프링에서 JDBC 사용 


-CutomDTO 클래스 파일 생성

1
2
3
4
5
6
7
8
9
10
package com.exe.springjdbctemplate;
 
public class CustomDTO {
    
    private int id;
    private String name;
    private int age;
    
    //getter,setter 생략...
}
cs


-app-context.xml을 프로젝트 패키지에 복사한뒤 

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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        https://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/p">
 
    <description>Example configuration to get you started.</description>
 
    <context:component-scan base-package="com.exe.springjdbctemplate" />
 
    <bean id="customDAO"
    class="com.exe.springjdbctemplate.CustomDAO">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="oracle.jdbc.driver.OracleDriver"
    p:url="jdbc:oracle:thin:@192.168.16.12:1521:TestDB"
    p:username="suzi"
    p:password="a123"
    />
</beans>
cs

: 사용자 정의 파일인 p를 써주고,

db정보인 dataSource 써주고, 그리고 sql문을 적어줄 DAO객체도 생성해준다.


-파일 구조


-CustomDAO.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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package com.exe.springjdbctemplate;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import javax.sql.DataSource;
 
public class CustomDAO {
 
    private DataSource dataSource;
    
    //의존성 주입
    public void setDataSource(DataSource dataSource) {
        this.dataSource=dataSource;
    }
    
    Connection conn=null;
    
    //insert
    public int insertData(CustomDTO dto) {
        int result=0;
        PreparedStatement pstmt=null;
        String sql;
        
        try {
            conn=dataSource.getConnection();
            
            sql="insert into custom(id,name,age) values (?,?,?)";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, dto.getId());
            pstmt.setString(2, dto.getName());
            pstmt.setInt(3, dto.getAge());
            
            result=pstmt.executeUpdate();
            
            pstmt.close();
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return result;
    }
    
    //select 모든 데이터
    public List<CustomDTO> getList(){
        
        List<CustomDTO> lists=new ArrayList<CustomDTO>();
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        String sql;
        
        try {
            conn=dataSource.getConnection();
            
            sql="select id,name,age from custom";
            
            pstmt=conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            
            while(rs.next()) {
                CustomDTO dto=new CustomDTO();
                
                dto.setId(rs.getInt("id"));
                dto.setName(rs.getString("name"));
                dto.setAge(rs.getInt("age"));
                
                lists.add(dto);
            }
            
            rs.close();
            pstmt.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return lists;
    }
    
    //update
    public int updateData(CustomDTO dto) {
        int result=0;
        PreparedStatement pstmt=null;
        String sql;
        
        try {
            conn=dataSource.getConnection();
            
            sql="update custom set name=?,age=? where id=?";
            pstmt=conn.prepareStatement(sql);
            
            pstmt.setString(1, dto.getName());
            pstmt.setInt(2, dto.getAge());
            pstmt.setInt(3, dto.getId());
            
            result=pstmt.executeUpdate();
            
            pstmt.close();
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return result;
    }
    
    //select 1개의 데이터
    public CustomDTO getReadData(int id){
        
        CustomDTO dto=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        String sql;
        
        try {
            conn=dataSource.getConnection();
            
            sql="select id,name,age from custom where id=?";
            
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            
            rs=pstmt.executeQuery();
            
            if(rs.next()) {
                dto=new CustomDTO();
                
                dto.setId(rs.getInt("id"));
                dto.setName(rs.getString("name"));
                dto.setAge(rs.getInt("age"));
            }
            
            rs.close();
            pstmt.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return dto;
    }
    
    //delete
    public int deleteDate(int id) {
        int result=0;
        PreparedStatement pstmt=null;
        String sql;
        
        try {
            conn=dataSource.getConnection();
            
            sql="delete from custom where id=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            
            result=pstmt.executeUpdate();
            pstmt.close();
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return result;
    }
}
cs


-CustomMain.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
package com.exe.springjdbctemplate;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class CustomMain {
 
    public static void main(String[] args) {
        
        GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        CustomDAO dao=(CustomDAO)context.getBean("customDAO");
 
        CustomDTO dto;
        
        dto=new CustomDTO();
        dto.setId(111);
        dto.setName("배수지");
        dto.setAge(25);
        
        dao.insertData(dto);
        
        System.out.println("insert 완료!");
        
    }
}
cs


-실행화면


(자바 콘솔창)


(cmd 창)

: DB에서도 잘 들어간것을 알 수 있다.



** 위에 코드로 DB 연결이 안될 경우 해결방법


위처럼 코딩을 한 경우에 DB에 연결이 안되는 경우가 있다.

이럴 때는 오라클 lib를 pom.xml에 추가해주어야한다. 추가해주어야 할 것은 아래와 같다.


1. ojdbc6 lib

2. 오라클 lib : 오라클은 직접 lib을 못가져다쓰게 해놔서 코드를 좀 다르게 써주어야한다.


-링크: https://mvnrepository.com/ 


1. ojdbc6 검색>12.1.0.1 버전 선택


-pom.xml의 dependencies 안에 아래 코드 추가해준다.

1
2
3
4
5
6
7
        <!-- ojdbc6 -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>12.1.0.1-atlassian-hosted</version>
            <scope>test</scope>
        </dependency>
cs


2. oracle lib 추가

아까의 페이지에서 아래의 Atlassian 3rdParty버튼 눌러서

: 이 url을 붙여서 아래의 코드의 url에 써준다.


-pom.xml의 dependencies 밖에 아래 코드 써준다.

1
2
3
4
5
6
7
    <repositories>
        <repository>
            <id>oracle</id>
            <name>Oracle JDBC Repository</name>
            <url>https://packages.atlassian.com/maven-3rdparty/</url>
        </repository>
    </repositories>
cs


-CustomMain.java에서 update,select 등 해보자.

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
package com.exe.springjdbctemplate;
 
import java.util.List;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class CustomMain {
 
    public static void main(String[] args) {
        
        GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        CustomDAO dao=(CustomDAO)context.getBean("customDAO");
        
        CustomDTO dto;
        /*
        dto=new CustomDTO();
        dto.setId(111);
        dto.setName("배수지");
        dto.setAge(25);
        
        dao.insertData(dto);
        
        System.out.println("insert 완료!");
        */
        
        //Oneselect
        dto=dao.getReadData(222);
        
        if(dto!=null) {
            System.out.printf("%d %s %d\n",dto.getId(),dto.getName(),dto.getAge());
        }
        
        System.out.println("OneSelect 완료!");
        
        //update
        dto = new CustomDTO();
        
        dto.setId(111);
        dto.setName("권지용");
        dto.setAge(22);
        
        dao.updateData(dto);
        
        //delete
        dao.deleteDate(222);
 
        //select
        List<CustomDTO> lists=dao.getList();
        
        for(CustomDTO dto1:lists) {
            System.out.printf("%d %s %d\n",dto1.getId(),dto1.getName(),dto1.getAge());
        }
        
        System.out.println("select 완료!");
    }
}
cs


-실행화면





3. 스프링에서 Spring JDBC 사용 


-링크: https://mvnrepository.com/artifact/org.springframework/spring-jdbc/5.1.6.RELEASE

spring-jdbc 검색 후 전과 똑같이 하단의 코드를 pom.xml에 붙여넣는다. 

대신 버전은 ${spring.framework.version}이렇게 써줘야한다. (위의 spring.framework.version을 바꾸면 같이 바뀌게)


-pom.xml

1
2
3
4
5
6
        <!-- spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
cs


**Spring JDBC 사용하려면...


-app-context.xml에 추가

: Spring JDBC써줄려면 jdbcTemplate만들어 주어야한다.


-CustomDAO2.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
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
package com.exe.springjdbctemplate;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import javax.sql.DataSource;
 
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
 
public class CustomDAO2 {
 
    private JdbcTemplate jdbcTemplate;
    
    //의존성 주입
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate=jdbcTemplate;
    }
    
    Connection conn=null;
    
    //insert
    public void insertData(CustomDTO dto) {
        
        StringBuilder sql=new StringBuilder();
            
        sql.append("insert into custom(id,name,age) values (?,?,?)");
        jdbcTemplate.update(sql.toString(),
                dto.getId(),dto.getName(),dto.getAge());    
    }
    
    //select 모든 데이터
    public List<CustomDTO> getList(){
        
        StringBuilder sql=new StringBuilder();
            
        sql.append("select id,name,age from custom");
        
        List<CustomDTO> lists=jdbcTemplate.query(sql.toString(), 
                new RowMapper<CustomDTO>() {
 
                    //RowMapper가 while문같은 역할
                    //ResultSet에 select한 결과를 담아서 dto에 반환한다.
                    //그거를 위에 RowMapper<CustomDTO>에 하나씩 담는다.
                    public CustomDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
                        
                        CustomDTO dto=new CustomDTO();
                        
                        dto.setId(rs.getInt("id")); 
                        dto.setName(rs.getString("name"));
                        dto.setAge(rs.getInt("age"));
                    
                        return dto;
                    }            
        });
        
        return lists;    
    }
    
    //select 1개의 데이터
    public CustomDTO getReadData(int id){
        StringBuilder sql=new StringBuilder();
        
        sql.append("select id,name,age from custom where id=?");
        
        CustomDTO dtoOne=jdbcTemplate.queryForObject(sql.toString(),
                new RowMapper<CustomDTO>() {
 
                    public CustomDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
                            
                        CustomDTO dto=new CustomDTO();
                        
                        dto.setId(rs.getInt("id"));
                        dto.setName(rs.getString("name"));
                        dto.setAge(rs.getInt("age"));
                        
                        return dto;
                    }
        },id);
        
        return dtoOne;
    }
    
    //update
    public void updateData(CustomDTO dto) {
 
        StringBuilder sql=new StringBuilder();
            
        sql.append("update custom set name=?,age=? where id=?");
        jdbcTemplate.update(sql.toString(),dto.getName(),dto.getAge(),dto.getId());
    }
    
    //delete
    public void deleteDate(int id) {
 
        StringBuilder sql=new StringBuilder();
        
        sql.append("delete from custom where id=?");
        jdbcTemplate.update(sql.toString(),id);
 
    }
}
cs


-CustomMain.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
53
54
55
56
57
58
package com.exe.springjdbctemplate;
 
import java.util.List;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class CustomMain {
 
    public static void main(String[] args) {
        
        GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        CustomDAO2 dao=(CustomDAO2)context.getBean("customDAO2");
        
        CustomDTO dto;
        /*
        dto=new CustomDTO();
        dto.setId(555);
        dto.setName("전정국");
        dto.setAge(23);
        
        dao.insertData(dto);
        
        System.out.println("insert 완료!");
        */
        
        //Oneselect
        dto=dao.getReadData(555);
        
        if(dto!=null) {
            System.out.printf("%d %s %d\n",dto.getId(),dto.getName(),dto.getAge());
        }
        
        System.out.println("OneSelect 완료!");
        
        /*
        //update
        dto = new CustomDTO();
        
        dto.setId(111);
        dto.setName("권지용");
        dto.setAge(22);
        
        dao.updateData(dto);
        
        //delete
        dao.deleteDate(222);
         */
        //select
        List<CustomDTO> lists=dao.getList();
        
        for(CustomDTO dto1:lists) {
            System.out.printf("%d %s %d\n",dto1.getId(),dto1.getName(),dto1.getAge());
        }
        
        System.out.println("select 완료!");
    }
}
cs


-실행화면





4. Spring JDBC 중 NamedParameterJdbcTemplate


-app-context.xml에 추가

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
    <!-- Spring JDBC -->
    <bean id="customDAO2" class="com.exe.springjdbctemplate.CustomDAO2">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        <property name="namedJdbcTemplate" ref="namedParameterJdbcTemplate"></property><!-- 여기도 추가 -->
    </bean>
    
    <bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>
    
    <!-- 이 부분!! -->
    <bean id="namedParameterJdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>
 
    <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="oracle.jdbc.driver.OracleDriver"
    p:url="jdbc:oracle:thin:@192.168.16.12:1521:TestDB"
    p:username="suzi"
    p:password="a123"
    />
cs

: Spring JDBC를 쓴부분에 named~ 객체를 추가하고 customDAO2에 property(메소드)의 매개변수로 추가해주었다.


-CustomDAO.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
public class CustomDAO2 {
 
    /*
    private JdbcTemplate jdbcTemplate;
    
    //의존성 주입
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate=jdbcTemplate;
    }*/
 
    private NamedParameterJdbcTemplate namedJdbcTemplate;
    
    public void setNamedJdbcTemplate(NamedParameterJdbcTemplate namedJdbcTemplate) {
        this.namedJdbcTemplate=namedJdbcTemplate;
    }
    
    Connection conn=null;
    
    //insert
    public void insertData(CustomDTO dto) {
        
        StringBuilder sql=new StringBuilder();
            
        /*
         * sql.append("insert into custom(id,name,age) values (?,?,?)");
         * jdbcTemplate.update(sql.toString(), dto.getId(),dto.getName(),dto.getAge());
         */
        
        sql.append("insert into custom (id,name,age) values (:id,:name,:age)");
        
        MapSqlParameterSource params=new MapSqlParameterSource();
        params.addValue("id", dto.getId());
        params.addValue("name", dto.getName());
        params.addValue("age", dto.getAge());
        
        namedJdbcTemplate.update(sql.toString(), params);
    }
cs

: 예시로 insert부분만 구현해 보았다.

그냥 Spring JDBC와는 차이점은

NamedParameterJdbcTemplate은 sql문에서 매개변수로 보내줄 때 ?대신 :id, :name 이런 식으로 보내준다.


-CustomMain.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
package com.exe.springjdbctemplate;
 
import java.util.List;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class CustomMain {
 
    public static void main(String[] args) {
        
        GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        CustomDAO2 dao=(CustomDAO2)context.getBean("customDAO2");
        
        CustomDTO dto;
 
        //insert
        dto=new CustomDTO();
        dto.setId(444);
        dto.setName("김지은");
        dto.setAge(20);
        
        dao.insertData(dto);
        
        System.out.println("insert 완료!");
 
        //select
        List<CustomDTO> lists=dao.getList();
        
        for(CustomDTO dto1:lists) {
            System.out.printf("%d %s %d\n",dto1.getId(),dto1.getName(),dto1.getAge());
        }
        
        System.out.println("select 완료!");
    }
}
cs


-실행화면


1. DTO를 만들자 


어제만든 home.jsp에서 name, phone, email이라는 변수를 넘겨준다.

저번 글 링크 : https://welcomto-dd.tistory.com/42


-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
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
<P>  The time on the server is ${serverTime}. </P>
<h3><a href="hello.action">Spring 환영 메세지</a></h3>
<h3><a href="test/param.action?name=suzi&phone=010-123-1234&email=suzi@naver.com">GET방식 테스트</a> </h3>
 
<h3>2. Post방식 테스트</h3>
<form action="test/param.action" method="post">
이름:<input type="text" name="name"><br/>
전화:<input type="text" name="phone"><br/>
메일:<input type="text" name="email"><br/>
<input type="submit" value="전송"/><br/>
 
</form>
</body>
</html>
cs

: 13,17,18,19번째 줄에서 변수를 넘겨주는 것을 볼 수 있다.


-PersonDTO.java

1
2
3
4
5
6
7
8
9
10
package com.exe.springmvc;
 
public class PersonDTO {
    
    private String name;
    private String phone;
    private String email;
 
    //getter,setter는 생략...
}
cs

: 넘겨준 변수를 받아줄 DTO를 만들었다.


-실행화면

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
package com.exe.springmvc;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller("test.controller")
public class TestController {
    
    @RequestMapping(value = "/test/param.action",method = {RequestMethod.POST,RequestMethod.GET})
    public String processPostRequest(PersonDTO dto, String name,HttpServletRequest request) {
        System.out.println("get/post 방식 Request");
        
        System.out.println(name);
        System.out.println(request.getParameter("phone"));
        
        System.out.println(dto);    //해시코드가 찍힘
        System.out.println("dto.getName(): "+dto.getName() );
        System.out.println("dto.getPhone(): "+dto.getPhone() );
        System.out.println("dto.getEmail(): "+dto.getEmail() );
        return "paramResult";
    }
}
cs

: 여기서 PersonDTO dto라는 매개변수를 추가해주고 system.out.println()으로 찍어서 출력해보자


-실행화면

: dto.setAttribute() 이런 작업 없이 스프링이 자동으로 잘 담아준 모습을 볼 수 있다!


**DTO를 만들어주고 변수이름을 맞춰주니 스프링이 알아서 DTO안에 넣어서 

주고받는 것을 알 수 있다.


2. 웹에서 한글 깨져 보일때 


-web.xml에 아래의 코드 추가해주자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <!-- 생략...-->
 
    <!-- 한글 인코딩(웹에서 깨져보일때) -->
    <filter>
        <filter-name>CharsetEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>CharsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
cs


-실행화면

: 한글이 깨지지 않고 잘 나온다.


3. ModelAndView에 넣어서 DTO 보내기 


**ModelAndView는 view경로와 dto를 한번에 묶어서 보낼 수 있는 자료형이다.


-home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<!-- 생략 -->
<h3><a href="test/mav.action?name=shin&phone=010-234-5555&email=shin@naver.com">3. ModelAndView Get 테스트</a></h3>
 
<h3>4. ModelAndView Post 테스트</h3>
<form action="test/mav.action" method="post">
이름:<input type="text" name="name"><br/>
전화:<input type="text" name="phone"><br/>
메일:<input type="text" name="email"><br/>
<input type="submit" value="전송"/><br/>
</form>
</body>
</html>
cs


-TestController.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
package com.exe.springmvc;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller("test.controller")
public class TestController {
    
    //생략...
 
    @RequestMapping(value="/test/mav.action",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView mavRequest(PersonDTO dto) {
        
        ModelAndView mav=new ModelAndView();
        mav.setViewName("paramResult");//view와
        mav.addObject("dto",dto);//dto를 함께 포장!!
        //dto는 여러개 보낼수 있다.
        //View는 하나여야한다.
        
        return mav;
    }
}
cs

: 여기서 ModelAndView mav라는 변수를 만들어서 보여줄 페이지인 view, 여기서는 paramResult.jsp 의 경로와,

dto를 담았다. 그리고 mav 리턴.


-paramResult.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
<%@page import="com.exe.springmvc.PersonDTO"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
    
    String name=request.getParameter("name");//String을 받을때는 Parameter
    String phone=request.getParameter("phone");
    String email=request.getParameter("email");
    
    PersonDTO dto=(PersonDTO)request.getAttribute("dto");//Object를 받을때는 Attribute(모든객체 다 받을수 있다.)
    
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h2>Param Result</h2>
이름:<%=name %><br/>
전화:<%=phone %><br/>
이메일:<%=email %><br/>
 
<br/><br/>
 
<h2>ModelAndView</h2>
<%if(dto!=null){ %>
이름:<%=dto.getName() %><br/>
전화:<%=dto.getPhone() %><br/>
이메일:<%=dto.getEmail() %><br/>
<%}else%>
    데이터없음
<%%>
</body>
</html>
cs

: dto를 TestController에서 보내줬기 떄문에 받아서 출력해준다.


**여기서 getParameter와 getAttribute의 차이

getParameter() : return값이 String만이 가능하다.

getAttribute() : return값으로 Object가 가능, 즉 모든 객체를 담을수 있음. 



4. Redirect 


**Redirect 쓰는 방법

1
2
3
4
5
6
    @RequestMapping(value="/test/redirect.action",method = {RequestMethod.GET,RequestMethod.POST})
    public String mavRedirectRequest(PersonDTO dto) {
        
        //return "redirect:/";    //홈으로 리다이렉트
        return "redirect:/hello.action";
    }
cs



1. annotation 사용 안 함 


-폴더 구조

: 객체생성에 관한 내용은 app-context.xml파일에 써주고 실행은 MessageMain.java에서 실행한다.


-app-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <description>Example configuration to get you started.</description>
 
    <!-- 어떤 패키지에만 환경셋팅 적용할지  -->
    <context:component-scan base-package="*" />
 
    <bean id="message" class="com.exe.springdi3.MessageKr"/>
    <!-- 중간지점 클래스를 Main에서 생성하는 객체 -->
    <!-- IoC(제어의 역전) -->
    <bean id="serviceConsumer" class="com.exe.springdi4.ServiceConsumer">
        <constructor-arg ref="messageService"></constructor-arg>
        <property name="timeService" ref="timeService"/
        <property name="jobService" ref="jobService"/>
    </bean>
    <bean id="messageService" class="com.exe.springdi4.MyMessageService"/>
    <bean id="timeService" class="com.exe.springdi4.MyTimerService"/>
    <bean id="jobService" class="com.exe.springdi4.MyJobService"></bean>
</beans>
cs

: annotation을 사용하지 않을 경우 app-context.xml에 위의 코드들을 써주어야 한다.


-ServiceConsumer.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
53
package com.exe.springdi4;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
//얘가 중간관리자
public class ServiceConsumer {
    
    MessageService ms;
    
    //오버로딩된 생성자가 있을 경우 기본생성자가 무조건 있어야하므로
    //여기에 명시해줌
    public ServiceConsumer() {};
    
    //생성자로 초기화
    //생성자로 의존성 주입
    public ServiceConsumer(MessageService ms) {
        this.ms=ms;
    }
    
    //메소드로 의존성 주입1
    TimeService ts;
    
    //여기는 app-context의 property name의 set뒤에 대문자로 바꾼 이름
    public void setTimeService(TimeService ts) {
        this.ts = ts;
    }
    
    //메소드로 의존성 주입2
    JobService js;
    
    public void setJobService(JobService js) {
        this.js=js;
    }
 
    public void consumerService() {
        
        //GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        //app-context.xml에서 읽어옴
        //MessageService ms=(MessageService)context.getBean("messageService");
        
        //생성자 의존성 주입
        String message=ms.getMessage();
        System.out.println(message);
        
        //메소드 의존성 주입1
        String time=ts.getTimeString();
        System.out.println(time);
        
        //메소드 의존성 주입2
        js.getJob();    
    }
}
cs

: app-context.xml과 ServiceConsumer.java 사이의 관계가 중요하다.


-그 외 파일들

: 여기서 JobService.java와 MyJobService.java가 Interface와 Class로 하나의 짝이고

(MyJobService 클래스가 JobService 인터페이스의 메소드를 오버라이딩해서 구현함)

MessageService.java와 MyMessageService.java, TimeService와 MyTimerService도 마찬가지로 짝이다.


다 같은 구조이므로 예시로 JobService.java와 MyJobService.java만 보여주면


-JobService.java

1
2
3
4
5
6
package com.exe.springdi4;
 
public interface JobService {
 
    public void getJob();
}
cs


-MyJobService.java

1
2
3
4
5
6
7
8
package com.exe.springdi4;
 
public class MyJobService implements JobService {
 
    public void getJob() {
        System.out.println("나는 프로그래머 입니다.");
    }
}
cs


-실행화면


**그런데 여기서!!

**autowire="byName"의 기능

-app-context.xml  

1
2
3
4
5
6
7
8
9
<bean id="serviceConsumer" class="com.exe.springdi4.ServiceConsumer"
    autowire="byName">
    <constructor-arg ref="messageService"></constructor-arg>
<!--     <property name="timeService" ref="timeService"/> 
        <property name="jobService" ref="jobService"/> -->
    </bean>
    <bean id="messageService" class="com.exe.springdi4.MyMessageService"/>
    <bean id="timeService" class="com.exe.springdi4.MyTimerService"/>
    <bean id="jobService" class="com.exe.springdi4.MyJobService"></bean>
cs


autowire="byName"을 써줄경우 생성자는 제외, 메소드로 의존성주입을 한 경우

밑의 bean id로 (set을 빼고 맨앞글자는 소문자)의 규칙에 맞으면 스프링이 알아서 찾아가게 된다.


실행해보면 위의 property부분을 주석처리해도 잘 실행되는 모습을 볼 수 있다.




2. annotation 사용 


-app-context.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <description>Example configuration to get you started.</description>
 
    <!-- 어떤 패키지에만 환경셋팅 적용할지  -->
    <context:component-scan base-package="*" />
    
    <!-- annotation 사용할 거임 -->
    <!-- 
    <bean id="message" class="com.exe.springdi3.MessageKr"/>
    중간지점 클래스를 Main에서 생성하는 객체
    IoC(제어의 역전)
    <bean id="serviceConsumer" class="com.exe.springdi4.ServiceConsumer"
    autowire="byName">
        <constructor-arg ref="messageService"></constructor-arg>
        <property name="timeService" ref="timeService"/>
        <property name="jobService" ref="jobService"/>
    </bean>
    <bean id="messageService" class="com.exe.springdi4.MyMessageService"/>
    <bean id="timeService" class="com.exe.springdi4.MyTimerService"/>
    <bean id="jobService" class="com.exe.springdi4.MyJobService"></bean>
     -->
</beans>
cs

: annotation을 안써줬을경우 써야하는 위의 코드를 annotation을 사용함으로써 모두 주석처리해주었다.


- 각 annotation의 역할

: @Component : 자동으로 빈 등록

@Component annotation을 사용해 bean을 각 java파일에서 생성하도록 해주었다.


: @Component로 객체 생성을 해주고 @Autowired(및 @Qualifier)를 이용해 생성자및 메소드의 파라미터를 넘겨준다.


-실행화면



** Annotation을 사용하는 게 훨씬 간단하다. 

1. 스프링 3.0 프로젝트 생성 및 경로 셋팅 


: 프로젝트의 이름을 써주고 Spring MVC project를 선택해서 생성해준다.


-프로젝트 경로


: 프로젝트의 이름은 "SpringMVC1" 으로 해주었지만 프로젝트 생성해줄때 패키지를 com.exe.springmvc로 설정해주었기 때문에

이게 스프링 웹 경로상의 주소는 "springmvc"가 된다. 

Web Project Settings에서 웹주소상의 경로를 확인할 수 있다.


2. 웹과의 연결 


-TestController.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
package com.exe.springmvc;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller("test.controller")
public class TestController {
    /*
     * @RequestMapping(value="/test/param.action",method = {RequestMethod.GET})
     * public String processGetRequest() {
     * 
     * System.out.println("GET 방식 Request");
     * 
     * return "paramResult";// /WEB-INF/views/paramResult.jsp }
     * 
     * @RequestMapping(value = "/test/param.action",method = {RequestMethod.POST})
     * public String processPostRequest() { System.out.println("post 방식 Request");
     * 
     * return "paramResult"; }
     */
    
    @RequestMapping(value = "/test/param.action",method = {RequestMethod.POST,RequestMethod.GET})
    public String processPostRequest(String name,HttpServletRequest request) {
        System.out.println("get/post 방식 Request");
        
        System.out.println(name);
        System.out.println(request.getParameter("phone"));
        
        return "paramResult";
    }
}
cs

: 주석 처리안한 메소드는 get,post방식을 하나의 메소드로 만든것이다.

/test/param.action의 경로의 주소를 입력하면 위의 메소드가 실행된다.

system.out.println()의 결과는 콘솔에 찍히고, 마지막에 paramResult.jsp로 보내준다.


**여기서 주목할 점은 Controller의 경로에는 "/test/param.action"이라고 "/"를 앞에 붙이지만

밑에 JSP파일에서는 "test/param.action" 이라고 쓴다. 헷갈리지 않게 명심!


-paramResult.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
    
    String name=request.getParameter("name");
    String phone=request.getParameter("phone");
    String email=request.getParameter("email");
    
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h2>Param Result</h2>
이름:<%=name %><br/>
전화:<%=phone %><br/>
이메일:<%=email %><br/>
 
</body>
</html>
cs

: home에서 넘어온 매개변수를 request.getParameter로 받아서 <%=name%>으로 각각 출력해주는 역을 한다.


-home.jsp

: index.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
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
 
<P>  The time on the server is ${serverTime}. </P>
 
<h3><a href="hello.action">Spring 환영 메세지</a></h3>
<h3><a href="test/param.action?name=suzi&phone=010-123-1234&email=suzi@naver.com">GET방식 테스트</a> </h3>
 
<h3>2. Post방식 테스트</h3>
<form action="test/param.action" method="post">
이름:<input type="text" name="name"><br/>
전화:<input type="text" name="phone"><br/>
메일:<input type="text" name="email"><br/>
<input type="submit" value="전송"/><br/>
 
</form>
</body>
</html>
cs

매개변수를 넘겨주는 역할을 하는 jsp페이지이다.


-실행화면

주소는 localhost/springmvc/로 들어가서 링크를 타고 들어가면 된다.



1. Spring 3.0 버전 이클립스 다운 


다운로드 링크 : https://spring.io/tools


메인 화면 맨 밑의 하단 TOOLS > Spring Tools 3 for Eclipse>아래 이미지에 표시해놓은 버튼눌러서 다운 

(Spring 3.9.8버전 다운로드)


- 다운 받아서 원하는 경로에 폴더 설정해준다 (웹서버인 톰캣과, 프로젝트 생성폴더인 work폴더 셋팅)



- server.xml 에 GET방식으로 받을때 한글인코딩해주기위해서 저 부분 써준다.

(경로: D:\sts-bundle\apache-tomcat-7.0.92\conf\server.xml)



-window>preperences에서 인코딩방식 바꿔준다.


-기존에 깔려있던 pivotal-tc-server 서버는 안쓸거기 때문에 삭제해준다.


-window>preperences>Server>Runtime Environment 가서도 삭제



**앞으로의 진도 일정

1. Pojo 문법

2. jdbc->mybatis->Spring JDBC

3. Web

4. jdbc->mybatis->SPring JD


2. 프로젝트 생성 (New Legacy Project) 



-next


**프로젝트에 오류뜰때 없애는 방법 2가지


1. repository 폴더 내용 삭제 

이 경로의 repository에 있는 폴더를 다 지우고 

다시 이클립스 재부팅하면 이클립스에서 다시 라이브러리를 받는다.


또 다른 방법은

2. Maven>update project

눌러주면 이클립스에서 필요한 Maven 라이브러리 다운 받는다.




3. 간단한 날짜 예제 


-TimeService.java

1
2
3
4
5
6
7
package com.exe.springdi4;
 
public interface TimeService {
 
    public String getTimeString();
    
}
cs


-MyTimerService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.exe.springdi4;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.management.timer.TimerMBean;
 
public class MyTimerService implements TimeService {
 
    public String getTimeString() {
        
        //날짜를 지정해주는 형식을 지정해줌
        SimpleDateFormat sdf= (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance(
                SimpleDateFormat.LONG,SimpleDateFormat.LONG);
        
        String now=sdf.format(new Date());
        
        return now;
    }
}
cs


-SerciveConsumer.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
package com.exe.springdi4;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
//얘가 중간관리자
public class ServiceConsumer {
    
    MessageService ms;
    
    //오버로딩된 생성자가 있을 경우 기본생성자가 무조건 있어야하므로
    //여기에 명시해줌
    public ServiceConsumer() {};
    
    //생성자로 초기화
    //생성자로 의존성 주입
    public ServiceConsumer(MessageService ms) {
        this.ms=ms;
    }
    
    //메소드로 의존성 주입
    TimeService ts;
    
    public void setTimeService(TimeService ts) {
        this.ts = ts;
    }
 
 
    public void consumerService() {
        
        //GenericXmlApplicationContext context=new GenericXmlApplicationContext("app-context.xml");
        
        //app-context.xml에서 읽어옴
        //MessageService ms=(MessageService)context.getBean("messageService");
        
        //생성자 의존성 주입
        String message=ms.getMessage();
        System.out.println(message);
        
        //메소드 의존성 주입
        String time=ts.getTimeString();
        System.out.println(time);
        
    }
}
cs




4. autowire="byName"과 annotation 


** autowire="byName"

1
2
3
4
5
6
7
8
9
<bean id="serviceConsumer" class="com.exe.springdi4.ServiceConsumer"
    autowire="byName">
        <constructor-arg ref="messageService"></constructor-arg>
        <property name="timeService" ref="timeService"/>
        <!-- <property name="jobService" ref="jobService"/> -->
    </bean>
    <bean id="messageService" class="com.exe.springdi4.MyMessageService"/>
    <bean id="timeService" class="com.exe.springdi4.MyTimerService"/>
    <bean id="jobService" class="com.exe.springdi4.MyJobService"></bean>
cs

: autowire="byName"이라고 써주면

property에 따로 써주지않아도 bean의 id와 메소드의 이름을보고 스프링이 알아서 찾아간다.


**@Component

@Component와 같은 역할을 하는 부분

1
2
    <bean id="serviceConsumer" class="com.exe.springdi4.ServiceConsumer"
    autowire="byName">
cs


**@Autowired

@Autowired와 같은 역할을 하는 부분

1
<constructor-arg ref="messageService"></constructor-arg>
cs



1. 연관검색어 기능 


-검색어를 입력하면 keyup이 될 때마다 맞는 검색어가 밑에 링크로 뜬다.

링크를 누르면 inputbox안에 value가 들어간다.


-suggestClient.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    .suggest{
        display: none;
        position: absolute;
        left:11px;
        top:131px;
    }    
</style>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
 
    //inputbox에 keyup될때마다 호출
    function sendKeyword(){
        
        var userKeyword=document.myForm.userKeyword.value;
        
        //아무것도 없을때 결과창을 숨긴다.
        if(userKeyword==""){
            hide();
            return;
        }
        
        var params="userKeyword="+userKeyword;
        
        sendRequest("suggestClient_ok.jsp", params, displaySuggest, "POST");
    }
    
    function displaySuggest(){
        
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                
                //5|abc,ajax,abc마트 값이 여기로 들어옴
                var resultText=httpRequest.responseText;
                
                var resultArray=resultText.split("|");
                
                //검색창 결과 갯수
                var count=resultArray[0];
                
                //alert(count);
                
                var keywordList=null;
                
                if(count>0){
                    keywordList=resultArray[1].split(",");
                    
                    var html="";
                    
                    for(var i=0;i<keywordList.length;i++){
                        //select호출
                        html += "<a href=\"javascript:select('" +
                                keywordList[i] + "');\">" +
                                keywordList[i] + "</a><br/>";
                        //<a href="javascript:select('ajax');">ajax</a><br/>
                        
                    }
                    var suggestListDiv=document.getElementById("suggestListDiv");
                    suggestListDiv.innerHTML=html;
                    show();
                    
                }else{
                    //count==0
                    hide();
                }
                
            }else{
                //status!=200
                hide();
            }
            
        }else{
            //readystate!=4
            hide();
        }
        
        
    }
    
    //사용자가 제시어에서 클릭한 키워드
    function select(selectKeyword){
        //클릭한 제시어를 inputbox에 넣어줌
        document.myForm.userKeyword.value=selectKeyword;
        hide();
    }
    
    function show(){
        var suggestDiv=document.getElementById("suggestDiv");
        suggestDiv.style.display="block";//보여짐
    }
    
    function hide(){
        var suggestDiv=document.getElementById("suggestDiv");
        suggestDiv.style.display="none";//숨김
    }
    
    window.onload=function(){
        hide();    
    }
    
</script>
</head>
<body>
<h1>제시어</h1>
<hr/>
<br>
<form action="" name="myForm">
<input type="text" name="userKeyword" onkeyup="sendKeyword();"/>
<input type="button" value="검색"/>
 
<div id="suggestDiv" class="suggest">
    <div id="suggestListDiv"></div>
</div>
</form>
</body>
</html>
cs



-suggestClient_ok.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
<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Collections"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
 
<%!
    String[] keywords={"ajax","Ajax","Ajax 실전 프로그래밍",
        "AZA","AZERA","자수","자전거","자바 프로그래밍",
        "자바 서버 페이지","자바캔","ABC마트","APPLE"
    };
 
    public List<String> search(String userKeyword){
        if(userKeyword==null||userKeyword.equals("")){
            return null;
            //이것도 가능
            //return Collections.EMPTY_LIST;
        }
        
        //userKeyword=userKeyword.toUpperCase();//대문자 검색
        
        List<String> lists=new ArrayList<String>();
        
        for(int i=0;i<keywords.length;i++){
            if(keywords[i].startsWith(userKeyword)){
                lists.add(keywords[i]);
            }
        }
        return lists;
    }
%>
 
<%
    String userKeyword=request.getParameter("userKeyword");
 
    List<String> keywordList=search(userKeyword);
    
    out.print(keywordList.size());
    
    out.print("|");
    
    Iterator<String> it=keywordList.iterator();
    
    while(it.hasNext()){
        String value=(String)it.next();
        
        out.print(value);
        
        //마지막에는 쉼표 안찍게
        if(keywordList.size()-1>0){
            out.print(",");
        }
    }
    
    //5|abc,ajax,abc마트
%>
 
cs



-실행화면



2. HTML DOM 객체를 이용한 노드 추가, 제거 

- 버튼을 누르면 노드를 추가하고 삭제할 수 있다.

이를 응용하면 파일을 추가하고 삭제하는 기능들을 만들 수 있다.


-DOM 객체 트리


- book 노드의 입장에서 firstChild는 title 노드가 되며, lastChild는 price가 된다.

- title 노드 입장에서 parentNode는 book 노드가 된다.

- book 노드 입장에서 parentNode는 books 노드가 된다.

- books 노드의 입장에서 firstChild 노드는 좌측의 book 노드이며, lastChild 노드는 우측의 book 노드가 된다.

- previousSibling 프로퍼티와 nextSibling 프로퍼티는 자식노드들 사이의 관계를 나타낸다. 예를 들어

author 노드의 입장에서 previousSibling은 title노드가 되고, nextSibling은 price가 된다.

- book 노드의 childNodes는 title노드, author노드, price노드가 되며, NodeList의 형태로 저장된다.

- NodeList는 childNodes로 구한 자식 노드에 접근할 수 있도록 하기 위해서 아래와 같은 두 가지를 제공하고 있다.



- Node 인터페이스의 주요 프로퍼티

 프로퍼티 타입

프로퍼티 이름 

설명 

String 

nodeName 

노드의 이름 

String  

nodeValue 

노드의 값 

unsigned short 

nodeType 

노드 타입 

Node 

parentNode 

부모노드 

Node

childNodes

자식 노드 목록 

Node 

firstChild 

첫 번째 사식 노드 

Node 

lastChild 

 마지막 자식 노드

Node 

previousSibling 

현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 이전의 자식 노드 

 Node

nextSibling 

현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 다음의 자식 노드 

 Document

ownerDocument 

이 노드가 포함된 Document 객체



-changeHTMLUsingDOM.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var count=0;
    function addItem(){
        count++;
        
        var newItemE=document.createElement("div");
        newItemE.setAttribute("id","item_"+count);
        
        var html="새로 추가된 아이템["+count+"]&nbsp;";
        html+="<input type=\"button\" value=\"삭제\" onclick=\"removeItem('item_" +count+ "');\"/>";        
    
        //<div id="item_1">
        //새로 추가된 아이템[1]<input type="button" value="삭제"
        //onclick="removeItem('item_1')"/>
        
        newItemE.innerHTML=html;
        
        var itemListDiv=document.getElementById("itemList");
        
        itemListDiv.appendChild(newItemE);
    }
    
    function removeItem(itemId){
        var removeItem=document.getElementById(itemId);
        removeItem.parentNode.removeChild(removeItem);
    }
    
</script>
</head>
<body>
<h1>HTML DOM을 이용한 화면 변경</h1>
<hr/>
<input type="button" value="추가" onclick="addItem(); "/>
<div id="itemList"></div>
 
</body>
</html>
cs



-실행화면



3. XML파일 Javascript로 읽어오기 


-books.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <title>겨울왕국</title>
        <author>디즈니</author>
    </book>
    <book>
        <title>수지의 가수생활</title>
        <author>EBS</author>
    </book>
    <book>
        <title>이솝우화</title>
        <author>미드</author>
    </book>
    <book>
        <title>힐러리의 삶</title>
        <author>클린턴</author>
    </book>
</books>
cs


-getBookXML.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
 
    function getBookList(){
        sendRequest("books.xml"null, displayBookList, "GET");
    }
 
    function displayBookList(){
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                //전달받은 XML을 DOM객체에 넣음
                 var Document=httpRequest.responseXML; //Text가 아니라 XML파일을 받았다!
                
                 //DOM 객체에서 Elements추출
                 var booksE=Document.documentElement;
                 
                 //book의 갯수 추출
                 var bookNL=booksE.getElementsByTagName("book");
                 //alert(bookNL.length);
                 
                 //전체데이터 읽고 HTML로 출력
                 var html="";
                 html+="<ol>";
                 for(var i=0;i<bookNL.length;i++){
                     
                     //하나의 book을 읽어냄
                     var bookE=bookNL.item(i);
                     var titleStr=bookE
                         .getElementsByTagName("title")
                         .item(0)
                         .firstChild
                         .nodeValue;
                     
                     var authorStr=bookE
                         .getElementsByTagName("author")
                         .item(0)
                         .firstChild
                         .nodeValue;
                     
                     html+= "<li>"
                         + titleStr
                         +"&nbsp;-&nbsp;"
                         + authorStr+"</li>";
                 }
                 html+="</ol>";
                 
                 document.getElementById("bookDiv").innerHTML=html;
            
            }
        }
    }
     
    window.onload=function(){
        getBookList();
    }
</script>
 
</head>
<body>
<h1 id="list">Book List</h1>
<hr/>
<div id="bookDiv" style="display:block; margin:0 auto;"></div>
 
</body>
</html>
cs


-실행화면




4. newsTtitle 을 XML 파일로 받아오기 

- 저번에는 'httpRequest.responseText'로 받았지만 이번에는 'httpRequest.responseXML'을 이용해서  

XML 파일로 받아보자. (쉼표보다 XML파일로 가져오는게 더 간편하다)


-newsTitleXML.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    div{
        margin:auto;
        border:1px solid #0000ff;
        width:600px;
        height:70%;
        padding:10px;
    }
    
</style>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
    function newsTitle(){
        sendRequest("newsTitleXML_ok.jsp"null, displayNewsTitle, "GET");
        
        setTimeout("newsTitle()",3000);
    }
    
    function displayNewsTitle(){
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                
                var doc=httpRequest.responseXML;
                //alert(doc); //objext XMLDocument
                
                var count=
                    doc.getElementsByTagName("count")
                    .item(0)
                    .firstChild
                    .nodeValue;
                
                //alert(count);
                
                if(count>0){
                    //title의 갯수
                    var titleNL=doc.getElementsByTagName("title");
                    
                    var htmlData="<ol>";
                    
                    for(var i=0;i<titleNL.length;i++){
                        htmlData+="<li>"
                            +titleNL.item(i).firstChild.nodeValue
                            +"</li>";
                    }
                    htmlData+="</ol>";
                    
                    var newsDiv=document.getElementById("news");
                    
                    newsDiv.innerHTML=htmlData;
                }
            }else{
                alert(httpRequest.status+":"+
                        httpRequest.statusText);
            }
            
        }
    }
    
    window.onload=function(){
        newsTitle();
    }
</script>
</head>
<body>
<div id="news"></div>
<input type="text">
</body>
</html>
cs


-newsTitleXML_ok.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 import="java.util.Date"%>
<%@ page contentType="text/xml; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<%!
    String[] newsTitle={
            "돈봉투·명품 넥타이 받은 김학의가 '전화해놨다' 했다",
            "'가난해?' 죽고싶게 묻고, 죽지 않을 만큼 준다",
            "경남FC '한국당 막무가내···징계 땐 책임져야'",
            "경찰 '승리 성접대 의혹 사실로 확인'",
            "검 '김성태 딸 부정채용' KT 전 전무 구속 기소",
            "법관들 '침묵' 역이용한 임종헌"
    };
 
%>
 
<result>
    <count><%=newsTitle.length %></count>
    <data>
        <%for(int i=0;i<newsTitle.length;i++){ %>
            <title><%=newsTitle[i]+" | "+new Date() %></title>
        <%%>
    </data>
</result>
cs


-실행화면


: 밑에 inputbox에 텍스트를 입력해놓아도 지워지지 않는것으로 보아 새로고침이 되지않는다.

그리고 위의 텍스트박스를 보면 setTimeout()함수를 통해 3초마다 호출이 되므로 3초마다 시간이 바뀌는 모습을 확인할 수 있다.




5. Javascript에서 클래스 사용 

-자바스크립트에서 클래스를 생성할 수 있다.

자바스크립트에서 클래스를 생성하는 다양한 방식을 예제로 살펴보자.


-member.js : 클래스 생성 역할

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Member 클래스
//얘는 생성자로 초기화해준 것과 같은것
Member =function(id,name,addr){
    this.id=id;
    this.name=name;
    this.addr=addr;
};
 
//클래스 안에 함수 정의(setter)
//얘는 메소드를 만들어서 setter로 초기화
Member.prototype.setValue=function(id,name,addr){
    this.id=id;
    this.name=name;
    this.addr=addr;
};
 
//클래스 안에 함수 정의(getter)
Member.prototype.getValue=function(){
    return "["+this.id+"]"+this.name+"("+this.addr+")";
};
cs

-log.js : console이라는 id를 가진 태그에 출력해주는 기능을 한다.

1
2
3
4
5
6
function log(msg){
    
    var consolE=document.getElementById("console");
    
    consolE.innerHTML+=msg+"<br/>";
}
cs


-memberClass.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/log.js"></script>
<script type="text/javascript" src="<%=cp%>/data/js/member.js"></script>
<script type="text/javascript">
    function memberClass(){
        //1.member.js없이 실행(메모리에 객체생성)
        var object1={};
        object1.id="suzi";
        object1.name="배수지";    
        log("log1: "+object1.id+", "+object1.name);
        
        //2.member.js없이 실행(메모리에 객체생성)
        var object2={};
        object2.id="zhihyo";
        object2.name="송지효";    
        log("log2: "+object2.id+", "+object2.name);
        
        //3.Member 클래스 객체 생성후 변수명으로 호출
        var member=new Member("songhee","천송이","강남");
        log("member1: "+member.id+", "+member.name+", "+member.addr);
        
        //4.setter로 초기화하고 변수로 호출
        member.setValue("hyolee","이효리","제주도");
        log("member2: "+member.id+", "+member.name+", "+member.addr);
        
        //5.getter로 호출
        var memberInfo=member.getValue();
        log("member.getValue(): "+memberInfo);
    }
    
    window.onload=function(){
        memberClass();
    }
</script>
</head>
<body>
<h1>Javascript 클래스 사용</h1>
<hr/>
 
<div id="console"></div>
</body>
</html>
cs


-실행화면



6. Javascript를 이용해 JSON형식으로 데이터받기 

-[], {}, ""를 이용해서 JSON형식에 맞게 데이터를 생성해주고

그 데이터를 자바스크립트에서 가져오는 예제이다.


-jsonUse.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #result{
        border:1px dotted #0000ff;
    }
    
    div{
        margin:auto;
        width:600px;
        height:100%;
    }
</style>
<script type="text/javascript">
    function useJson(){
        var userArray=[
           {
               userId:"suzi",
               name:"배수지",
               age:25,
               phone:[
                     {home:["031-111-1111","032-222-2222"]}, 
                     {office:["02-333-3333","051-444-4444"]}
                     ]
           },//배열0         
           {
               userId:"songhee",
               name:"천송이",
               age:38,
               phone:[{},{}]
           },//배열1     
           {
               userId:"zhihyo",
               name:"송지효",
               age:37,
               phone:[{},{}]
           }//배열2         
        ];
        
        //한개의 데이터 읽기
        var id=userArray[0].userId;//suzi
        var name=userArray[0].name;//배수지
        var age=userArray[0].age;//25
        var homePhone1=userArray[0].phone[0].home[0];//031-111-1111
        var homePhone2=userArray[0].phone[0].home[1];//032-222-2222
        var officePhone1=userArray[0].phone[1].office[0];
        
        var printData=id+", "+name+", "+age+"<br/>";
        printData+="userArray[0].phone[0].home[0]: "+homePhone1+"<br/>";
        printData+="userArray[0].phone[0].home[1]: "+homePhone2+"<br/>";
        printData+="userArray[0].phone[1].home[0]: "+officePhone1+"<br/>";
        
        var resultDiv=document.getElementById("result");
        resultDiv.innerHTML=printData;
        
    }
    
    window.onload=function(){
        useJson();
    }
</script>
</head>
<body>
<h1>JSON(Javascript Object Notation)</h1>
<hr/>
<div id="result"></div>
</body>
</html>
cs



-실행화면





1. JQuery 코드 링크  


<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

: 위의 링크를 head영역 안에 써주면 JQuery의 기능을 가져와 쓸 수 있게 된다.



2. JQuery 소스 받아오기


링크 : https://jqueryui.com/



이 페이지에서 왼쪽 탭에 원하는 기능을 선택하고

view source를 누르면 소스를 볼 수 있다.



3. JQuery 예제


-위의 페이지에서 소스를 받아와서 실행해보자!


-test5.jsp(탭 예제)

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

request.setCharacterEncoding("UTF-8");

String cp=request.getContextPath();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<script type="text/javascript">

$(function(){

$("#container").tabs();

})

</script>

</head>

<body>

<div id="container">

<ul>

<li><a href="#f1">첫번째</a></li>

<li><a href="#f2">두번째</a></li>

<li><a href="#f3">세번째</a></li>

</ul>

<div id="f1">

테스트1.............

</div>

<div id="f2">

테스트2.............

</div>

<div id="f3">

테스트3.............

</div>

</div>

</body>

</html>


-test5.jsp(탭 예제




1. 메일 전송 


메일 보낼 때 프로토콜 : SMTP(Simple Mail Transfer Protocol)

메일 받을 때 프로토콜 2가지 : POP, IMAP


1) POP 방식 : MOVE의 개념

- 로컬 장치에 이메일을 내려받으면 서버에서는 이메일을 삭제.

- 데이터의 용량은 줄일 수 있지만, 중요한 문서가 있을 경우 삭제될 위험이 있는 단점이 있다.


2) IMAP 방식 : COPY의 개념(서버와 클라이언트가 동기화)

- 메일서버와 클라이언트의 메일함이 동기화되어 문서가 삭제될 위험 가능성은 낮다.

- 하지만 메일서버의 용량이 다 찼을 경우 메일이 오지못하고 reject되는 경우가 있어 용량을 많이 차지한다는 단점이 있다.




2. 메일 기능 구현 setting 


1) 메일서버세팅


① james-2.3.2.zip파일 다운

링크 : http://james.apache.org/ - james-2.3.2 파일을 다운 받는다.

- 기본 java 폴더에 풀어놓음(폴더경로에 한글이 있으면 안된다)


② javamail-1.4.3.zip파일 다운

링크 : https://www.oracle.com/technetwork/java/index-138643.html

-mail.jar 

-이클립스 lib에 추가


③ jaf-1_1_1.zip파일 다운

링크 : https://www.oracle.com/technetwork/java/jaf11-139815.html

-activation.jar : 파일첨부기능

-이클립스 lib에 추가


-추가한 화면


그리고 james 파일가서 /bin/run.bat 파일 시작해주면 서버가 스타트된다.



2) rub.bat를 실행해서 서버 실행

: 4555는 서버의 서비스번호



3) cmd telnet을 이용해 메일서버 잘 작동하는지 확인(확인작업이기 때문에 생략 가능)

: 제어판의 프로그램 기능가서 windows 기능 사용/사용안함 클릭 후, 맨 아래에 텔넷 클라이언트 클릭해준다.


-cmd

: 서버의 서비스번호인 4555

cmd에 'telnet localhost 4555' 입력하면

위와 같은 창이 뜨고 root/root로 로그인해서 들어가면 메일서버가 잘 동작하고 있는 걸 확인할 수 있다.




3. 메일 기능 이클립스에 구현 


-mailSend.jsp : 사용자에게 메일을 보낼 정보를 받을 페이지


-MailSend.java : 메일(파일과 같이) 보내는 기능 구현


-mailSend_ok.jsp : mailSend.jsp의 정보를 받아서 MailSend.java의 클래스를 불러와 실질적으로 여기서 메일 전송처리해줌! 


-MailSend.java의 일부


-mailSend_ok.jsp


-실행화면


-'접속하기' 버튼 누르면 아래 이미지처럼 메일전송 완료!


-메일이 파일과 함께 도착했다!


-지정한 폴더에 파일도 저장된 것을 확인 할수 있다.




-코드 압축 파일





+ Recent posts