728x90
728x90
자바기반 앱개발 & 웹서비스 구축 개발자
애플리케이션 테스트 수행

수업이 끝나면서 각 과목 별 시험 쳤던 문제들을 복습 겸 정리해보겠습니다.
첫 번째 글은 제일 처음 수업을 들었던 순서대로 자바 과목 문제가 되겠네요. 

 

 

 

 

 


 

[애플리케이션테스트수행하기]

1. 아래 클래스를 컴파일하고 실행하여 결과를 출력하고자 한다. 

class Hello{
	public static void main(String[] args){
    	System.out.println("Java World");
        }
}

1) 컴파일 실행문 :  javac Hello.java

2) 실행 명령문 :  java Hello

3) 실행결과 :  Java World

 

2. 위 코드의 파일명을 적으시오.

Hello.java

 

[ 3~5 ] 다음 클래스에 대해 물음에 답하시오.

class A {
	private int a;
	public void setA(int a){ this.a = a; }
    }
class B extends A {
	protected int b, c;
}
class C extends B {
	public int d, e;
}

 

3. A obj A = new A(); 에 의해 생성되는 객체 objA의 멤버들을 모두 나열하라.

2개
private int a;

public void setA( int a ) { this.a=a; }

4. B obj B = new B(); 에 의해 생성되는 객체 objB의 멤버들을 모두 나열하라.

4개
private int a;
public void setA( int a ) { this.a=a; }
protected int b, c;

5. C obj C = new C(); 에 의해 생성되는 객체 objB의 멤버들을 모두 나열하라.

6개
private int a;
public void setA( int a ) { this.a=a; }
public int d, e;

 

6. 자바의 모든 클래스가 반드시 상속받게 되어있는 클래스는?    1

1) Object   2) Java   3) Class   4) Super

 

7. 다음 중 설명에 적절한 단어를 기입하라.

자바에서 상속받는 클래스를 (  sub class   ) 라고 부르며, extends 키워드를 이용하여 상속을 선언한다. 상속받은 클래스에서 상속해준 부모 클래스의 멤버를 접근할 때  (  super  ) 키워드를 이용한다. 한편 자바의 클래스는 객체를 만들 수 없는 추상클래스와 인터페이스가 있다. 인터페이스는 자바 클래스와 달리 (  다중상속  ) 을 할 수 있으며 (  implements  ) 키워드를 이용하여 인터페이스를 구현한 클래스를 작성한다.

 

[애플리케이션결함조치하기]

8. 다음 코드에서 생성자로 인한 오류를 찾아내어 이유를 설명하고 오류를 수정하라.

class A {
	private int a;
    protected A(int a) { this.a = a; }
}
class B extends A {
	private int b;
    protected B() { b = 0; }
}

 

해설 >> 클래스 A의 생성자를 protected로 사용해도 무관하므로 다음은 오류가 아니다. 

protected A (int a) { this.a=a; }

잘못된 부분은 클래스 B의 다음 생성자에 있다. 
class A 에서 디폴트 생성자를 선언하거나 class B의 생성자에서 super(b)를 선언해야 한다.

protected B () { b=0; }

 

 

9. 추상 클래스를 구현하는 문제이다. 실행 결과와 같이 출력되도록 클래스 B를 완성하라.

abstract class OddDetector {
	protected int n;
	public OddDetector (int n) {
    	this.n = n;
	}
	public abstract boolean isOdd(); //홀수이면 true 리턴
}
public class B extends OddDetector {
	public B(int n) { 
    	super(n);
	}
	public static void main (String[] args) {
    	B b = new B(10);
    	System.out.println(b.isOdd()); //B가 짝수이므로 false 출력
	}
}
실행결과 : false

 

해설 >> 클래스 B에서 isOdd() 메소드 오버라이딩 한다.

public boolean isOdd() { //isOdd() 메소드 오버라이딩
	return(n%2 !=0) ? true : false;

또는

public boolean isOdd() {    //isOdd() 메소드 오버라이딩
	if(n%2 !=0) return true
	else return false;
}

 

 

10. 다음 코드의 실행 결과 "반지름=10"이 출력되도록 Circle 클래스를 수정하라.

Circle c = new Circle(10);
c.paint();

답 >> 

class Circle {
	private int radius;
	public Circle(int radius) {
		this.radius = radius;
        }
        public void paint(){
		System.out.printlnt("반지름 = " + radius);
	}
}

 

 

[애플리케이션테스트수행하기]

[ 11~12 ] JUnit에서는 Annotation을 사용하면 제어가 쉬워진다. 다음 설명하는 애노테이션을 적으시오.

11-1. @BeforeClass 단위 테스트 안의 모든 메소드 실행 전에 단 한번만 수행
11-2. @AfterClass 단위 테스트 안의 모든 메소드 실행이 된 후 마지막에 단 한번만 수행
12-1. @Before  단위 테스트 안의 각 메소드가 실행될 때마다 실행 전에 수행
12-2. @After 단위 테스트 안의 각 메소드가 실행될 때마다 실행 후에 수행

 

 

[ 13~15 ] 다음은 JUnit을 이용한 테스트 코드이다. 물음에 답하시오.

public class CalculatorTest {
       1)      @Test         
       public void testSum( ) {

               // fail("Not yet implemented");
               Calculator cal = new Calculator();
                2)         assertEquals       (30, cal.sum(20,10));
                System.out.println("test1");
       }
       1)     @Test           
       public void testSum1( ){
               // fail("Not yet implemented");
               Calculator cal = new Calculator();
                2)          assertEquals        (60, cal.sum(50,10));
                System.out.println("test2");

       }
      @BeforeClass
       public static void beforeTest( ) {
               System.out.println("BeforeClass");
       }
      @AfterClass
       public static void afterTest( ) {
               System.out.println("AfterClass");
       }
      @Before
       public static void setUp( ) {
               System.out.println("Before setUp");
       }
      @After
       public static void tearDown( ) {
               System.out.println("after tearDown");
       }

}

13. 위 코드는 jnuit을 이용한 테스트 수행 코드이다. 1번에 들어갈 애노테이션을 적으시오

@Test

 

14. 위 코드는 두 수의 합을 구하는 sum( ) 메소드를 테스트 하는 코드이다. 2에 들어갈 메소드를 적으시오.
이 메소드는 두 수의 합의 결과가 같은 지를 확인한다.

assertEquals

 

15. 위 코드를 실행했을 때 출력되는 출력문을 순서대로 적으시오.

BeforeClass
Before setUp
test1
after tearDown
Before setUp
test2
after tearDown
AfterClass

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

오라클 DB 연결을 위한 준비 : BuildPath, Deployment Assembly에 ojdbc6.jar 추가

 

 

 

커넥트풀 설정

 

 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="url" value="jdbc:oracle:thin:@192.168.0.78:1521:xe"></property>
			<property name="username" value="mvc"></property>
			<property name="password" value="1234"></property>
		</bean>
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<!-- 설정파일 -->
			<!-- <property name="configLocation" value="classpath:/mybatis-config.xml"></property> -->		
		</bean>
</beans>

 

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>5.1.9.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.7.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</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>com.lje</groupId>
	<artifactId>boardex02</artifactId>
	<name>SpringMVCBoard02</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.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.17</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>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.12</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.8</version>
			<scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.2</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.8</source>
					<target>1.8</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>

 

 

JDBCTest.java

package com.lje.boardex02.persistence;

import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;

import lombok.extern.log4j.Log4j;


@Log4j
public class JDBCTest {
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testConnect() {
		try(Connection con = DriverManager.getConnection(
					"jdbc:oracle:thin:@192.168.0.78:1521:XE",
					"mvc",
					"1234")){
						log.info("con: "+con);
					
		}catch(Exception e) {
			fail(e.getMessage());
		}
	}
}

 

 

MybatisTest.java

