Theme. Spring Boot를 DB와 연결하기 위한 설정

 

< 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
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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sample3-db</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample3-db</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.1</version>
        </dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId> <!-- Spring Boot 버전과 동일하게 맞춰줄 것 -->
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

 

 

< application.properties >

 

1
2
3
4
5
6
7
8
 
server.port=3000
 
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:포트넘버/DB명?serverTimeZone=Asia/Seoul
spring.datasource.hikari.username=아이디
spring.datasource.hikari.password=비밀번호
 
cs

 

< DB Config >

 

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 mul.cam.a;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
 
@Configuration
@PropertySource("classpath:/application.properties")
public class DatabaseConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public HikariConfig hikariConfig() {
        return new HikariConfig();
    }
    
    @Bean
    public DataSource dataSource() {
        DataSource dataSource = new HikariDataSource(hikariConfig());
        System.out.println("dataSource: " + dataSource);
        
        return dataSource;
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        System.out.println("DatabaseConfig sqlSessionFactory");
        
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        
        Resource[] arrResource = new PathMatchingResourcePatternResolver().getResources("classpath:sqls/*.xml");
        sqlSessionFactoryBean.setMapperLocations(arrResource);
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        
        return (SqlSessionFactory)sqlSessionFactoryBean.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSession(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    
}
 
cs

 

 

간단한 예시로 Member.xml - MemberDao - MemberService - MemberController 순으로 연결을 간단하게 살펴보자.

사용되는 MemberDto는 아래와 같다.

 

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
package mul.cam.a.dto;
 
public class MemberDto {
    
    private String id;
    private String pwd;
    private String name;
    private String email;
    private int auth;
    
    public MemberDto() {
    }
 
    public MemberDto(String id, String pwd, String name, String email, int auth) {
        super();
        this.id = id;
        this.pwd = pwd;
        this.name = name;
        this.email = email;
        this.auth = auth;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public int getAuth() {
        return auth;
    }
 
    public void setAuth(int auth) {
        this.auth = auth;
    }
 
    @Override
    public String toString() {
        return "MemberDto [id=" + id + ", pwd=" + pwd + ", name=" + name + ", email=" + email + ", auth=" + auth + "]";
    }
    
 
}
 
cs

 

 

< Member.xml >

주의할 것은 mapper의 namespace에 패키지명도 함께 적어야한다는 것이고, sql문 부분의 id값이 dao에서의 함수명으로 동일하게 사용된다는 것이다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
<mapper namespace="mul.cam.a.dao.MemberDao"> <!-- mapper에 패키지명도 적어야! -->
 
<select id="allMember" resultType="mul.cam.a.dto.MemberDto">
    select id, pwd, name, email, auth
    from member
</select>
 
</mapper>
 
 
 
 
cs

 

 

< MemberDao.java >

MemberDao.java는 인터페이스이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mul.cam.a.dao;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
 
import mul.cam.a.dto.MemberDto;
 
@Mapper    // Member.xml의 id값이 그대로 함수명이 된다.
@Repository
public interface MemberDao {
    
    // 함수명은 반드시 Member.xml의 해당 id값과 동일해야 한다
    List<MemberDto> allMember();
    
}
 
cs

 

 

< MemberService.java >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package mul.cam.a.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import mul.cam.a.dao.MemberDao;
import mul.cam.a.dto.MemberDto;
 
@Service
@Transactional
public class MemberService {
 
    @Autowired
    MemberDao dao;
    
    public List<MemberDto> allMember(){ // dao와 함수명이 꼭 같을 필요는 없다.
        return dao.allMember();
    }
}
 
cs

 

< MemberController.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 mul.cam.a.controller;
 
import java.util.Date;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import mul.cam.a.dto.MemberDto;
import mul.cam.a.service.MemberService;
 
@RestController
public class MemberController {
    
    @Autowired
    MemberService service;
    
    @GetMapping(value = "/allList")
    public List<MemberDto> allList(){
        System.out.println("MemberController allList " + new Date());
        
        return service.allMember();
    }
}
 
cs

 

 

끝.

 

 

'Spring' 카테고리의 다른 글

[Spring Boot] File 업로드 및 다운로드  (0) 2023.03.26
[Spring Boot] 스프링 부트 실행 및 기초  (0) 2023.03.26

Theme. 파일 업로드 및 다운로드

 

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
package mul.cam.a.controller;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import mul.cam.a.MediaTypeUtiles;
import mul.cam.a.dto.HumanDto;
 
@RestController
public class HelloController {
 
    // file upload
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public String fileUpload(HumanDto human,
                             @RequestParam("uploadFile")
                             MultipartFile uploadFile,
                             HttpServletRequest req) {
        
        System.out.println("HelloController fileUpload " + new Date());
        System.out.println(human.toString());
        
        // 경로
        String path = req.getServletContext().getRealPath("/upload"); // 서버에 업로드
//        String path = "c:\temp"; // 폴더에 upload
        
        
        String filename = uploadFile.getOriginalFilename(); // 기본 파일명
        String filepath = path + "/" + filename;
        
        System.out.println(filepath);
        
        File file = new File(filepath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(uploadFile.getBytes());
            bos.close();
        
        } catch (Exception e) {
            return "file upload fail";
        } 
        return "file upload success";
        
    }
    
    // file download
    @Autowired
    ServletContext servletContext;
    
    @RequestMapping(value = "/fileDownload")
    public ResponseEntity<InputStreamResource> download(String filename, HttpServletRequest req) throws Exception{
        System.out.println("HelloController download " + new Date());
        
        // 경로
        String path = req.getServletContext().getRealPath("/upload");
        
        MediaType mediaType = MediaTypeUtiles.getMediaTypeForFileName(this.servletContext, filename);
        System.out.println("filename: " + filename);
        System.out.println("mediaType: " + mediaType);
        
        File file = new File(path + "/" + filename); // filename은 업로드됐을 때의 new filename
//        File file = new File(path + File.separator + filename);
        
        InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
        
        // db에서 다운로드 카운트 넣으려면 이 곳에 넣음
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) // file.getName()은 원본 파일명
                .contentType(mediaType)
                .contentLength(file.length())
                .body(isr);
    }
    
    
    
    
}
 
cs

 

이때 사용된 static 메서드는 아래 클래스에 나타내었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package mul.cam.a;
 
import org.springframework.http.MediaType;
 
import jakarta.servlet.ServletContext;
 
public class MediaTypeUtiles {
 
    public static MediaType getMediaTypeForFileName(ServletContext servletContext, String filename) {
        
        String minType = servletContext.getMimeType(filename);
        
        try {
            MediaType mediaType = MediaType.parseMediaType(minType);
            return mediaType;
        } catch (Exception e) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
        
        
    }
}
 
cs

 

이때, 주의할 것은 프로젝트에 upload 폴더를 추가해줘야 한다는 것이다.

아래와 같이 main 폴더 하위에 webapp 폴더를 생성하고, 그 안에 upload 폴더를 생성해주도록 하자.

 

 

또한, HumanDto 클래스의 경우에는 다음과 같다.

 

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
package mul.cam.a.dto;
 
public class HumanDto {
    
    private int number;
    private String name;
    private String address;
    
    public HumanDto() {}
 
    public HumanDto(int number, String name, String address) {
        super();
        this.number = number;
        this.name = name;
        this.address = address;
    }
 
    public int getNumber() {
        return number;
    }
 
    public void setNumber(int number) {
        this.number = number;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    @Override
    public String toString() {
        return "HumanDto [number=" + number + ", name=" + name + ", address=" + address + "]";
    }
    
    
}
 
cs

 

이제 html 파일을 만들어서 파일 업로드 및 다운로드를 실행해보자. 

abc.txt라는 파일을 업로드 및 다운로드한다. 

 

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
 
<h3>file upload</h3>
 
<p id="fileResult">...</p>
 
<form id="uploadFileForm">
    number:<input type="text" name="number" value="1002"><br>
    name:<input type="text" name="name" value="성춘향"><br>
    address:<input type="text" name="address" value="남원시"><br><br>    
    
    file:<input type="file" name="uploadFile"><br><br> <!-- controller에서 requestparam 부분 uploadFile과 이름 맞췄다. -->
    
    <button type="button" id="uploadBtn">파일업로드</button>    
</form>
 
<script type="text/javascript">
$(document).ready(function(){
    $("#uploadBtn").click(function(){
        
        $.ajax({
            url:"http://localhost:3000/fileUpload",
            type:"post",
            data:new FormData($("#uploadFileForm")[0]),
            enctype:'multipart/form-data',
            processData:false,
            contentType:false,
            cache:false,
            success:function(str){
                alert('success');
                $("#fileResult").text(str);
            },
            error:function(){
                alert('error');
            }
        });        
    });
});
</script>
 
<br><br>
 
<h3>file download</h3>
 
<button type="button" id="downloadBtn">파일 다운로드</button>
 
<script type="text/javascript">
 
$("#downloadBtn").click(function(){
    
    location.href = "http://localhost:3000/fileDownload?filename=" + "abc.txt";
    
    /* 
    아래 코드는 success는 나오지만, 다운로드는 실행되지 않을 것이다.
    즉, 아래와 같이 다운로드 하면 안된다. 
    
    $.ajax({
        url:"http://localhost:3000/fileDownload",
        type:"get",
        data:{ filename:"abc.txt" },
        success:function(){
            alert('success');    
        },
        error:function(){
            alert('error');
        }        
    });
    */
});
 
</script>
 
</body>
</html>
 
 
 
 
 
 
 
 
 
 
cs

 

 

실행 결과는,

 

 

 

 

 

 

 

 

끝.

 

 

'Spring' 카테고리의 다른 글

[Spring Boot] DB와 연결하기  (0) 2023.03.26
[Spring Boot] 스프링 부트 실행 및 기초  (0) 2023.03.26

Theme. 프로젝트 생성과 기본 세팅(Spring Tool Suite 4 사용)

 

File - New - spring starter project 선택

 

 

Name에 프로젝트 name 작성 - Maven으로 진행

 

 

Spring Boot Version 선택

 

이미 생성했던 sample1이라는 프로젝트를 통해 설명을 진행하도록 한다.

제일 먼저 pom.xml에서 <dependency>를 세팅해줘야 한다.

내장 tomcat을 사용할 것이므로 아래와 같이 추가해줘야 한다. 중간중간 version에 대한 부분은 새로 만들때마다 바뀌게 될 것이다.

 

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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sample1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample1</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 추가된 부분 start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!-- 추가된 부분 end -->
        
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

 

프로젝트에는 main 메서드가 포함된 클래스가 존재한다.

서버를 실행할 때, 항상 해당 클래스에서 실행하고, 코드의 변경이 있으면 항상 서버를 껐다가 켜서 사용하는 것을 주의하자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package mul.cam.a;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class Sample1Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Sample1Application.class, args);
    }
 
}
 
