2021.01.18 일지 - Spring

117515 단어 SpringSpring

스프링 처음 시작하기

  1. 가지고 있던 3.9.11 버전을 압축을 풀어준 뒤 STS.exe를 실행시켜준다. 실행시켜준 뒤 workspace명은 하단과 같이 설정해준다.
  2. 스프링이 모두 설치되고 켜지면 File>New>Spring Legacy Project를 눌러 프로젝트를 새로 생성해준다.
  3. 프로젝트명은 Sp01로 해주고 박스 쳐진 곳을 클릭하고 Next를 눌러준다. 새창이 뜨는데 Proceed? Yes 클릭
  4. 패키지명 적어주는 란이 나오는데 depth를 3번째까지 들어가야 돼서 우선 컨트롤러만 만들어주게 peachy.ct.controller로 명명
  5. 만들어진 모습, 처음에는 X자가 뜨는데 그건 스프링에 필요한 것들이 다운되기 전이라서 그렇다. 다운로드가 다 되고 나면 X자가 없어진다.
  6. pom.xml에서 일부 버전을 바꿔줘야 할 것들이 몇가지 있다. 자바 버전과 스프링 버전을 바꿔준다.

    AS-IS

    TO-BE

  7. 디펜던시들도 몇 가지 넣어준다. 디펜던시 넣어줄 때 위치는 별로 상관없고, <dependencies></dependencies> 사이에만 들어가면 된다.

servlet

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

jUnit

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

log4j

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

최종 pom.xml

<?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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>peachy.ct</groupId>
	<artifactId>controller</artifactId>
	<name>Sp01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- <dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency> -->

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<!-- <dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency> -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<!-- <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency> -->
		<dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <version>4.12</version>
		</dependency>
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  1. JRE에도 javaw.exe가 있고 JDK에도 javaw.exe가 있는데, 제대로 인식시켜주게 하기 위해서 STS.ini 파일을 연다.
  2. 그런 뒤, 하단 이미지처럼 경로를 지정해준다.
  3. 이제 인코딩을 변경해줄 건데, Window>Preferences>General>Workspace에 가서 박스쳐준 곳처럼 바꿔준다.
  4. CSS, HTML, JSP파일도 마찬가지로 바꿔주면 된다.
  5. HomeController를 IndexController로 이름을 변경한다. 그러고 하단 내용으로 바꿔치기한다.
package peachy.ct.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController {
	
	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index() {
		return "index";
	}
}
  1. view에 있는 index도 바꿔준다. 그러니까 src>main>webapp>WEB-INF>views에 있는 home.jsp도 index.jsp로 바꿔주고, 하단 내용으로 바꿔준다.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Sp01 Index</title>
	</head>
	<body>
		<div style="text-align:center;">
			<h1>Sp01 Index</h1>
		</div>
	</body>
</html>
  1. 서버에서 pivotal 서버에 커서를 대고 우클릭 한 뒤 New를 눌러줘 Tomcat 서버를 새로 만들어준다.
  2. 그러고 pivotal 서버는 delete 눌러준다.
  3. Tomcat 서버를 더블클릭 해주면 Overview, Modules가 뜨는데 Modules에서 Path를 /controller에서 /로 변경
  4. 127.0.0.1:8080에서 index 뜨는 거 확인 후에 새로운 클래스인 SampleController 생성, 하단 내용 복사 붙여넣기
package peachy.ct.controller;

import java.util.ArrayList;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;

@Controller
@RequestMapping("/sample/*")
public class SampleController {
   @RequestMapping("")
   public void m01() {
      System.out.println("m01 - default URL");
   }
   @RequestMapping("/base1")
   public void m02() {
	   System.out.println("m02 - Get / Post / ...");
   }
   @RequestMapping(value = "/base2", method = RequestMethod.GET)
   public void m03() {
	   System.out.println("m03 - Only Get");
   }
   @RequestMapping(value = "/base3", method = {RequestMethod.GET, RequestMethod.POST})
   public void m04() {
	   System.out.println("m04 - Get / Post");
   }
   @RequestMapping(value = "/form", method = RequestMethod.GET)
   public String form() {
      return "sample/form";
   }
}


18. index.jsp도 링크를 연결해준다.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Sp01 Index</title>
	</head>
	<body>
		<div style="text-align:center;">
			<h1>Sp01 Index</h1>
			<p>
				<a href="sample/">m01</a>
				<a href="sample/base1">m02</a>
				<a href="sample/base2">m03</a>
				<a href="sample/base3">m04</a>
				<a href="sample/form">form</a>
			</p>
		</div>
	</body>
</html>
  1. form.jsp 하단처럼 만들어놓고 method 변경해가면서 테스트 해보면 끝!
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Sp01 Index</title>
	</head>
	<body>
		<div style="text-align:center;"><form action="base3" method="post">
				<input type="submit" value="전송" />
			</form>
		</div>
	</body>
</html>

스프링 활용하기

  1. getter/setter를 자동으로 만들어주는 lombok 라이브러리를 사용해보겠다. 자료실에 들어가서 java -jar lombok.jar 명령어를 실행시켜준다.
  2. 실행시켜주면 하단과 같은 창이 뜨는데 specify location 연 뒤 STS.exe와 연결시켜준다.
  3. 인스톨 성공하면 quit 클릭
  4. lombok을 다 깔아줬으면 pom.xml에 롬복 관련 디펜던시를 추가해준다. 이제 package를 만들어 줄 차례다. src/main/javapeachy.ct.domain으로 생성해준다.
       <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.6</version>
			<scope>provided</scope>
		</dependency>
  1. 그 안에 Human이란 클래스를 만들어준다. 하단 내용 복사 붙여넣기 해준다.