package com.lje.boardex02.persistence;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class MybatisTest {
	@Inject
	private SqlSessionFactory sqlFactory;
	@Test
	public void testFactory() {
		log.info(sqlFactory);
	}
	@Test
	public void testSession() throws Exception{
		try(SqlSession session = sqlFactory.openSession()) {
			log.info(session);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

JUnit은 단위 테스트 도구

 외부 테스트 프로그램(케이스)을 작성하여 System.out으로 번거롭게 디버깅하지 않아도 됨
 프로그램 테스트 시 걸릴 시간도 관리할 수 있게 해주며 오픈 소스이며, 플러그인 형태로 Eclipse에 포함되어 있음.
 하나의 jar 파일로 구성 사용법 간단
 JUnit은 보이지 않고 숨겨진 단위 테스트를 끌어내어 정형화시켜 단위 테스트를 쉽게 해주 는 테스트용 Framework
 JDK 1.4에서 추가된 assertXXX를 사용하여 Test를 진행
 JUnit은 테스트 결과를 확인하는 것 이외 최적화된 코드를 유추해내는 기능도 제공
 테스트 결과를 단순한 텍스트로 남기는 것이 아니라 Test클래스로 남김
 개발자에게 테스트 방법 및 클래스의 History를 넘겨줄 수도 있음.

 

JUnit의 특징

1. 단위 테스트 Framework 중 하나
2. 문자 혹은 GUI 기반으로 실행됨 
3. 단정문으로 테스트 케이스의 수행 결과를 판별함(assertEquals(예상 값, 실제 값))
4. 어노테이션으로 간결하게 지원함
5. 결과는 성공(녹색), 실패(붉은색) 중 하나로 표시

 

Eclipse - JUnit 설정

1. Java Project를 생성 후 Project 이름에서 오른쪽 마우스를 클릭하고 Properties를 선택
2. Java BuildPath를 선택
3. Libraries 탭을 선택하고, Add Library를 선택
4. JUnit을 선택하고, Next 버튼 선택
5. 버전을 선택하고, Finish 버튼 선택
6. JUnit이 추가 된 사항을 확인

 

 

JUNIT 실행 방법

* 그림처럼 실행하거나 단위실행 가능하다.

 

 

com.calculator 패키지, Calculator 클래스 작성

 

Calculator.java

package com.calculator;

public class Calculator {
	public int sum(int num1, int num2) {
		return num1+num2;
	}
	public int mul(int num1, int num2) {
		return num1*num2;
	}
	
	
}

 

 

CalculatorTest.java

package com.calculator.test;

import static org.junit.Assert.*;

import org.junit.Test;

import com.calculator.Calculator;

public class CalculatorTest {
	Calculator calculator = new Calculator();
	
	@Test
	public void testSum() {
		assertEquals(30,  calculator.sum(10,20));
	}
	public void testMul() {
		assertEquals(100,  calculator.mul(10,10));
	}
}

 

대표적인 단정문

assertArrayEquals(a,b) : 배열 a와b가 일치함을 확인 
assertEquals(a,b) : 객체 a와b의 값이 같은지 확인 
assertSame(a,b) : 객체 a와b가 같은 객체임을 확인 
assertTrue(a) : a가 참인지 확인 
assertNotNull(a) : a객체가 null이 아님을 확인

 상세내용 링크 : http://junit.sourceforge.net/javadoc/org/junit/Assert.html

 

어노테이션 활용

1) 테스트 메소드 지정
@Test
public void testSum() {
}
2) 테스트 메소드 수행시간 제한하기
@Test(timeout=5000) //밀리초
public void testSum() {
}
3) 테스트 메소드 Exception 지정하기
@Test(expected=RuntimeException.class)
public void testSum() {
}
4) 초기화 및 해제
@BeforeClass, @AfterClass
- 메소드 위에 선언되면 해당 테스트 클래스는 한번만 수행

@BeforeClass
public static void setupBeforClass() throws Exception{
}
@AfterClass
public static void tearDownAfterClass() throws Exception{
}
@Before, @After가 메소드 위에 선언되면 해당 테스트 클래스 안에 메
소드들이 테스트 되기 전과 후에 각각 실행되게 지정하는 어노테이션
@Before
public void setUp() throws Exception{
}
@After
public void tearDown() throws Exception{
}

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

1. 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>com.lje</groupId>
	<artifactId>boardex02</artifactId>
	<name>SpringMVCBoard02</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>5.1.9.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.17</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>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.12</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.8</version>
			<scope>provided</scope>
		</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.9</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</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>

 

수정할 것

Spring Context

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.9.RELEASE</version>
    <scope>test</scope>
</dependency>

 

 

lombok : setter, getter를 만들어주는 repository

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
    <scope>provided</scope>
</dependency>

 

 

2. DTO

 

자동으로 getter setter가 안된다면 아래 홈페이지에 들어가서 jar를 받은 후 sts폴더 아래 넣어준다.

 

Download

 

projectlombok.org

 

 

 

 

메모장으로 확인해 봤을 때 잘 들어가있으면 된 것이다. Maven > Update 로 새로고침 후  작업을 계속한다.

-startup
plugins/org.eclipse.equinox.launcher_1.5.400.v20190515-0925.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.1000.v20190125-2016
-product
org.springsource.sts.ide
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.8
--add-modules=ALL-SYSTEM
-Xms40m
-Dosgi.module.lock.timeout=10
-Dorg.eclipse.swt.browser.IEVersion=10001
-Xmx1200m
-javaagent:C:\sts-bundle\sts-3.9.9.RELEASE\lombok.jar

 

어노테이션 사용방법

@Component
@data

@Getter
@Setter

//생성자
@AllArgConstructor