cs

 

그리고 @Configuration이라는 annotation을 붙이고 WebMvcConfigurer를 상속하여 사용할 클래스를 생성해준다.

해당 클래스는 클라이언트의 접속을 허가해주는 부분을 설정하는 클래스이다.

 

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 mul.cam.a;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
// 외부 접속을 허용해주도록 설정!
 
@Configuration    // 설정
public class WebConfigurer implements WebMvcConfigurer{
 
    @Override // 외부접속에 대한 허가를 해주는 부분
    public void addCorsMappings(CorsRegistry registry) {
        
        // 접속 클라이언트를 허가
        registry.addMapping("/**").allowedOrigins("*"); // 모든 접속을 허가
//        registry.addMapping("/**").allowedOrigins("http://localhost:8090"); // 특정 접속을 허가 
        
        
    }
 
    
    
}
 
cs

 

그리고, src/main/resources 안에 application.properties가 존재하는데, 이 부분에서 server의 port number를 세팅할 수 있다.

 

 

임의로 3000으로 port number를 세팅하여 사용하도록 한다.

server.port=3000 이라고 작성하면 된다.

 

Theme. front-end 부분 만들기 전 back-end에서만의 실행 및 결과

 

이제 Controller를 만들어서 진행해보도록 한다.

아직, front-end부분을 만들지 않았으므로 결과를 확인하기 위해서는,

