com.example.demo.config 패키지를 만든 뒤 아래와 같이 CacheConfig 클래스를 작성해줍니다.
package com.example.demo.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.cache.Cache;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;
import java.util.concurrent.TimeUnit;
@EnableCaching
@Configuration
public class CacheConfig {
private final CachingProvider cachingProvider = Caching.getCachingProvider();
private final javax.cache.CacheManager cacheManager = cachingProvider.getCacheManager();
@Bean
public CacheManager cacheManager() {
return new JCacheCacheManager(cacheManager);
}
@Bean
public Cache<Integer, Integer> commonCache() {
MutableConfiguration<Integer, Integer> configuration =
new MutableConfiguration<Integer, Integer>()
.setTypes(Integer.class, Integer.class)
.setStoreByValue(false)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 5)));
return cacheManager.createCache("commonCache", configuration);
}
}
위 내용을 간략히 살펴보면 cacheManager 빈을 하나 등록해주고 그 캐시매니저에 commonCache라는 이름의 캐시 빈을 하나 등록해주는 겁니다. 이 commonCache가 key, value 페어를 저장하는 하나의 서랍이라고 생각하시면되고요. 여기서는 키와 값의 타입이 모두 Integer 이고 만료정책은 생성시간을 기준으로 5초로 설정해주었습니다.
4. API 구현 및 테스트
이제 commonCache에 값을 저장하고 만료되기 전까지 캐시의 데이터를 사용하도록 서비스 클래스를 하나 만들어주겠습니다.
package com.example.demo.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CacheService {
@Cacheable(cacheNames = "commonCache", cacheManager = "cacheManager", key = "#code")
public Integer getCachedValue(int code) {
System.out.println("계산중....");
// DB 조회 등의 로직...
return (int) (Math.random() * 10);
}
}
com.example.demo.service 패키지를 만들고 CacheService 클래스를 작성했습니다.
getCachedValue 메서드에 @Cacheable 어노테이션을 붙여주고 commonCache를 사용하고 cacheManager는 CacheConfig에 등록했던 cacheManager 이름을 적어주었습니다. 그리고 key로 파라미터로 전달받는 code 값을 사용하겠다고 선언해주었습니다. 만약 key로 어떤 객체의 멤버변수를 사용해야한다면 key = "#obj.employeeId" 와 같이 사용가능합니다. (공식문서 참고)
CacheService.getCachedValue 가 호출되면 code 값을 key로하여 return된 Integer 값을 commonCache에 저장하게되고 만료시간인 5초 이내에 동일한 key값(여기서는 code 파라미터 값)으로 메서드 호출이 발생할 경우 메서드 내부의 비즈니스 로직을 타지않고 바로 캐시에 저장되어있는 값을 반환합니다. 이를 확인하기위해 계산중.... 메시지를 출력하도록 했습니다.
TaskExecutorConfig 클래스를 만들고 @Configuration 어노테이션을 추가하여 설정을 위한 클래스를 하나 만들었습니다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class TaskExecutorConfig {
@Bean(name = "executor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("my-");
return executor;
}
}
그리고 executor() 메서드를 하나 만들어서 ThreadPoolTaskExecutor를 생성하여 반환해주도록 하고 @Bean으로 등록하면서 name 속성을 지정해주었습니다. 참고로 name 속성의 값은 메서드명과 달라고 무관합니다. 또한, 해당 executor를 이용하여 쓰레드를 실행시켰을 때 내가 만든 ThreadPoolTaskExecutor가 사용되는 것인지 확인할 수 있도록 쓰레드명prefix를 "my-"로 세팅해주었습니다.
이전 포스팅을 읽어보셨거나 또는 ThreadPoolTaskExecutor를 직업 new 키워드로 생성해서 사용해보신 분은 눈치채셨을 수도 있을텐데요, 여기서 initialize()를 하지 않았습니다. 공식문서에는 initialize 메서드를 호출하는 것으로 나와있지만 굳이 하지 않아도 빈으로 등록될 때 initialize를 하더군요.
@Autowired 로 ThreadPoolTaskExecutor 사용하기
아래는 빈으로 등록한 executor를 서비스 레이어에서 autowired하여 사용하는 예제입니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class TestService {
@Autowired
@Qualifier("executor")
private ThreadPoolTaskExecutor executor;
public void executeThreads() {
log.info("executing threads....");
Runnable r = () -> {
try {
log.info(Thread.currentThread().getName() + ", Now sleeping 10 seconds...");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 10; i++) {
executor.execute(r);
}
}
}
TestService라는 서비스 클래스에서 멤버변수 executor에 위에서 빈으로 등록한 객체를 쓰도록 @Qualifier로 executor 이름을 명시해주었습니다.
위 코드를 실행해보면 쓰레드 명이 my-1 로 출력되는 것을 확인하실 수 있습니다. corePoolSize를 default 값인 1 로 사용하여 싱글 쓰레드로 실행되기 때문에 my-2, my-3은 보이지 않습니다. corePoolSize 를 2 이상으로 세팅해주면 my-2, my-3 등의 쓰레드도 확인가능합니다.
2021-01-26 18:16:23.147 INFO 16390 --- [ my-1] com.keichee.test.service.TestService : my-1, Now sleeping 10 seconds...
2021-01-26 18:16:33.150 INFO 16390 --- [ my-1] com.keichee.test.service.TestService : my-1, Now sleeping 10 seconds...
2021-01-26 18:16:43.152 INFO 16390 --- [ my-1] com.keichee.test.service.TestService : my-1, Now sleeping 10 seconds...
2021-01-26 18:16:53.157 INFO 16390 --- [ my-1] com.keichee.test.service.TestService : my-1, Now sleeping 10 seconds...
@Async로 ThreadPoolTaskExecutor 사용하기
@Async 어노테이션을 이용하여 위에서 빈으로 등록한 ThreadPoolTaskExecutor를 사용하려면 @EnableAsync 도 추가해주어야 합니다.
따라서 TaskExecutorConfig 클래스에 @EnableAsync 어노테이션을 추가해줍니다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@EnableAsync
@Configuration
public class TaskExecutorConfig {
@Bean(name = "executor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("my-");
return executor;
}
}
그리고 서비스 레이어의 메서드를 하나 추가하겠습니다.
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class TestService {
@Async("executor")
public void task() {
try {
log.info(Thread.currentThread().getName() + ", Now sleeping 10 seconds...");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
이제 controller 쪽에서 task() 메서드를 loop 돌면서 호출해보면 @Autowired 를 이용한 방법과 동일하게 로그가 출력되는 것을 확인하실 수 있을 겁니다.
이상으로 SpringBoot에서 ThreadPoolTaskExecutor 설정하여 사용하는 방법에 대해서 알아보았습니다.
간략하게 다시 정리해보자면
1. @Configuration 으로 등록한 클래스에 executor @Bean 추가 (@Async 를 이용할 경우 @EnableAsync 도 추가)
2. @Autowired @Qualifier 로 주입하여 사용하거나 또는 메서드 레벨에 @Async 를 붙여 사용
정말 간단한 연락처 관리 프로그램이므로 이름과 연락처 정보만 담을 예정이고 개인정보 암호화 같은건 다루지 않습니다.
입력받은 정보 그대로 string으로 저장을 하도록 하겠습니다.
이렇게 테이블 설계가 완료되면 이제 백엔드에서 쿼리해올 수 있도록 구현을 들어가보겠습니다.
백엔드 개발
우선 새로운 프로젝트를 만들어야겠죠.
아래 순서대로 새로운 프로젝트를 만들어 줍니다.
Project Explorer > New > Project 선택
Wizards에서 spring으로 검색한 뒤 Spring Starter Prject 선택 (이게 안나온다면 STS설치하기부터 하고 오시면 됩니다.)
Name 항목은 프로젝트명을 입력하는 곳입니다.
여기에 contact-manager 라고 넣어주시고 Java Version은 8 이상으로 아무거나 쓰셔도 무방할겁니다.
여기서는 Java 11 버전을 사용하였습니다.
Next를 눌러 다음으로 넘어간 뒤 Available 검색창에서 spring web, lombok, mybatis, mysql를 검색하여 우측의 selected 항목에 세 개 항목이 들어가도록 체크하고 Finish 버튼을 클릭합니다. 저는 이미 사용한 적이 있어서 Frequently Used에 항목이 나타나서 체크만 해주었습니다. 처음 하시는 분들은 Available에서 검색하시면 됩니다.
우측 하단에 progress bar가 진행되는 것을 확인할 수 있습니다.
또는 Progress View에서 확인할 수도 있죠. Progress View가 안보인다면 이클립스 상단 메뉴에서 Window > Show View > Other > Progress로 검색하면 추가할 수 있습니다.
우선 위에서 만든 contact 테이블의 내용을 조회해오는 API를 만들어 보도록 하겠습니다.
com.example.demo 패키지 하위에 domain 라는 이름의 패키지를 만들고 해당 패키지에 ContactInfo.java 파일을 생성해줍니다.
그리고 아래와 같은 내용을 넣어줍니다.
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ContactInfo {
private String name;
private String phone;
}
ContactInfo 클래스는 contact 테이블과 연동할 dto입니다.
com.example.demo 패키지 하위에 mapper 라는 이름의 패키지를 만들고 해당 패키지에 ContactInfoMapper.java 파일을 생성해줍니다. ContactInfoMapper는 클래스가 아닌 인터페이스로 생성해주고 아래와 같이 쿼리문을 작성해줍니다.
import com.example.demo.domain.ContactInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ContactInfoMapper {
@Select("select * from contact")
List<ContactInfo> selectAll();
@Insert("insert into contact (name, phone) values (#{name}, #{phone})")
int insert(ContactInfo contactInfo);
@Delete("delete from contact where name = #{name}")
int delete(String name);
@Select("<script>" +
"select * from contact " +
"<where>" +
"<if test=\"name != null and name.length > 0\">and name = #{name}</if>" +
"<if test=\"phone != null and phone.length > 0\">and phone = #{phone}</if>" +
"</where>" +
"</script>")
List<ContactInfo> selectBy(@Param("name") String name, @Param("phone") String phone);
@Update("update contact " +
"set phone = #{phone} " +
"where name = #{name}")
int update(String name, String phone);
}
이 ContactInfoMapper 인터페이스는 마이바티스와 연동이 되어 쿼리를 database로 전달하고 결과를 받아오는 역할을 합니다.
com.example.demo 패키지 하위에 service 라는 이름의 패키지를 만들고 해당 패키지에 ContactInfoService.java 파일을 생성해줍니다.
이 파일에는 아래와 같이 내용을 넣어주시면 됩니다.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.domain.ContactInfo;
import com.example.demo.mapper.ContactInfoMapper;
@Service
public class ContactInfoService {
@Autowired
private ContactInfoMapper contactInfoMapper;
public List<ContactInfo> getEveryContactInfo() {
return contactInfoMapper.selectAll();
}
public int addContactInfo(ContactInfo contactInfo) {
return contactInfoMapper.insert(contactInfo);
}
public int delContactInfo(String name) {
return contactInfoMapper.delete(name);
}
public List<ContactInfo> getContactInfos(String name, String phone) {
return contactInfoMapper.selectBy(name, phone);
}
public int updateContactInfo(String name, String phone) {
return contactInfoMapper.update(name, phone);
}
}
ContactInfoMapper의 메서드를 호출하는 역할만 하고 있지만 프로젝트가 복잡해지면 각종 비즈니스 로직이 들어가야할 클래스입니다.
조회한 뒤에 정렬을 한다든지, 필터링을 한다든지 하는 로직은 이 서비스 클래스에 넣어주시면 됩니다.
이제 controller쪽에서 사용할 응답 도메인 클래스를 하나 더 만들어 보겠습니다.
com.example.demo.domain 패키지에 Response.java 파일을 생성하고 아래와 같이 작성해줍니다.
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonInclude(Include.NON_NULL)
public class Response<T> {
private int code;
private String message;
private T data;
public Response(int code, String message) {
this.code = code;
this.message = message;
}
public Response(int code, String message, T data) {
this(code, message);
this.data = data;
}
}
마지막으로 com.example.demo 패키지 하위에 controller 라는 이름의 패키지를 만들고 해당 패키지에 ContactInfoController.java 파일을 생성해서 아래 내용을 넣어주세요.
import com.example.demo.domain.ContactInfo;
import com.example.demo.domain.Response;
import com.example.demo.service.ContactInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/contact-info")
public class ContactInfoController {
@Autowired
private ContactInfoService contactInfoService;
@GetMapping("/list") // --> localhost:8080/contact-info/list
public List<ContactInfo> getAllContactInfo() {
return contactInfoService.getEveryContactInfo();
}
@GetMapping("/get")
public ResponseEntity<Response> getContactInfos(
@RequestParam(required = false) String name,
@RequestParam(required = false) String phone) {
List<ContactInfo> result = contactInfoService.getContactInfos(name, phone);
if (result.size() == 0) {
return ResponseEntity.status(HttpStatus.OK).body(new Response(204, "데이터 없음"));
}
return ResponseEntity.ok(new Response(200, "조회 성공", result));
}
@PostMapping("/add")
public ResponseEntity<Response> addNewContactInfo(@RequestBody ContactInfo contactInfo) {
contactInfoService.addContactInfo(contactInfo);
return ResponseEntity.ok(new Response(200, "등록 성공"));
}
@DeleteMapping("/del")
public ResponseEntity<Response> delContactInfo(@RequestParam String name) {
int result = contactInfoService.delContactInfo(name);
if (result == 0) {
return ResponseEntity.status(HttpStatus.OK).body(new Response(204, "데이터 없음"));
}
return ResponseEntity.ok(new Response(200, "삭제 성공"));
}
@PutMapping("/update")
public ResponseEntity<Response> updateContactInfo(@RequestParam String name, @RequestParam String phone) {
int result = contactInfoService.updateContactInfo(name, phone);
if (result == 0) {
return ResponseEntity.status(HttpStatus.OK).body(new Response(204, "데이터 없음"));
}
return ResponseEntity.ok(new Response(200, "수정 성공"));
}
@ExceptionHandler
public ResponseEntity<Response> contactInfoErrorHandler(Exception e) {
log.error("error!!, {}", e.getClass().getName(), e);
if (e instanceof DuplicateKeyException) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(new Response(409, "이미 중복된 이름이 등록되어있습니다."));
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new Response(500, "서버오류가 발생하였습니다."));
}
}
}
이 클래스가 프론트와 백엔드를 연결해주는 부분으로 API url을 정의하고 어떤 파라미터들을 전달받아야 하는지, 응답은 어떻게 주고 예외처리는 어떻게 하는지에 대한 내용이 담겨있죠.
이제 백엔드 구현은 완료되었습니다. 아 참!! 하나 빼먹은게 있네요. database 접속 정보를 빼먹었습니다. 자, src/main/resources 하위의 application.properties 파일을 열어서 직접 생성하셨던 database 접속 정보를 아래처럼 넣어주세요.
접속 포트(8889)와 database명(javastudy) 그리고 username, password 정보를 생성하신 데이터베이스에 맞게 변경해주셔야 합니다.
여기까지 완료되었다면 Project Explorer에 아래와 같이 파일들이 존재해야 합니다.
이제 ContactManagerApplication을 Sppring Boot App으로 기동해서 API가 잘 동작하는지 확인을 해보도록 하겠습니다.
앱 기동에 성공하면 Console View에서 아래 로그를 확인 할 수 있습니다.
INFO 69998 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
INFO 69998 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
INFO 69998 --- [main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
INFO 69998 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
INFO 69998 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1185 ms
INFO 69998 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
INFO 69998 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
INFO 69998 --- [main] c.e.demo.ContactManagerApplication : Started ContactManagerApplication in 2.457 seconds (JVM running for 3.521)
그리고 controller 패키지 내에 ViewController.java 파일을 만들어서 아래와 같이 짧은 코드를 작성해주겠습니다.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@GetMapping("/contact-info")
public String contactInfo() {
return "contact-info"; // contact-info.html을 화면에 보여주는 역할
}
}
그리고 src/main/resources 하위의 templates 디렉토리에 contact-info.html 파일을 하나 생성하고 아래 내용을 넣어주세요.
오늘은 backend 보다는 frontend 작업을 위한 Bootstrap 추가를 webjar를 이용할 수 있도록 설정해보도록 할 예정입니다.
저는 backend 개발자다보니 front쪽은 자세히 알려드리기는 힘들지만 빠르게 서치해서 사용해본 경험상 webjar는 maven 의존성 관리를 통해 라이브러리를 다운받아 사용할 수 있어 매우 쉽게 라이브러리 추가가 가능합니다. org.webjars에는 bootstrap, jquery, font-awesome, swagger-ui 뿐만 아니라 angularJS, momentJS, d3js 등 매우 많은 프론트 개발을 위한 라이브러리들을 제공하고 있습니다. 매번 다운로드받아서 프로젝트에 추가할 필요 없이 백엔드 라이브러리들을 관리하듯이 메이븐 의존성으로 쉽게 관리할 수 있도록 도와주는 역할을 한다고 보시면 됩니다.
webjar 설정을 위해서 추가할 파일은 딱 하나입니다. org.springframework.web.servlet.config.annotation.WebMvcConfigurer를 구현하는 WebMVCConfig 클래스를 하나 생성하고 다음과 같이 addResourceHandlers 메서드를 오버라이드하여 작성해줍니다.
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
new String[] {"classpath:/static/script", "classpath:/static/style"});
}
}
우선 webjars 경로를 등록해주는 것 때문에 이 클래스를 만들어 사용하는데 이때 @EnableWebMvc 어노테이션을 사용하게 됩니다. 그런데 여기서 주의할 점이 이 어노테이션을 사용하게되면 WebMvcAutoConfiguration 이 disable되면서 기존 설정들이 정상적으로 동작하지 않게 됩니다. 따라서 기존에 잘 읽어오던 static하위의 javascript파일들과 css파일들을 못찾아 404 오류가 발생하게 되죠. 그래서 addResourceHandlers에 이 두 파일들이 존재하는 디렉토리를 classpath경로로 추가해줘야 합니다.
또한, application.properties 파일에 작성하였던 아래 두 라인은 더이상 사용하지 않고 방금 추가한 WebMVCConfig 클래스에 별도로 ViewResolver를 등록하여 사용해야합니다.
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
아래는 완성된 WebMVCConfig 클래스의 코드입니다.
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
new String[] {"classpath:/static/script", "classpath:/static/style"});
}
}
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
자, 모든 준비는 완료가 되었습니다. 이제 pom.xml에 다음과 같이 부트스트랩 의존성을 추가해줍니다.
이제 새로운 프로젝트를 생성합니다. 현재 이클립스를 처음 설치하신 분이라면 패키지 탐색기(Project Explorer)에 아래와 같이 나오는데 여기서 밑에서 두 번째에 있는 Create a project...를 선택합니다. 만약 이미 프로젝트를 만들어 놓은게 있는 분들이라면 그냥 탐색기 창에서 우클릭해서 New > Project 를 선택하시면 됩니다.
아래와 같이 새 프로젝트 생성 마법사가 뜨면 spring 으로 검색을 해서 Spring Starter Project를 선택합니다.
이제 만들 프로젝트의 이름을 Name 항목에 적어줍니다. 그리고 Java Version 은 11로 선택해줍니다. (8로 해도 무방합니다)
Spring Boot의 버전을 선택할 수 있는데 이 부분은 그대로 놔두고 Available 검색창에서 web이라고 검색하여 Spring Web을 선택해줍니다. (이외에도 lombok이나 데이터 베이스 드라이버, MyBatis 등 유용한 기능들을 선택하여 사전설치가 가능합니다만 여기서는 선택하지 않습니다.)
그리고 pom.xml 파일에 아래 의존성을 추가해줍니다. jasper는 JSP 파일을 컴파일 해주는 기능을 합니다.
<!-- Need this to compile JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
이제 프로젝트명에서 우클릭하고 "src/main/webapp" 새 폴더를 하나 만듭니다. 이렇게 폴더를 만들면 아래와 같이 생성됩니다.
이제 다시 우클릭하여 build path 설정(Configure Buildpath...)화면으로 들어갑니다.
Add Folder... 를 클릭하고 webapp 디렉토리를 찾아 체크해줍니다.
OK 버튼을 누르고 Apply하면 프로젝트 구조가 아래와 같이 바뀐것을 확인할 수 있습니다.
이제 webapp 아래에 WEB-INF디렉토리를 생성하고 하위에 또 views 라는 디렉토리를 생성합니다. 그리고 test.jsp 파일을 만들어 아래와 같이 작성해줍니다.
자, 이제 마지막으로 해당 페이지와 연결할 API를 작성합니다. root package에서 controller 라는 패키지를 하나 만들고 그 아래에 DemoController.java를 아래와 같이 작성합니다.
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("/test")
public String login() {
return "/test";
}
}
여기까지 완료되었으면 이제 Run As > Java Application 또는 Run As > Spring Boot App 으로 기동시켜줍니다.
그리고 localhost:8080/test 에 접속하면 아래와 같이 jsp 페이지가 뜨는 것을 확인할 수 있습니다.
JSP 페이지에 javascript 및 css 파일 연동
이제 JSP 페이지에 javascript 파일 및 css 파일을 연결시켜보겠습니다.
javascript와 css 파일은 src/main/resources 하위의 static 폴더 안쪽에 몰아넣어주면 됩니다.
우선 static 폴더 하위에 script 폴더를 만들어 test.js파일을 생성하고 아래 내용을 작성합니다.
$(document).ready(function() { printCurrentDatetime(); });
function printCurrentDatetime() {
let date = new Date();
$('#currentTime').html(date);
setTimeout(printCurrentDatetime, 1000);
}
그리고 static 폴더 하위에 style 폴더를 만들어 test.css 파일을 생성하고 아래와 같이 작성합니다.
@charset "UTF-8";
body {background-color:cornflowerblue;}
자, 더이상 파일을 만들 필요는 없습니다. 마지막으로 JSP 파일에 위에서 작성한 두 파일을 연결시켜주겠습니다.