..public class Person{
	private String name;
    private int age;
    private String gender;
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

선수학습 내용

 

Spring MVC 패턴 스프링 게시판 만들기

이번에는 Spring MVC 패턴을 이용하여 게시판을 만들어보도록 하겠습니다. 우선 로직과 파일의 폴더 구성은 아래와 같습니다. 작업 순서도 1. DB작성 2. 프로젝트 생성 3. pom.xml, web.xml 수정 1. 테이블, 시..

coding-restaurant.tistory.com

 


 

Mybatis란?

 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크
 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해 줌
 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해
XML과 애노테이션을 사 용할 수 있음

 

스프링 + MyBatis 연동 설정

1. 필수 라이브러리

• MyBatis 라이브러리 • mybatis-spring 라이브러리 • MySQL JDBC 드라이버

• 개발 전 테스트

• MySQL의 연결 테스트 • Spring 프로젝트의 SqlSessionFactory 연결 테스트

 


 

 

 

XML

(server) context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <!-- driver, xe 수정 : 서버에 이부분을 뺀다 -->
     	 <!-- <Resource name="jdbc/myoracleDB" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/> -->
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

context.xml

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <!-- driver, xe 수정 -->
     	 <!-- <Resource name="jdbc/myoracleDB" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/> -->
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

web.xml

...더보기
<?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">

	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>

	</filter>

	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

 

 

라이브러리 추가

 

 

Pom.xml 수정

mybatis 저는 신버전을 붙였습니다.

 

 

mybatis-spring도 붙입니다.

 

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>com.lje</groupId>
	<artifactId>springboard</artifactId>
	<name>SpringMVCBoard01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.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>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- 단위 Test를 하기 위한 junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.2</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.8</source>
					<target>1.8</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>

 

servlet-context.xml

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.lje.springboard" />
	
	
	
</beans:beans>

 

root-context.xml

...더보기
<?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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="url" value="jdbc:oracle:thin:@192.168.0.78:1521:xe"></property>
			<property name="username" value="mvc"></property>
			<property name="password" value="1234"></property>
		</bean>
		
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<!-- 설정파일 -->
			<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
			<!-- 파일위치.name에 s주의. resources 밑에 mappers라는 폴더를 생성, 그 아래 모두 -->
			<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml"></property>
		</bean>
		<!-- 실제 DB 사용 시 이것만 부른다 -->
		<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
		</bean>
		<!-- <bean id="dao" class="com.lje.spring.dao.BDao" /> 이거 일일히 쓰는 대신 아래 한줄로 끝!-->
		<context:component-scan base-package="com.lje.springboard"></context:component-scan>
</beans>

 

코드 완성 후 해야 할 작업이 있다. 
root-context.xml에 Namespaces 탭을 클릭, context 부분의 체크박스에 체크한다.

 

*오라클이 아닌 mySQL을 사용할 때는?

<?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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<!-- 오라클DB -->
		<!-- 
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="url" value="jdbc:oracle:thin:@192.168.0.78:1521:xe"></property>
			<property name="username" value="mvc"></property>
			<property name="password" value="1234"></property>
		</bean>
		 -->
		 <!-- mySQLDB 6.0 이상 -->
		<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
			<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
			<property name="url" value="jdbc:mysql://127.0.0.1:3306/mvcdb?useSSL=false&amp;serverTimezone=Asia/Seoul" />
			<property name="username" value="mvc" />
			<property name="password" value="1234" />
		</bean> -->
		
		 <!-- mySQLDB 5.0 ver -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
			<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
			<property name="url" value="jdbc:mysql://127.0.0.1:3306/mvcdb" />
			<property name="username" value="mvc" />
			<property name="password" value="1234" />
		</bean>
		 
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<!-- 설정파일 -->
			<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
			<!-- 파일위치.name에 s주의. resources 밑에 mappers라는 폴더를 생성, 그 아래 모두 -->
			<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml"></property>
		</bean>
		<!-- 실제 DB 사용 시 이것만 부른다 -->
		<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
		</bean>
		<!-- <bean id="dao" class="com.lje.spring.dao.BDao" /> 이거 일일히 쓰는 대신 아래 한줄로 끝!-->
		<context:component-scan base-package="com.lje.springboard"></context:component-scan>
</beans>

  

 

아까 선언한 파일이름들에 해당하는 xml파일들을 만들어준다.

 

 

BoardMapper.xml : DAO 의 역할을 대신 한다.

MyBatis 홈페이지 > 시작 부분에서 매핑된 SQL 구문 살펴보기 아래의 코드를 복사해온다.

 

 

MyBatis – 마이바티스 3 | 시작하기

XML에서 SqlSessionFactory 빌드하기 모든 마이바티스 애플리케이션은 SqlSessionFactory 인스턴스를 사용한다. SqlSessionFactory인스턴스는 SqlSessionFactoryBuilder를 사용하여 만들수 있다. SqlSessionFactoryBuilder는 XML설정파일에서 SqlSessionFactory인스턴스를 빌드할 수 있다. XML파일에서 SqlSessionFactory인스턴스를 빌드하는 것은 매우 간단한다. 설

www.mybatis.org

<?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="com.lje.boardex.BoardMapper">
  <select id="selectAll" resultType="Board">
    select * from mvc_board
  </select>
  <!-- com.lje.spring.dto.Board.이런식으로 다 적어야하나 mybatis-config.xml에서 코드를 적어주면 생략도 가능하다 -->
  <select id="selectOne" resultType="Board">
  	select * from mvc_board where bno=#{bno}
  </select>
  <!-- #을 쓰면 정수는 정수열, 문자는 문자열로, $는 String -->
  <insert id="create">
  	insert into mvc_board(bno, write, title, content)
  	values(mvc_board_seq.nextval, #{writer}, #{title}, #{content})
  </insert>
  <!-- insert, update는 리턴타입 없다. select만 --> 
  <update id="modify">
  	update mvc_board set writer=#{writer}, title=#{title}, content=#{content}
  	where bno=#{bno}
  </update>
  <delete id="remove">
  	delete from mvc_board where bno=#{bno}
  </delete>
  <update id="hitUpdate">
  	update mvc_board set hit=hit+1 where bno=#{bno}
  </update>
</mapper>
...더보기

mysql 사용 시 BoardMapper.xml

<?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="com.lje.boardex.BoardMapper">
  <select id="selectAll" resultType="Board">
    select * from mvc_board
  </select>
  <!-- com.lje.spring.dto.Board.이런식으로 다 적어야하나 mybatis-config.xml에서 코드를 적어주면 생략도 가능하다 -->
  <select id="selectOne" resultType="Board">
  	select * from mvc_board where bno=#{bno}
  </select>
  <!-- #을 쓰면 정수는 정수열, 문자는 문자열로, $는 String -->
  <insert id="create">
  	insert into mvc_board(write, title, content)
  	values(#{writer}, #{title}, #{content})
  </insert>
  <!-- insert, update는 리턴타입 없다. select만 --> 
  <update id="modify">
  	update mvc_board set writer=#{writer}, title=#{title}, content=#{content}
  	where bno=#{bno}
  </update>
  <delete id="remove">
  	delete from mvc_board where bno=#{bno}
  </delete>
  <update id="hitUpdate">
  	update mvc_board set hit=hit+1 where bno=#{bno}
  </update>
</mapper>

 


mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<typeAliases>
		<package name = "com.lje.springboard.dto" />
		<!-- 여따 적으면 BoardMapper.xml의 mapper 태그에서 생략 가능하다. -->
	</typeAliases>
</configuration>

 

 

DAO

IDao.java (1)DAO 폴더에 Interface를 생성 (2)Class 생성

 

IDao.java

...더보기
package com.lje.springboard.dao;

import java.util.List;

import com.lje.springboard.dto.Board;

public interface IDao {
	public void create(Board board) throws Exception;
	//try-catch가 없기에 여기서는 예외를 DAO에서 써줘야함
	
	public List<Board> listAll() throws Exception;
	public Board read(int bno) throws Exception;
	public void update (Board board) throws Exception;
	public void delete (int bno) throws Exception;
	public void hitUpdate (int bno) throws Exception;
	
}

 

BDao.java

...더보기
package com.lje.springboard.dao;

import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.lje.springboard.dto.Board;

//root-context.xml에서 정의한 sqlSession를 사용할 것임
@Repository
public class BDao implements IDao {
	
	//어노테이션은 오토와이어드나 Inject를 쓸 수 있다
	@Inject
	private SqlSessionTemplate sqlSession;
	
	//BoardMapper.xml에서 정의한 namespace
	private static String namespace = "com.lje.boardex.BoardMapper";
	
	
	@Override
	public void create(Board board) throws Exception {
		//BoardMapper.xml의 id
		sqlSession.insert(namespace+".create", board);
		

	}

	@Override
	public List<Board> listAll() throws Exception {
		return sqlSession.selectList(namespace+".selectAll");
	}

	@Override
	public Board read(int bno) throws Exception {
		return sqlSession.selectOne(namespace+".selectOne", bno);
	}

	@Override
	public void update(Board board) throws Exception {
		sqlSession.update(namespace+".modify", board);

	}

	@Override
	public void delete(int bno) throws Exception {
		sqlSession.delete(namespace+".remove", bno);

	}

	@Override
	public void hitUpdate(int bno) throws Exception {
		sqlSession.update(namespace+".hitUpdate", bno);

	}

}

 

 

Service

BoardServiceImpl

package com.lje.springboard.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.lje.springboard.dao.BoardDao;
import com.lje.springboard.dao.IDao;
import com.lje.springboard.dto.Board;

@Service
public class BoardServiceImpl implements BoardService {
	@Inject
	private IDao dao;
	//private IDao dao=new BDao...를 하지 않는 이유는 BDao에 @repository라는 annotaion을 넣어두어서 root-context.xml
	//context:component-scan에서 읽어온당. 따라서 root-context에는 bean을 만들지 않아도 된다.
	
	
	@Override
	public List<Board> listAll()  throws Exception {
		// TODO Auto-generated method stub
		return dao.listAll();
	}

	@Override
	public void insert(Board board)  throws Exception {
		dao.create(board);
	}

	@Override
	public Board read(int bno)  throws Exception{
		// 조회 시 조회수 증가
		dao.hitUpdate(bno);
		return dao.read(bno);
	}

	@Override
	public void modify(Board board)  throws Exception{
		dao.update(board);

	}

	@Override
	public void delete(int bno)  throws Exception{
		dao.delete(bno);

	}

}

 

BoardService

package com.lje.springboard.service;

import java.util.List;

import com.lje.springboard.dto.Board;

public interface BoardService {
	public List<Board> listAll() throws Exception;
	public void insert (Board board) throws Exception;
	public Board read(int bno) throws Exception;
	public void modify(Board board) throws Exception;
	public void delete(int bno) throws Exception;
}

 

BoardController

package com.lje.springboard.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lje.springboard.dto.Board;
import com.lje.springboard.service.BoardService;
import com.lje.springboard.service.BoardServiceImpl;

@Controller
@RequestMapping("/board")
public class BoardController {
	
	@Inject
	BoardService service;
	
	@RequestMapping("/list")
	public String list(Model model) throws Exception {
		//service = new BoardServiceImpl(); 위에 inject로 서비스객체가 만들어져서 필요없음
		model.addAttribute("list", service.listAll());
		return "board/list";
	}
	@RequestMapping("/read")
	public String read(@RequestParam("bno") int bno, Model model) 
			throws Exception{
		//service = new BoardServiceImpl();
		model.addAttribute("board", service.read(bno));
		return "board/update";
	}
	@GetMapping("write")
	public String writeForm() {
		return "board/write";
	}
	
	@PostMapping("write")
	public String write(@ModelAttribute("board") Board board) throws Exception{
		//service = new BoardServiceImpl();
		System.out.println(board); //작업테스트
		service.insert(board);
		return "redirect:list";
	}
	
	@RequestMapping("update")
	public String modify(@ModelAttribute("board") Board board) throws Exception{
		//service = new BoardServiceImpl();
		service.modify(board);
		return "redirect:list";
	}
	
	@RequestMapping("delete")
	public String delete(@RequestParam("bno") int bno) throws Exception{ 
		//service = new BoardServiceImpl();
		service.delete(bno);
		return "board/view";
	}
}
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

이번에는 Spring MVC 패턴을 이용하여 게시판을 만들어보도록 하겠습니다.
우선 로직과 파일의 폴더 구성은 아래와 같습니다.

 

 

작업 순서도

1. DB작성
2. 프로젝트 생성
3. pom.xml, web.xml 수정

 

 

 


 

1. 테이블, 시퀀스 작성 후 테스트 데이터 입력

select * from tab;
create table mvc_board( 
    bno number primary key, 
    writer varchar2(20) not null, 
    title varchar2(100) not null, 
    content varchar2(1000) not null,
    write_date DATE default SYSDATE, 
    hit int default 0);
create sequence mvc_board_seq;
insert into mvc_board(
    bno, writer, title, content)
    values (mvc_board_seq.nextval, 
    'kim', '제목1', '내용1입니다');
commit;

 

 

2. 프로젝트 생성

변경할 코드는 아래에서 참조한다.

 

Apache Tomcat 9 (9.0.24) - JNDI Datasource How-To

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky. Here then are some example configurations that have been poste

tomcat.apache.org

 

server.xml 수정

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --><Server port="8006" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector connectionTimeout="20000" port="8081" protocol="HTTP/1.1" redirectPort="8443"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8010" protocol="AJP/1.3" redirectPort="8443"/>


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>

      <!-- <Context docBase="test1" path="/test1" reloadable="true" source="org.eclipse.jst.jee.server:test1"/>
      <Context docBase="MVC_Board" path="/MVC_Board" reloadable="true" source="org.eclipse.jst.jee.server:MVC_Board"/>
      <Context docBase="exam01" path="/exam01" reloadable="true" source="org.eclipse.jst.jee.server:exam01"/> -->
      <Context docBase="SpringMVCBoard01" path="/springboard" reloadable="true" source="org.eclipse.jst.jee.server:SpringMVCBoard01">
     	<!-- driver, xe 수정 
     	 <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/> -->
      </Context></Host>
    </Engine>
  </Service>
</Server>

 

혹은 context.xml 수정

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <!-- driver, xe 수정 -->
     	 <Resource name="jdbc/myoracleDB" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

 

3. 이클립스 - 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>com.lje</groupId>
	<artifactId>springboard</artifactId>
	<name>SpringMVCBoard01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.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>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.12</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.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.8</source>
					<target>1.8</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>

 

 

pom.xml 수정 (2) Maven Repository 이용

1) spring-test context

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>

 

2) Spring JDBC

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>

 

3) dbcp

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>

 

4) mysql connector J

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

 

자동으로 Maven Repository로 연결이 되는 mysql과 달리 오라클은 유료 프로그램이기 때문에 직접 연결을 해 주어야 한다. Build Path를 눌러 Java Build Path > Add External JARs 그리고 Deployment Assembly > Java Build Path Entiries 를 눌러 두 가지를 추가해준다.

 

 

 

web.xml 수정 : <webapp></webapp>에 Character Encoding Filter 삽입