http://localhost:3000/매핑 value..... 를 입력하여 확인하도록 한다. (크롬 사용)

중간에 HumanDto 클래스 타입의 객체를 생성하여 사용하는 부분이 있는데, 해당 클래스의 코드는 아래와 같다.

 

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
package mul.cam.a.dto;
 
public class HumanDto {
    
    private int number;
    private String name;
    private String address;
    
    public HumanDto() {}
 
    public HumanDto(int number, String name, String address) {
        super();
        this.number = number;
        this.name = name;
        this.address = address;
    }
 
    public int getNumber() {
        return number;
    }
 
    public void setNumber(int number) {
        this.number = number;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    @Override
    public String toString() {
        return "HumanDto [number=" + number + ", name=" + name + ", address=" + address + "]";
    }
    
    
}
 
cs

 

자 이제 HelloController.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
package mul.cam.a.controller;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import mul.cam.a.dto.HumanDto;
 
@RestController 
// MVC model에서의 @Controller(controller부분) + @Responsebody(ajax부분)
public class HelloController {
 
    /////////////// 서버(back-end)에서 값을 보내주기만 하는 부분 ////////////////////////
    // http://localhost:3000/
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String hello() {
        System.out.println("HelloController hello() " + new Date());
        
        return "hello"// ajax를 통해 값을 front-end로 보내준다.
    }
    