package peachy.ct.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Human {
	private String name;
	private int age;
}
  1. 또 다른 클래스, HumanList도 만들어준다. 하단 내용 복사 붙여넣기 해준다.
package peachy.ct.domain;

import java.util.ArrayList;
import lombok.Data;

@Data
public class HumanList {
	private ArrayList<Human> list;
}
  1. 그 안에 ToDoDTO란 클래스도 만들어준다. 하단 내용 복사 붙여넣기 해준다.
package peachy.ct.domain;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import lombok.Data;

@Data
public class ToDoDTO {
	private String subject;
	
	@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm:ss")
	private Date cdate;
}
  1. SampleController도 번갈아가며 수정해주어야 한다.
package peachy.ct.controller;

import java.util.ArrayList;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;

import lombok.extern.log4j.Log4j;
import peachy.ct.domain.Human;
import peachy.ct.domain.HumanList;
import peachy.ct.domain.ToDoDTO;

@Controller
@RequestMapping("/sample/*")
@Log4j
public class SampleController {
   @RequestMapping("")
   public void m01() {
      log.info("m01 - default URL");
   }
   @RequestMapping("/base1")
   public void m02() {
      log.info("m02 - Get / Post / ...");
   }
   @RequestMapping(value = "/base2", method = RequestMethod.GET)
   public void m03() {
      log.info("m03 - Only Get");
   }
   @RequestMapping(value = "/base3", method = {RequestMethod.GET, RequestMethod.POST})
   public void m04() {
      log.info("m04 - Get / Post");
   }
   @RequestMapping(value = "/form", method = RequestMethod.GET)
   public String form() {
      return "sample/form";
   }
   @RequestMapping("/param1")
   public void m05(Human board) {
	   log.info("m05() dto: " + board);
   }
   @RequestMapping("/param2")
   public void m06(@RequestParam String name, @RequestParam int age) {
	   log.info("m06() name: " + name + ", age:" + age);
   }
   @RequestMapping("/param3")
   public void m07(@RequestParam ArrayList<String> names) {
	   log.info("m07() names:" + names);
   }
   @RequestMapping("/param4")
   public void m08(@RequestParam("ns") ArrayList<String> names) {
	   log.info("m08() names:" + names);
   }
   @RequestMapping("/param5")
   public void m09(@RequestParam String[] names){
	  log.info("m09() names: " + names);
	  for(String name: names) log.info("name: " + name);
   }
   @RequestMapping("/param6")
   public void m10(HumanList hlist) {
	  log.info("m10() hlist: " + hlist);
   }
   @RequestMapping("/param7")
   public void m11(Human dto, @RequestParam int page) {
	  log.info("m11() dto:" + dto + ", page:" + page);
   }
   @RequestMapping("/param8")
   public void m12(ToDoDTO dto)  {
	  log.info("m12() dto.getCdate(): " + dto.getCdate());
   }
   @RequestMapping(value="/json1", method=RequestMethod.GET)
   @GetMapping("/json1")
   public ResponseEntity<String> m13() {
	   String msg = "{\"name:\":\"임연지\", \"age\":25}";
	   HttpHeaders headers = new HttpHeaders();
	   headers.add("Content-Type", "application/json;charset=utf-8");
	   
	   return new ResponseEntity<String>(msg, headers, HttpStatus.OK);
   }
   @GetMapping("/json2")
   public @ResponseBody Human m14() { // *****
	   return new Human("박영후", 31);
   }
}
  1. index.jsp에서 데이터 넘기는 것을 확인할 수 있다.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Sp01 Index</title>
	</head>
	<body>
		<div style="text-align:center;">
			<h1>Sp01 Index</h1>
			<p>
				<a href="sample/">m01</a>
				<a href="sample/base1">m02</a>
				<a href="sample/base2">m03</a>
				<a href="sample/base3">m04</a>
				<a href="sample/form">form</a>
			</p>
			<p>
				<a href="sample/param1?name=홍길동&age=24">m05</a>
				<a href="sample/param2?name=이순신&age=27">m06</a>
				<a href="sample/param3?names=김좌진&names=유관순&names=강감찬">m07</a>
				<a href="sample/param4?ns=김좌진&ns=유관순&ns=강감찬">m08</a>
				<a href="sample/param5?names=김좌진2&names=유관순2&names=강감찬2">m09</a>
			</p>
			<p>
				<a href="sample/param6?list%5B0%5D.name=이순신&list%5B0%5D.age=27&list%5B1%5D.name=홍길동&list%5B1%5D.age=24">m10</a>
				<a href="sample/param7?name=홍길동&age=24&page=10">m11</a>
				<a href="sample/param8?subject=데이트&cdate=2021/01/18 17:05:30">m12</a>
			</p>
			<p>
				<a href="sample/json1">m13</a>
				<a href="sample/json2">m14</a>
			</p>
		</div>
	</body>
</html>
  1. 복사 붙여넣기 한 것들을 사용하려면 pom.xml에 디펜던시들을 추가해줘야 오류가 나지 않는다.

lombok 관련 디펜던시

	    <dependency>
	        <groupId>org.springframework</groupId>
	        <artifactId>spring-test</artifactId>
	        <version>${org.springframework-version}</version>
	    </dependency>
	    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
	    <dependency>
	        <groupId>org.projectlombok</groupId>
	        <artifactId>lombok</artifactId>
	        <version>1.18.6</version>
	        <scope>provided</scope>
	    </dependency>

ResponseBody 관련 디펜던시

	    <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

index.jsp 최상단에서 에러뜰 때

  1. 프로젝트에 대고 마우스 우클릭 후 Properties 클릭
  2. Project Facets>Java>Apache Tomcat v9.0에 클릭하면 끝

좋은 웹페이지 즐겨찾기