...더보기
<?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">

	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>

	</filter>

	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

 

 

4. 패키지 작성

com.exam.spring_board.command / com.exam.spring_board.controller
com.exam.spring_board.dao / com.exam.spring_board.dto

 

DAO

BoardDao.java

...더보기
package com.lje.springboard.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.lje.springboard.dto.Board;
import com.mysql.cj.xdevapi.PreparableStatement;

public class BoardDao {
	 private BoardDao() { }
	 private static BoardDao dao = new BoardDao();
	 public static BoardDao getInstance() { return dao; }
	

	public Connection getConnection() { // 커넥트풀
		Connection conn = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/myoracleDB");
			conn = ds.getConnection();
			// etc.
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public List<Board> selectAll() {
		List<Board> list = new ArrayList<Board>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from mvc_board";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Board board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setWrite_date(rs.getTimestamp("write_date"));
				board.setHit(rs.getInt("hit"));
				list.add(board);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps, rs);
		}
		return list;
	}
	
	//조회수 증가
	public void updateHit(int bno) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "update mvc_board set hit=hit+1 where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			int n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
		
	}
	

	public Board selectOne(int bno) {
		Board board = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from mvc_board where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			rs = ps.executeQuery();
			while (rs.next()) {
				board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setContent(rs.getString("content"));
				board.setWrite_date(rs.getTimestamp("write_date"));
				board.setHit(rs.getInt("hit"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps, rs);
		}
		return board;
	}
	
	public void insert(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "insert into mvc_board(bno, writer, title, content) "
				+ "values (mvc_board_seq.nextval, ?,?,?)";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			int n = ps.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	public void update(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "update mvc_board set writer=?, title=?, content=? "
				+ "where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			ps.setInt(4, board.getBno());
			int n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	public void delete(int bno) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "delete from mvc_board where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			int n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	private void closeDB(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void closeDB(Connection conn, PreparedStatement ps) {
		try {
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

 

DTO

Board.java

...더보기
package com.lje.springboard.dto;

import java.sql.Timestamp;

public class Board {
	private int bno;
	private String writer;
	private String title;
	private String content;
	private Timestamp write_date;
	private int hit;
	
	public int getBno() {
		return bno;
	}
	public void setBno(int bno) {
		this.bno = bno;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Timestamp getWrite_date() {
		return write_date;
	}
	public void setWrite_date(Timestamp write_date) {
		this.write_date = write_date;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
	@Override
	public String toString() {
		return "Board [bno=" + bno + ", writer=" + writer + ", title=" + title + ", content=" + content
				+ ", write_date=" + write_date + ", hit=" + hit + "]";
	}
	
}

 

 

SERVICE


BoardService.java

...더보기
package com.lje.springboard.service;

import java.util.List;

import com.lje.springboard.dto.Board;

public interface BoardService {
	public List<Board> listAll();
	public void insert (Board board);
	public Board read(int bno);
	public void modify(Board board);
	public void delete(int bno);
}

 

BoardServiceImpl.java (인터페이스)

인터페이스 생성 시 add로 BoardService를 추가해주면 자동으로 코드가 작성됩니다.

...더보기

1) 싱글톤 방식

package com.lje.springboard.service;

import java.util.List;

import com.lje.springboard.dao.BoardDao;
import com.lje.springboard.dto.Board;

public class BoardServiceImpl implements BoardService {
	
	
	@Override
	public List<Board> listAll() {
		// TODO Auto-generated method stub
		return BoardDao.getInstance().selectAll();
	}

	@Override
	public void insert(Board board) {
		BoardDao.getInstance().insert(board);
	}

	@Override
	public Board read(int bno) {
		// 조회 시 조회수 증가
		BoardDao dao = BoardDao.getInstance();
		dao.updateHit(bno);
		return dao.selectOne(bno);
	}

	@Override
	public void modify(Board board) {
		BoardDao.getInstance().update(board);

	}

	@Override
	public void delete(int bno) {
		BoardDao.getInstance().delete(bno);

	}

}

 

2) 어노테이션을 쓴다면 (지금사용안함)

package com.lje.springboard.service;

import java.util.List;

import com.lje.springboard.dao.BoardDao;
import com.lje.springboard.dto.Board;

public class BoardServiceImpl implements BoardService {
	BoardDao dao = null;
	public BoardServiceImpl() {
		dao = new BoardDao();
	}
	
	@Override
	public List<Board> listAll() throws Exception {
		// TODO Auto-generated method stub
		return dao.selectAll();
	}

	@Override
	public void insert(Board board) throws Exception {
		dao.insert(board);
	}

	@Override
	public read(int bno) throws Exception {
		// TODO Auto-generated method stub
		return dao.selectOne(bno);
	}

	@Override
	public void modify(Board board) throws Exception {
		dao.update(board);

	}

	@Override
	public void delete(int bno) throws Exception {
		dao.delete(bno);

	}

}

 

이 경우 BoardDao.java도 수정

package com.lje.springboard.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.lje.springboard.dto.Board;
import com.mysql.cj.xdevapi.PreparableStatement;

public class BoardDao {
	/*
	 * private BoardDao() { }
	 * 
	 * private static BoardDao dao = new BoardDao();
	 * 
	 * public static BoardDao getInstance() { return dao; }
	 */

	public Connection getConnection() { // 커넥트풀
		Connection conn = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/myoracleDB");
			conn = ds.getConnection();
			// etc.
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public List<Board> selectAll() {
		List<Board> list = new ArrayList<Board>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from mvc_board";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Board board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setWrite_date(rs.getTimestamp("write_date"));
				board.setHit(rs.getInt("hit"));
				list.add(board);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps, rs);
		}
		return list;
	}

	public Board selectOne(int bno) {
		Board board = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from mvc_board where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			rs = ps.executeQuery();
			while (rs.next()) {
				board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setWrite_date(rs.getTimestamp("write_date"));
				board.setHit(rs.getInt("hit"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps, rs);
		}
		return board;
	}
	
	public void insert(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "insert into mvc_board(bno, writer, title, content) "
				+ "values (mvc_board_seq.nextval, ?,?,?)";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			int n = ps.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	public void update(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "update mvc_board set writer=?, title=?, content=? "
				+ "where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			ps.setInt(4, board.getBno());
			int n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	public void delete(int bno) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "delete from mvc_board where bno=?";
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			int n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(conn, ps);
		}
	}
	
	private void closeDB(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void closeDB(Connection conn, PreparedStatement ps) {
		try {
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

 

 

CONTROLLER

BoardController.java

...더보기
package com.lje.springboard.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lje.springboard.dto.Board;
import com.lje.springboard.service.BoardService;
import com.lje.springboard.service.BoardServiceImpl;

@Controller
@RequestMapping("/board")
public class BoardController {
	BoardService service;
	
	@RequestMapping("/list")
	public String list(Model model) {
		service = new BoardServiceImpl();
		model.addAttribute("list", service.listAll());
		return "board/list";
	}
	@RequestMapping("/read")
	public String read(@RequestParam("bno") int bno, Model model) 
			throws Exception{
		service = new BoardServiceImpl();
		model.addAttribute("board", service.read(bno));
		return "board/update";
	}
	@GetMapping("write")
	public String writeForm() {
		return "board/write";
	}
	
	@PostMapping("write")
	public String write(@ModelAttribute("board") Board board) {
		service = new BoardServiceImpl();
		System.out.println(board); //작업테스트
		service.insert(board);
		return "redirect:list";
	}
	
	@RequestMapping("update")
	public String modify(@ModelAttribute("board") Board board) {
		service = new BoardServiceImpl();
		service.modify(board);
		return "redirect:list";
	}
	
	@RequestMapping("delete")
	public String delete(@RequestParam("bno") int bno) { 
		service = new BoardServiceImpl();
		service.delete(bno);
		return "board/view";
	}
}

 

 

 

VIEW (JSP) : list.jsp / write.jsp ...

중간 실행해서 체크해볼 때는 폴더 안에 만들었으니 /board/를 빼먹지 않는다. http://localhost:8081/springboard/board/list

...더보기

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tr>
			<td>번호</td>
			<td>제목</td>
			<td>작성자</td>
			<td>날짜</td>
			<td>조회수</td>
		</tr>
		<c:forEach items="${list }" var="board">
			<tr>
				<td>${board.bno }</td>
				<td><a href="read?bno=${board.bno}">${board.title }</a></td>
				<td>${board.writer }</td>
				<td>${board.write_date }</td>
				<td>${board.hit }</td>				
			</tr>
		</c:forEach>
	</table>
</body>
</html>

 

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="write" method="POST">
		<table>
			<tr>
				<td>작성자</td>
				<td><input type="text" name="writer"></td>
			</tr>
			<tr>
				<td>제목</td>
				<td><input type="text" name="title"></td>
			</tr>
			<tr>
				<td>내용</td>
				<td><textarea rows="7" cols="50" name="content"></textarea></td>
			</tr>
			<tr>
				<td colspan=2 align="center">
					<input type="submit" value="저장">
					<input type="reset" value="재작성">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>update.jsp</title>
</head>
<body>
	<form action="update" method="POST">
		<table border=1>
			<tr>
				<td>번호</td>
				<td><input type="text" name="bno" readonly value="${board.bno }"></td>
			</tr>
			<tr>
				<td>작성자</td>
				<td><input type="text" name="writer" value="${board.writer }"></td>
			</tr>
			<tr>
				<td>제목</td>
				<td><input type="text" name="title" value="${board.title }"></td>
			</tr>
			<tr>
				<td>내용</td>
				<td><textarea rows="7" cols="50" name="content">${board.content }</textarea></td>
			</tr>
			<tr>
				<td>작성일</td>
				<td>${board.write_date }</td>
			</tr>
			<tr>
				<td>조회수</td>
				<td>${board.hit }</td>
			</tr>
			<tr>
				<td colspan=2 align="center">
					<input type="submit" value="저장">
					<input type="reset" value="재작성">
					<input type="reset" value="삭제" onclick="location.href='delete?bno=${board.bno}'">
					<input type="reset" value="목록보기" onclick="location.href='list'">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

 

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

부산인재개발원 취업지원팀에서 들은 이력서와
 자기소개서 작성법 수업을 듣고 요약 정리해보았습니다.

 


 

1. 이력서 작성

사진은 주민등록증 사진 캡쳐는 금물!
새로 계절감이 드러나지 않는 4계절용 정장을 입고 찍어준다.
언제나 지원할 수 있도록! 3개월 이내 촬영한 것이면 더 좋다.


생년월일 : 주민등록 상 생년월일
연락처 : 잘못 적지 않았는지, 바뀌었는 지 두번 체크

개인 웹사이트가 있으면 적어준다.

학력은 고등학교부터 이전 직장까지 적어준다.
순서는 대학교부터 거꾸로.

워킹홀리데이, 해외, 자격증 등
자격증은 3~4개 정도가 적당하다.
자동차운전면허증는 (지역명)경찰청으로,

국비지원 교육 이수 기간이 있다면 적어준다.
기간, 교육명, 기관명, 주요내용까지 적어준다.

수상내역과 팀프로젝트 등도 기재한다.

 

기타 작성 시 유의사항


 자신에게 유리한 이력서 양식을 선택하며
지원분야를 잘 체크하며
업무, 사회성을 나타내기 위한 경력과
오탈자를 유의하며(자간, 글씨크기, 맞춤법 확인)
* 한글의 경우 Alt+C를 누르면 똑같아지고
워드는 빗자루모양 메뉴를 활용한다.

 

 


2. 자기소개서 작성

 

기업은 자소서를 통해 지원자의 대인관계,
적응력, 성격, 인생관, 성장배경, 장래성을
가늠하려 하기에 회사가 원하는 이력서는
개인을 개괄적으로 이해하는 문서
자소서는 개인을 보다 깊이 이해하기 위한
목적으로 생각하고 작서하면 되겠다.

회바회지만 개성보다는 기업과 나의
 융화성을 잘 어필해주면 좋은데

성장과정 :
특별히 남달랐던 부분만.
에피소드, 가훈만 '핵심있게'
회사나 업무에 도움이 되는 특성으로
장점이 된 결과만 적어준다.

성격 : 업무에 방해가 되는 단점은 삭제!
단점은 보완점이나 개선을 위해했던 노력과
단점이 곧 장점이 되는 부분을 적는다.

사회생활 : 경력사항, 담당업무는 구체적으로
업무는 단순나열보다는 배운점, 
성과 등을 적는다. '긍정적으로'

지원동기 / 입사 후 포부 : 자바언어를 기반으로
한 웹 앱 개발 등 배운 내용을 기반으로 한
프로그램업체에 지원한다는 소설

기업 입장에서 보기에 지원자가 할 줄 
아는 것과 입사 후 무얼 잘하겠다는
예측이 되도록 내용을 채운다.

 

 

기타 작성 시 유의사항

 

자소서는 한 장에 여백이 없도록 작성한다.
유사경력이 없어도 경력 란에 아르바이트나
다른 경력을 적어주는 게 좋다.
왜냐하면 사회경험 및 사회성을 보기 때문

 

글자체, 크기, 자간 등 서식은 일치시키고
미리보기 또는 인쇄를 활용해 체크한다.

 

절대 구구절절 늘어놓지 않고
경력만 단순 나열한다.

 

지원 회사 사이트 및 정보를 참고해
지원 동기 및 입사 후 포부를 적는다.
귀사에서 배워 내 커리어를 쌓겠다
좋은 경험이 될 것이다 따위의 이야기는
빼자. ---- 본인의 커리어를 쌓아
이직할 수 있다는 느낌을 주지 말자.

 

막연하게 이 분야가 좋다기보다
구체적으로 이 분야에 어떤 부분이 좋고
나의 어떤 부분과 잘맞는지를 언급하면 좋다.

 

 


서류지원 사이트

 

 

사람인

잡코리아

워크넷(공공기관)

인크루트(자소서 예시가 좋다)

알바몬

알바천국

부산시청

 

 


서류 지원 시 주의사항

 

'자바' 이렇게 검색하기보다
2차분류-'소프트웨어'
이런 식으로 크게 체크 후 검색해보자
학원생들 서류 지원은 평균 100개의
 기업에 지원을 한다고 한다.

포트폴리오 등 첨부파일도 꼼꼼히 쳌!

 

 

 


면접 준비

 

회사에 잘 어울릴 사람인지를 테스트하는 자리.

회사에 대한 기본 정보, 비전, 대표자 등
사이트에서 체크해보고 면접을 간다.

내게 요구되는 기술 및 지식을
대표적인 용어를 말로 정리해
연습해보고 간다.

1분 자기소개를 시키기도 한다.
드러내야할 것은 내 장점, 경험 등
깔끔하고 군더더기 없이 한다.

수료한 교육 내용을 물어볼 수도 있고
팀프로젝트 시 어려웠던 점
프로그램 분야로 진로를 변경한 이유
교육 받으면서 잘 했던 분야 
가장 힘들었던 분야
지원한 동기, 회사에 궁금한 점

 

인사담당사가 면접 시 경계하는 사람
결국 무난히 열심히 하는 사람을 원한다.

팀내 트러블메이커, 이기주의자
지각, 결근러, 실제 역량보다
부풀려진 이력서, 조직원가 전혀
어울리지 못하는 유형을 피할 것이다.

 

화법


천천히 간단명료히 차분히 또박또박, 
질문을 재확인하는 것도 괜찮다.
외래어, 반말, 속어 은어는 당연히 피하고
모르는 부분 지적 시 차분히 배우겠다고 피드백.



면접 15분 전에 도착


면접관 눈을 너무 보지도 너무 피하지도 않는다
결론부터 말한다, 
질문에 대답은 3분 정도로,
말끝을 분명히 하고 지나친 바디랭귀지는 자제
기분 나쁜 질문에도 성의껏 대답

 


부산인재개발원 취업지원팀 전화번호 : 051-927-9911

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

MVC 패턴


애플리케이션의 역할을 모델(Model), 뷰(View), 컨트롤러(controller)로 나누어 작업
Smalltalk-80 처음 소개
업무 서비스와 도메인 객체를 사용자 인터페이스로부터 분리, 하나 이상의 컨트롤러를 통해서 이들 사이 상호작용을 통제하는 아키텍처 패턴

 

 

MVC 모델 구성 요소

 

모델 : 데이터를 실어서 보내준다.


애플리케이션의 핵심적인 기능 제공
뷰와 컨트롤러 등록
데이터 변경 시 뷰와 컨트롤러에 통지



관련된 컨트롤러 생성, 초기화, 사용자에게 정보 표시
데이터 변경이 통지될 때 모델로부터 데이터를 읽어 처리


컨트롤러


사용자 입력을 이벤트로 받아들여 해석하여 모델에 대한 요청을 서비스하거나 뷰에 대한 요청을 표시
데이터 변경이 통지될 때 모델로부터 데이터 읽어와 처리
Front Controller 패턴 적용 – 컨트롤러가 중심이 되는 변형된 구조를 가짐 (이전 글의 BoardServlet 같은 전단서블릿)

 

 

CRUD MVC 패턴 총정리 : 게시판만들기

오라클에서 테이블 만들기 select * from tab; //테이블 뭐가 있나 조회 create table test( bno number primary key, writer varchar2(20), title varchar2(100), content varchar2(1000), reg_data date default..

coding-restaurant.tistory.com

 

동작


클라이언트가 컨트롤러에게 데이터 조회, 저장 등의 작업 요청
컨트롤러 : 서블릿으로 구현, 업무 로직 처리, 모델생성, 모델의 데이터 갱신, 뷰에 모델 전송, 뷰가 변경된 데이터 사용 가능하게 함
모델 : POJO Java 클래스로 구현, 데이터와 데이터처리에 필요한 메서드 포함, 자신이 관리하는 데이터에 집중
뷰 : JSP로 구현, 컨트롤러가 제공한 모델을 사용하여 데이터에 액세스하여 웹페이지(뷰)를 렌더링하여 응답을 생성하고 컨트롤러에 전달
컨트롤러는 클라이언트에 응답을 전송하고 서비스 종료

 

 

Spring MVC 매커니즘

 

 

BoardServlet 만들 필요 없이 기본으로 Servlet MVC 패턴은 Dispatcher Servlet을 제공한다.
또한 annotation도 제공한다.

1. 핸들러 맵핑 : 어떤 요청이 들어왔는지 확인한다.
2. 실질적으로 일을 처리할 컨트롤러를 선택한다.
3. 처리 결과를 Model(데이터를 실어준다)과 논리View(데이터를 표시)로 다시 Dispatcher Servlet으로 돌려준다. 
4. ViewResolver, 진짜 물리적인 뷰를 찾아서 내용을 보여준다.

* 논리뷰와 물리적인 뷰의 차이는>

 

 

 

스프링 프로젝트 작성 두 가지 방법


Spring Boot를 이용하는 방법 

File -> new -> Spring Start Project


Spring 템플릿 프로젝트를 이용하는 방법 (이 글에서 사용할 전통적인 방법)
File>New>Spring Legacy Project
New Spring Project 위저드의 Spring Project 화면에서 Spring MVC Project 항목을 선택, 프로젝트 이름: SpringProject01로 지정하고 next 선택
Project Setting>Spring MVC Project화면에서 패키지명을 com.pgm.project01로 지정, finish 선택

 

 

디렉토리 구조 살펴보기


src/main/java - controller (dto, dao...)
resources - 자원
webapp - view

 

 


--- 디렉토리는 * 두개, 파일이름은 하나

 

스피링 한글 처리 인코딩 필터

한글 처리 시 web.xml에 CharacterEncodingFilter 추가

<filter>
	<filter-name>characterEncodingFilter</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>
    <init-param>
    	<param-name>forceEncoding</param-name>
        <param-value>true</param-value>
   </init-param> 
</filter> 

<filter-mapping> //필터 지정 위치
	<filter-name>characterEncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

 

 

root 웹 애플리케이션 컨텍스트


IoC 컨테인 애플리케이션 컨텍스트는 트리 구조를 가짐
모든 애플리케이션 컨텍스트는 부모 애플리케이션 컨텍스트를 가질 수 있으며, 계층구조 안에 모든 애플리케이션 컨텍스트는 각각 독립적인 설정 정보를 사용하여 Spring 빈 객체를 생성하고 관리
의존성 주입을 위해 Spring 빈을 찾을 때 먼저 자신의 애플리케이션컨텍스트를 관리하는 Spring 빈 중에서 찾는다
자신을 관리하는 Spring 빈 중에 없는 경우 부모 애플리케이션 컨텍스에게 Spring 빈을 찾아 줄 것을 요청
계층구조를 따라 최상위 root 컨텍스트까지 요청 가능

 

 

컨트롤러 구현

 

 

 

데이터를 받는 두 가지 방법

 

 

데이터(커맨드) 객체 이용

 

 

 

Get /Post 방식 처리

 

 

 


 

실습하기

 

1. Spring Legacy Project 프로젝트를 생성한다.

 

 

스프링은 항상 디폴트 패키지를 적어야한다.
사용하지 않는 프로젝트는 클로즈 시켜서 닫아두어야 엉키는 등의 에러가 없다.

 

 

처음 플젝 만들 때마다 시작 전 구축이 빨라진 이유는 아래 사진처럼
디폴트로 받아야하는 라이브러리가 이미 생성되어있기 때문이다. 

 

 

 

2. Maven Repository 바로가기

스프링의 장점! 직접 찾아 라이브러리를 넣어줄 필요없이
pom.xml에 라이브러리를 등록해놓으면 알아서 프로그램이 찾아간다.

 

 

Maven Repository: Search/Browse/Explore

Vert.x Web Client Last Release on Aug 26, 2019

mvnrepository.com

 

프로젝트 아래 pom.xml을 수정한다.
. Maven을 사용하는 프로젝트에는 설정 파일인 pom.xml 파일이 있다.
POM Project Object Model의 약자

출처 : https://offbyone.tistory.com/163

 

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>com.lje</groupId>
	<artifactId>exam01</artifactId>
	<name>exam01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>3.1.1.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>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>        
	</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>

 

자바버전 수정, 스프링 현재버전(5.1.9)으로 바꾸고  junit 버전을 고친다.
스프링 현재버전 확인은 아래 홈페이지에서.

 

 

pom.xml 변경 후 플젝의 버전들이 자동으로 바뀐 것을 확인해볼 수 있다.
메이븐을 사용하여 프로젝트의 라이브러리 의존성을 관리하면 실제 .jar 파일들을 관리할 필요없이 pom.xml 파일만 잘 관리하며 되는 것

 

 

다른 방법으로는 Maven > Update Project 한 후 프로퍼티에 들어가 확인한다.

 

 

 

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>com.lje</groupId>
	<artifactId>exam01</artifactId>
	<name>exam01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.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>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.12</version>
			<scope>test</scope>
		</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.8</source>
                    <target>1.8</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>

 

 

로딩 순서

실행 시 web.xml을 가장 먼저 읽는다. 스프링에서 루트는 webapp이다. (jsp의 WebContent와 같은 것)

 

 

 

Web.xml

...더보기
<?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">

	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 디폴트서블릿 -->
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>characterEncodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
</web-app>

 

디폴트 패키지에 가서 컨트롤러를 보고, 그 후 RequestMapping 에 보면 / (루트,경로)가 적혀있다.
요청을 찾는다는 뜻.

 

 

 

TestController.java

...더보기
package com.lje.exam01;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.ModelAndView;

import com.lje.exam01.vo.MemberInfo;

@Controller
public class TestController {

	@RequestMapping(value = "/test", method = RequestMethod.POST)
	public String test(HttpServletRequest req, Model model) {
		String name = req.getParameter("name");
		model.addAttribute("name", name);
		return "test";
	}

	// public void test(){}해도 찾아진다.
	// public String test(){return "test"; //논리뷰}

	@RequestMapping("/input")
	public String input() {
		return "board/input";
	}

//	@RequestMapping(value="/memberPro", method=RequestMethod.POST)
//	public String member(Request..??? request, Model model) {
//		String id = request.getParameter("id");
//		String pw = request.getParameter("pw");
//		String name = request.getParameter("name");
//		String tel = request.getParameter("tel");
//		model.addAttribute("id", id);
//		model.addAttribute("pw", pw);
//		model.addAttribute("name", name);
//		model.addAttribute("tel", tel);
//		return "board/memberPro";
//	}
	
	@RequestMapping(value="/memberPro", method=RequestMethod.POST)
	public String member(@RequestParam("id") String id, 
			@RequestParam("pw") String pw, Model model) 
	{
		model.addAttribute("id", id);
		model.addAttribute("pw", pw);
		return "board/memberPro";
	}

	/* @RequestMapping("/view") */
	public ModelAndView view() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("id", "abcd");
		mv.addObject("pw", "1234");
		mv.setViewName("board/view");
		return mv;
	}

	// 위랑 같은 내용 다른 문법
	@RequestMapping("/view")
	public String view(Model model) {
		model.addAttribute("id", "abcd");
		model.addAttribute("pw", "1234");
		return "board/view";
	}
	
	@RequestMapping("/test2")
	public String view2(@RequestParam("id") 
	String id, Model model) {
		model.addAttribute("id", id);
		return "board/view";
	}
	
	//@RequestMapping("/test3")
	public String memberView(MemberInfo memberInfo ) {
		return "board/view3"; 
	}
	
	//test3의 다른 방법
	@RequestMapping("/test3")
	public String memberView(HttpServletRequest request, 
			Model model) {
		MemberInfo memberInfo = new MemberInfo();
		memberInfo.setName(request.getParameter("name"));
		memberInfo.setId(request.getParameter("id"));
		memberInfo.setPw(request.getParameter("pw")); 
		memberInfo.setTel(request.getParameter("tel")); 
		model.addAttribute("memberInfo", memberInfo);
		return "board/view3"; 
	}
	

}

 

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

오라클에서 테이블 만들기

select * from tab;  //테이블 뭐가 있나 조회

create table test(
bno number primary key,
writer varchar2(20),
title varchar2(100),
content varchar2(1000),
reg_data date default sysdate);

create sequence test_seq;

insert into test (
bno, writer, title, content)
values (test_seq.nextval, 'aaa', '제목입니다', '내용입니다');

select * from test;

commit;

 

New > Dynamic Web Project > MVC_Board 프로젝트를 만든다.
* 만들 때 Generate web.xml deployment desciptor에 체크한 후 Finish한다.

 

 

 

톰캣 홈페이지의 Taglibs에 들어가 네가지를 다운받은 후, lib폴더에 붙여넣는다.

 

 

아파치 톰캣 웹사이트에 들어가 document > Oracle 부분의 소스를 참고할 것이다.

 

Apache Tomcat 9 (9.0.24) - JNDI Datasource How-To

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky. Here then are some example configurations that have been poste

tomcat.apache.org

 

MVC 패턴 코드 전체구성

 

 

 

 

META-INF

context.xml : Resource name 부분을 복사 붙여넣기 후 수정

<?xml version="1.0" encoding="UTF-8"?>
<context>
	<Resource name="jdbc/boardddb" auth="Container"
              type="javax.sql.DataSource" 
              driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
              username="mvc" password="1234" 
              maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
</context>
<!--maxTotl : 커넥트풀 최대유지 . -1 : 시간안정함 -->

 

web.xml 셋팅 : 부분을 복사 붙여넣기 후 수정 (web-content)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	id="WebApp_ID" version="4.0">
	<display-name>MVC_Board</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<resource-ref>
		<description>Oracle Datasource example</description>
		<res-ref-name>jdbc/boardddb</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>
</web-app>

 

 

dao

DBConn.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConn {
	public static Connection getConnection() {
		Connection conn=null;
		try {
			Context initContext = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource)envContext.lookup("jdbc/boardddb");
			conn = ds.getConnection();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return conn;
	}
	public static void closeConn(Connection con) {
		try {
			if(con!=null)
				con.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	public static void closePs(PreparedStatement ps) {
		try {
			if(ps!=null)
				ps.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	public static void closeRs(ResultSet rs) {
		try {
			if(rs!=null)
				rs.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

 

 

BoardDao.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import dto.Board;

public class BoardDao {
	//싱글톤
	private BoardDao () {}
	private static BoardDao dao = new BoardDao();
	public static BoardDao getInstance() {
		return dao;
	}
	public ArrayList<Board> selectAll(){
		ArrayList<Board> list = new ArrayList<Board>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		String sql = "select * from test";
		try {
			conn = DBConn.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				Board board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setContent(rs.getString("content"));
				board.setReg_data(rs.getTimestamp("reg_data"));
				list.add(board);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConn.closeRs(rs);
			DBConn.closePs(ps);
			DBConn.closeConn(conn);
		}
		
		System.out.println(list.toString());
		return list;
		
	}  
	public Board selectOne(int bno){
		Board board = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		String sql = "select * from test where bno=?";
		try {
			conn = DBConn.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			rs = ps.executeQuery();
			while(rs.next()) {
				board = new Board();
				board.setBno(rs.getInt("bno"));
				board.setWriter(rs.getString("writer"));
				board.setTitle(rs.getString("title"));
				board.setContent(rs.getString("content"));
				board.setReg_data(rs.getTimestamp("reg_data"));
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConn.closeRs(rs);
			DBConn.closePs(ps);
			DBConn.closeConn(conn);
		}
		return board;
		
	}  	
	public void insert(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "insert into test(bno, writer, title, content)"
				+ "values(test_seq.nextval,?,?,?)";
		
		try {
			conn = DBConn.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			int n = ps.executeUpdate();
		} catch (Exception e) {
				e.printStackTrace();
		} finally {
			DBConn.closePs(ps);
			DBConn.closeConn(conn);
		}
	}
	public void update(Board board) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "update test set writer=?, title=?, content=? where bno=?";
		
		try {
			conn = DBConn.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, board.getWriter());
			ps.setString(2, board.getTitle());
			ps.setString(3, board.getContent());
			ps.setInt(4, board.getBno());
			int n = ps.executeUpdate();
		} catch (Exception e) {
				e.printStackTrace();
		} finally {
			DBConn.closePs(ps);
			DBConn.closeConn(conn);
		}
	}
	public void delete(int bno) {
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "delete from test where bno=?";
		
		try {
			conn = DBConn.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bno);
			int n = ps.executeUpdate();
		} catch (Exception e) {
				e.printStackTrace();
		} finally {
			DBConn.closePs(ps);
			DBConn.closeConn(conn);
		}
	}
	
}

 

 

dto

Board.java

package dto;

import java.sql.Timestamp;

public class Board {
	private int bno;
	private String writer;
	private String title;
	private String content;
	private Timestamp reg_data;
	public int getBno() {
		return bno;
	}
	public void setBno(int bno) {
		this.bno = bno;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Timestamp getReg_data() {
		return reg_data;
	}
	public void setReg_data(Timestamp reg_data) {
		this.reg_data = reg_data;
	}
	@Override
	public String toString() {
		return "Board [bno=" + bno + ", writer=" + writer + ", title=" + title + ", content=" + content + ", reg_data="
				+ reg_data + "]";
	}
	
}

 

 

 

controller

BoardServlet.java (전단서블릿)

package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controller.service.BoardService;
import oracle.net.aso.s;

/**
 * Servlet implementation class BoardServlet
 */
@WebServlet("*.do")
public class BoardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BoardServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/* get은 자동인데 포스트는 한글처리해줘야된다 */
		request.setCharacterEncoding("utf-8");
		doProcess(request, response);
	}
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		
		ActionFactory af = ActionFactory.getInstance(); 
		BoardService service =af.getService(command) ;
		if(service!=null)
			service.execute(request, response);
					

	}

}

 

 

ActionFactory.java

package controller;

import controller.service.BoardDeleteService;
import controller.service.BoardListService;
import controller.service.BoardService;
import controller.service.BoardUpdateService;
import controller.service.BoardViewService;
import controller.service.BoardWriteFormService;
import controller.service.BoardWriteService;

public class ActionFactory {
	//싱글톤
	private ActionFactory () {}
	private static ActionFactory af = new ActionFactory();
	public static ActionFactory getInstance() {
		return af;
	}
	public BoardService getService(String command) {
		BoardService service = null;
		if(command.equals("/list.do"))
			service = new BoardListService();
		else if(command.equals("/writeForm.do")) {
			service = new BoardWriteFormService();
		}else if(command.equals("/write.do")) {
			service = new BoardWriteService();
		}else if(command.equals("/view.do")) {
			service = new BoardViewService();
		}else if(command.equals("/update.do")) {
			service = new BoardUpdateService();
		}else if(command.equals("/delete.do")) {
			service = new BoardDeleteService();
		}
		return service;
	}
}

 

 

controller.service

BoardService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface BoardService {
	public void execute(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException;
}

 

BoardListService.java

package controller.service;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDao;
import dto.Board;

public class BoardListService implements BoardService {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 BoardDao dao = BoardDao.getInstance();
		 ArrayList<Board> list = dao.selectAll(); //게시판리스트 받아옴
		 request.setAttribute("boardlist", list); //리케스트의 속성으로 넣음 (실제부르는이름, 보이는이름)
		 request.getRequestDispatcher("/board/list.jsp").forward(request, response); 
		 //포워드 정보 페이지로 request, response를 갖고 list.jsp로 감. 가면 boardlist를 바로 읽을 수 있음 
		 
	}

}

 

 

BoardWriteFormService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BoardWriteFormService implements BoardService{

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.getRequestDispatcher("board/write.jsp")
		.forward(request, response);
		
		
	}
		
}

 

BoardWriteService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDao;
import dto.Board;

public class BoardWriteService implements BoardService {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		Board board = new Board();
		board.setWriter(request.getParameter("writer"));
		board.setTitle(request.getParameter("title"));
		board.setContent(request.getParameter("content"));
		BoardDao dao = BoardDao.getInstance();
		dao.insert(board);
		response.sendRedirect("list.do");
	}

}

 

BoardViewService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDao;
import dto.Board;

public class BoardViewService implements BoardService {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int bno = Integer.parseInt(request.getParameter("bno"));
		BoardDao dao = BoardDao.getInstance();
		Board board = dao.selectOne(bno);
		request.setAttribute("board", board);
		request.getRequestDispatcher("board/view.jsp")
			.forward(request, response);
	}

}

 

BoardUpdateService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDao;
import dto.Board;

public class BoardUpdateService implements BoardService {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		Board board = new Board();
		board.setBno(Integer.parseInt(request.getParameter("bno")));
		board.setWriter(request.getParameter("update"));
		board.setTitle(request.getParameter("title"));
		board.setContent(request.getParameter("content"));
		
		BoardDao dao = BoardDao.getInstance();
		dao.update(board);
		response.sendRedirect("list.do");
	}

}

 

BoardDeleteService.java

package controller.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDao;
import dto.Board;

public class BoardDeleteService implements BoardService {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int bno = Integer.parseInt(request.getParameter("bno"));
		BoardDao dao = BoardDao.getInstance();
		dao.delete(bno);
		response.sendRedirect("list.do");
	}

}

 

 

WebContent

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%response.sendRedirect("list.do"); %>
</body>
</html>

 

 

board

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tr>
			<td colspan="4" align="right">
			<a href="writeForm.do">글쓰기</a></td>
		</tr>
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성자</th>
			<th>작성일</th>
		</tr>
		<c:forEach items="${boardlist}" var="board">
		<tr>
			<td>${board.bno }</td>
			<td><a href="view.do?bno=${board.bno }">${board.title}</a></td>
			<td>${board.writer }</td>
			<td><fmt:formatDate value="${board.reg_data }"/></td>
		</tr>
		</c:forEach>
	</table>
</body>
</html>

 

view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="update.do" method="post">
	<table>
		<tr>
			<th>번호</th>
			<td><input type="text" name="bno" readonly value=${board.bno }></td>
		</tr>
		<tr>
			<th>작성자</th>
			<td><input type="text" name="writer" value=${board.writer }></td>
		</tr>
		<tr>
			<th>제목</th>
			<td><input type="text" name="title" value=${board.title }></td>
		</tr>
		<tr>
			<th>내용</th>
			<td><textarea rows="7" cols="50" name="content">${board.content}</textarea></td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<input type="submit" value="수정">
				<input type="reset" value="취소">
				<input type="button" value="삭제" onclick="location.href='delete.do?bno=${board.bno}'">
				<input type="button" value="목록" onclick="location.href='list.do'">
			</td>
		</tr>
	</table>
	</form>
</body>
</html>

 

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="write.do" method="post">
	<table>
		<tr>
			<th>작성자</th>
			<td><input type="text" name="writer"></td>
		</tr>
		<tr>
			<th>제목</th>
			<td><input type="text" name="title"></td>
		</tr>
		<tr>
			<th>내용</th>
			<td><textarea rows="7" cols="50" name="content"></textarea></td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<input type="submit" value="저장">
				<input type="reset" value="취소">
				<input type="button" value="목록" onclick="location.href='list.do'">
			</td>
		</tr>
	</table>
	</form>
</body>
</html>

 

 

처리 순서 요약

index(뷰)에서 요청 -> boardservlet 에서 do/post 중 하나 -> process에서 request정보, 전체 uri 중 contextpath(프로젝트 우측 버튼, 프로퍼티에 가면 web project setting의 context root)를 가져온다. (index 앞의 response.sendRedirect("list.do"); list.do 앞에 이것저것 붙는다. ) uri는 실제 리소스 주소 (MVC_Board/list.do)다. url은 http부터.

contextpath.length() 는 길이. 전체 주소에서 path의 길이 (/ 포함)
어떤 값이 나오는 게 궁금하면 System.out.println(requestURI....contextpath...command)등으로 출력해본다.

BoardServlet의 BoardService에서 서비스를 얻기위해

ActionFactory 서비스 생성 후 레퍼런스 리턴

다시 BoardServlet 와서 request, response 참조값을 가지고 함수 호출..

db의 값을 가지고 list.jsp 페이지로 간다.

list.jsp에...

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

개발 환경의 우선순위

 

 

스프링 개발 툴 (3가지 방법)

1. 이클립스 + 스프링 플러그인
 Help -> Eclipse Marketplace에서 Spring Tools Add-On 3.9.7.Release 확장 프로그램 설치

2. STS(Spring Tool Suite)
 이클립스에 스프링 플러그인이 포함된 버전
https://spring.io/tools 에서 STS4 다운로드(윈도우 64bit용)
 압축을 해제한 후 ecplipsec.exe 또는 SpringToolSuite4.exe 실행
 에러가 발생할 경우 – 한경변수에 JAVA_HOME, path에 JAVA_HOME/bin 추가
 주의 : sts 설치디렉토리 및 workspace는 한글 이름이 들어간 디 렉토리를 사용하지 말 것

3. InteliJ

 

아래 core 에서 64bit 버전을 받아 (본인의 컴퓨터는 64bit므로) 압축파일을 풀어 C드라이브에 위치한다.

 

 

Apache Tomcat® - Apache Tomcat 9 Software Downloads

Welcome to the Apache Tomcat® 9.x software download page. This page provides download links for obtaining the latest version of Tomcat 9.0.x software, as well as links to the archives of older releases. You must verify the integrity of the downloaded files

tomcat.apache.org

 

이클립스에 가서 서버를 연결해준다. 화면에 없으면 View > other > server를 클릭해서 나타나게 한다.

 

 

서버 연결 시 포트 에러가 생기는 경우는 바꿔주자.

 

 

 

툴즈 설치

 

Help > Ecilipse MarketPlace에 들어가서 Spring을 검색하면 Tools와 Add-ON(플러그인)이 있다.
우리는 Tools3를 설치해야 하며 Spring Tools3은 정통방식 4는 부트형식으로 프로그래밍할 때 받는 것이다.

 

 

별다른 과정 없이 설치해준 뒤 이클립스를 재시작해주면 끝난다.

 

 

 


 

스프링 툴스 홈페이지

 

Spring Tools 4

Spring Tools 4 is the next generation of Spring tooling for your favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code,

spring.io

 

Spring Tools

Spring Tool Suite™ 3

spring.io

 

우리는 3버전에 들어가서 윈도우 버전으로 받아본다. 

 

 

Spring Tool Suite™ 3 (STS 3) Download page

Use one of the links below to download an all-in-one distribution for your platform. Choose either a native installer or simple archive, they contain equivalent functionality

spring.io

 

파일의 경로나 이름이 길면 에러가 발생할 수 있으니 C드라이버에 sts3.zip으로 이름을 변경해서 압축 해제한다.
지금받는 파일은 일종의 이클립스라고 보면 된다. 만일 이클립스가 열려있으면 닫은 뒤 sts프로그램을 실행해준다.
exe파일은 아래 경로에 있다.

 

 

실행시키면 이클립스처럼 뜬다. 아까 서버를 연결해두었던 프로젝트라 연결되어있는 것을 확인할 수 있다.

 

 

스프링 뿐만 아니라 거의 모든 프로젝트를 만들어 작업할 수 있다.

 

 

다음으로는 테스트 프로젝트를 생성한다.

 

 

그 이전의 팝업은 OK하고 패키지 경로는 3단계로 자유로이 적어준다. url 거꾸로 적듯 하는건데 com.lje.test1으로 했다.
보통 두번째는 회사명 세번째는 프로젝트명으로 많이 만든다. 생성 후 플젝에 에러뜨는 것은 라이브러리를 아직 받는 중이어서 그렇다. 그래도 이전처럼 직접 라이브러리를 받을 필요가 없어져서 좋아진거라고 한다.

 

 

서버를 돌려본다.

 

 

언어설정

Web

 

 

4버전으로 새로운 경로폴더를 만들었는데 이 버전은 기본 스프링 > 레거시프로젝트가 없다.

 

서버 연결 후 윈도우 > 이클립스 마켓플레이스 > 스프링 검색 후 3 Add on 설치하면 레거시프로젝트 사용 가능

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

이번에는 스프링 개요 및 환경 구축에 대해 알아보겠습니다.


 

프레임워크(Framework) 정의

* 사전적 의미 : ‘어떤 것을 구성하는 구조 또는 뼈대’ 
소프트웨어적 의미로는 ’기능을 미리 클래스나 인터페이스 등으로 만들어 제공하는 반제품’을 뜻한다.

 

프레임워크(Framework) 장점

1. 일정한 기준에 따라 개발이 이루어지므로 개발 생산성과 품질이 보장된 애플리케이션을 개발할 수 있음
2. 개발 후 유지보수 및 기능의 확장성에서도 고품질 보장
* 소형 프로젝트는 jsp모델1을 쓰나 형태가 커지면 모델 뷰 컨트롤러를 분리하는 게 맞다.

 


 

스프링 프레임워크 정의

1. 스프링 프레임워크(이하 스프링)는 자바 웹 애플리케이션 개발을 위한 오픈소스 프레임워크
2. EJB(Enterprise Java Bean, 엔터프라이즈 자바 빈즈)보다 경량 프레임워크(lightWeight Framework)
EJB는 서버클라이언트를 조절하기에 기능이 많아 편리하다. 그러나 고성능 서버를 요구한다.
* 환경설정 이해가 중요하다
. jsp로 구축한 이전 과정에 비해 상대적으로 쉬운 편.

 

스프링 프레임워크 특징

1. 의존성 주입(DI: Dependency Injection)
 클래스 객체를 개발자가 코드에서 생성하지 않고 프레임워크가 생성하여 사용하는 방법

2. 제어 역행(IoC: Inversion of Control)
 개발자가 필요한 코드를 작성, 특정 구조에 포함
 서블릿이나 빈 등을 개발자가 코드에서 생성하지 않고 프레임워크가 직접 수행하는 방법

3. 관점지향(AOP : Aspect Oriented Programming)
 관심사의 분리 (Seperation of Concerns)
 핵심 기능 외 부수 기능들을 분리 구현함으로써 모듈성을 증가시키는 방법
 보안, 트랜잭션, 로깅 처리 등이 대표적

4. POJO(plain old java object) 방식 프레임워크
 특정 규약과 환경에 종속되지 않는다.
 단일 책임 원칙을 지키는 클래스

 


 

컨테이너(Container) 정의

1. 톰캣은 서블릿 컨테이너라고 부르는데, 그 이유는 톰캣을 실행하면 톰캣은 서블릿의 생성, 초기화, 서비스 실행, 소멸에 관한 모든 권한을 가지고 서블릿을 관리

2. 스프링은 애플리케이션에서 사용되는 여러 가지 빈(클래스 객체)을 개발자가 아닌 스프링이 권한을 가지고 직접 관리

 


 

스프링의 특징

1. EJB보다 가볍고 배우기도 쉬우며 경량 컨테이너의 기능을 수행
2. 제어 역행(IoC, Inversion of Control) 기술을 이용해 애플리케이션 간의 느슨한 결합을 제어함.
3. 의존성 주입(DI, Dependency Injection) 기능을 지원함 : 클래스 내에서 다른 객체를 사용하는 것
4. 관점 지향(AOP, Aspect-Oriented Programming) 기능을 이용해 자원 관리 : 핵심 비핵심 기능을 분리해 처리
5. 영속성과 관련된 다양한 서비스를 지원함
6. 수많은 라이브러리와의 연동 기능을 지원

 

스프링의 주요 기능

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

구글 클라우드 플랫폼의 API 및 서비스를 이용한다. 프로젝트는 새로 생성해도 되고, 기본적으로 있는 프로젝트를 사용해도 된다. 기본 마커와 위치는 호주의 시드니로 설정해서 구현해보았다. 

 

 

API 사용 설정 및 중지  |  Cloud API  |  Google Cloud

API를 사용 설정하면 API가 현재 프로젝트와 연결되고, 모니터링 페이지가 추가되며, 프로젝트에서 결제가 사용 설정되어 있는 경우 해당 API에 대한 결제가 사용 설정됩니다. 참고: 프로젝트에서 결제가 사용 설정되어 있지 않은 경우에는 일부 API를 사용하지 못할 수도 있으며, API를 사용하려면 결제를 사용 설정해야 합니다. 자세한 내용은 API 및 결제를 참조하세요. API 사용 설정 프로젝트에서 API를 사용 설정하는 가장 간단한 방법은 GCP C

cloud.google.com

 

 

 

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

 


 

코드 구성 및 구현 화면

 

 

res > values 안의 xml을 수정해준다. 나머지는 수정한 부분 없음.

google_maps_api.xml

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=C2:A9:31:6B:97:C3:EF:81:A9:A6:23:C1:A7:62:C9:45:D0:AF:13:DB%3Bcom.example.googlemaptest

    You can also add your credentials to an existing key, using these values:

    Package name:
    C2:A9:31:6B:97:C3:EF:81:A9:A6:23:C1:A7:62:C9:45:D0:AF:13:DB

    SHA-1 certificate fingerprint:
    C2:A9:31:6B:97:C3:EF:81:A9:A6:23:C1:A7:62:C9:45:D0:AF:13:DB

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
        여기에 키를 입력
    </string>
</resources>

 

 

MainActivity.java

package com.example.googlemaptest;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

 

 

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemaptest">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

Gradle Scripts > build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.googlemaptest"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v