    // http://localhost:3000/test
    @GetMapping(value = "/test")
    public String test() {
        System.out.println("HelloController test() " + new Date());
        
        return "테스트";
    }
    
    // http://localhost:3000/human
    @GetMapping(value = "/human")
    public HumanDto getDto() {
        System.out.println("HelloController getDto() " + new Date());
        
        HumanDto human = new HumanDto(1001"홍길동""서울시");
        
        return human;
    }
    
    // http://localhost:3000/get_list
    @GetMapping("/get_list")
    public List<HumanDto> get_list(){
        System.out.println("HelloController get_list() " + new Date());
 
        List<HumanDto> list = new ArrayList<>();
        list.add(new HumanDto(101"홍길동""서울시"));
        list.add(new HumanDto(102"성춘향""남원시"));
        list.add(new HumanDto(103"임꺽정""광주시"));
        
        return list;
    }
    
////////////////// 외부에서 데이터를 서버로 보낸 경우, 서버에서 매개변수로 받는 것 /////////////////////
    // 예를 들어, http://localhost:3000/conn_param?title=제목입니다
    @GetMapping(value = "/conn_param")
    public String conn_param(String title) {
        System.out.println("HelloController conn_param() " + new Date());
 
        System.out.println("title: " + title);
        
        return "conn success";
    }
    
    // http://localhost:3000/param_obj?number=1002&name=성춘향&address=남원시
    @GetMapping(value = "param_obj")
    public String param_obj(HumanDto human) {
        System.out.println("HelloController param_obj() " + new Date());
 
        System.out.println("human: " + human);
        
        return "OK";
    }
    
    
    
    
}
 
cs

 

http://localhost:3000/

 

http://localhost:3000/test

 

 

HumanDto 객체를 보내준 결과는 json 형태로 나타나는데, 위와 같이 깔끔하게 보기 위해서는 "JSON VIEWER"를 크롬에 추가했다.

 

 

 

console에도 아래와 같이 "제목입니다"라는 값을 받았음을 알 수 있다.

 

 

 

 

console에도 아래와 같이 값들을 받았음을 알 수 있다.

 

 

 

 

Theme. front-end 부분 만들어서 실행 및 결과 확인

 

eclipse를 이용하여 html 파일들을 만들어 진행하도록 한다. ajax를 활용했다.

1. index.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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button" id="btn">hello</button>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("#btn").click(function(){
        
        $.ajax({
            url:"http://localhost:3000/test",
            type:"get",
            success:function(str){
//                 alert('success');
                $("#demo").text(str); // 서버(Spring Boot)에서 넘겨받은 str의 값이 p태그 안에 들어오게 됨
            
            },
            error:function(){
                alert('error');
            }
        });
        
    });
});
</script>
 
<br><br>
 
번호:<h3 id="num"></h3>
이름:<h3 id="name"></h3>
주소:<h3 id="address"></h3>
 
<button type="button" id="human">human</button>
 
<script type="text/javascript">
$("#human").click(function(){
    
    $.ajax({
        url:"http://localhost:3000/human",
        type:"get",
        success:function(obj){
            // alert('success');
            // alert(JSON.stringify(obj));
            $("#num").text(obj.number); // json이므로!
            $("#name").text(obj.name);
            $("#address").text(obj.address);
        },
        error:function(){
            alert('error');
        }        
    });
    
});
</script>
 
<br><br>
 
<h3 id="param"></h3>
 
<button type="button" id="paramBtn">conn param</button>
 
<script type="text/javascript">
$("#paramBtn").click(function(){
    
    $.ajax({
        url:"http://localhost:3000/conn_param",
        type:"get",
        data:{ "title":"제목입니다" }, // server로 보내는 data
        success:function(str){
            $("#param").text(str);
        },
        error:function(){
            alert('error');
        }
    })
    
});
</script>
 
<br><br>
 
번호:<h3 id="num1"></h3>
이름:<h3 id="name1"></h3>
주소:<h3 id="address1"></h3>
 
<button type="button" id="list">list</button>
 
<script type="text/javascript">
$("#list").click(function(){
    
    $.ajax({
        url:"http://localhost:3000/get_list",
        type:"get",
        success:function(obj){
//             alert('success');
//             alert(JSON.stringify(obj));
            $("#num1").text(obj[1].number); // 102
            $("#name1").text(obj[1].name); // 성춘향
            $("#address1").text(obj[1].address); // 남원시
        },
        error:function(){
            alert('error');
        }        
    });
    
});
</script>
 
 
</body>
</html>
 
 
 
 
 
 
cs

 

index.html의 실행 결과는 다음과 같다.

 

 

각 버튼을 누르게 되면,

 

 

STS에서 console 결과를 확인해보면, 중간에 서버로 값을 넘겨준 것이 확인된다. ("제목입니다" 보내준 부분)

 

 

만약, ajax를 활용하지 않고 사용한다면,

 

2. default.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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button" onclick="btnclick()">hello</button>
 
<script type="text/javascript">
function btnclick(){
    
    let xhttp = new XMLHttpRequest();
    
    xhttp.onreadystatechange = function(){
        if(xhttp.readyState == 4 && xhttp.status == 200){
//             document.getElementById("demo").innerText = xhttp.responseText;
 
            // xhttp.responseText는 문자열이므로 json으로 바꿔줘야 함            
            let json = JSON.parse(xhttp.responseText); // json 파싱
            document.getElementById("demo").innerText = json.name;
        }
    }
    
    xhttp.open("get""http://localhost:3000/human"true);
    xhttp.send();
}
 
</script>
 
 
</body>
</html>
cs

 

 

 

 

끝.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Spring' 카테고리의 다른 글

[Spring Boot] DB와 연결하기  (0) 2023.03.26
[Spring Boot] File 업로드 및 다운로드  (0) 2023.03.26

+ Recent posts