'Java' 태그의 글 목록 :: 잡다한 프로그래밍
반응형

1. 사전준비

#1) Nodejs 설치하기

https://nodejs.org/ko/에서 LTS버전을 다운받아 설치한다.

 

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

#2) yarn 설치하기

다음과 같이 yarn을 설치한다.

npm install --global yarn

 

#3) react app 생성하기

다음과 같이 리엑트 앱을 생성한다.

npx create-react-app 이름

2. 앱 실행하기

cd를 이용하여 폴더를 이동 후 다음과 같이 프로젝트를 실행한다.

yarn start

 

#1) 결과

다음과 같은 결과를 확인할 수 있다.

 

#2) App.js 수정

app.js 의 <p> 태그를 수정하고 저장하면 자동으로 compile되고 자동으로 페이지가 수정된다.

 

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> 안녕
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;


3. 결론

create react-app를 사용하게 되면 다른 server와 함께 사용할 때 처럼 webpack같은 부분이 모두 이미 포함되어있다.

반응형
반응형

1. 사전 준비

- pom.xml 수정

다음과 같은 내용을 pom.xml에 추가합니다 1. mybatis (버전은 스프링 버전에 맞게 선택 가능) 2. mybatis-spring

3.dbcp2, 4. mysql-connector 5. spring-jdbc

		<!-- MySQL -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.3</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

 

- jdbc.properties생성

WEB-INF에 properties폴더 생성 > 다음과 같은 jdbc.properties 파일 생성

jdbc.username = user_id
jdbc.password = password
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://URL/DB_NAME?serverTimezone=Asia/Seoul&useSSL=false

 

- mysql 연동

다음과 같이 root-context.xml에 추가한다 

	<!-- MySQL dataSource -->
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
    
	<!-- jdbc.properties를 찾게 해주는 placeholder -->    
 	<context:property-placeholder location="/WEB-INF/properties/jdbc.properties" />

2. mybatis 연동 및 사용

- TestModel 생성

DB로부터 받아온 데이터를 담을 Model 클래스를 생성한다

@Getter
@Setter
public class Test_Model {

	private String date;

	private int count;

}

 

- mybatis-config.xml 생성

main/resources에 다음과 같은 mybatis-config.xml을 생성한다. 등록된 모델을 test라는 별칭으로 사용할 수 있다.

<?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>
		<typeAlias type="test.main.model.Test_Model" alias="test" />
	</typeAliases>

</configuration>

 

- rmcMapper.xml 생성

main/resource에 mappers라는 패키지를 만들고 패키지 내에 다음과 같은 testMapper.xml을 생성한다.

resultType를 config.xml에 지정한 test타입으로 반환하고 사용할 쿼리의 id를 getData로 지정한다.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="test.main.mapper.testMapper">
	<select id="getData" resultType="test">
		select * FROM test_db
	</select>
</mapper>

 

- root-config.xml 수정

다음과 같이 root-config.xml에 mybatis를 설정하기 위한 위한 코드를 추가한다. mybatis-config.xml과 Mapper.xml을 bean으로 등록하고 sqlsession을 bean으로 등록한다.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:/mybatis-config.xml" />
		<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
	</bean>
	
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
	</bean>
	

3. Controller, Service, DAO 만들기

- Controller 생성

다음과 같은 Controller를 작성한다. 간단하게 getData를 해오는 코드이다.

@Controller
@RequestMapping(value = "/brokenSVC")
public class testController {
	@Autowired
	private BrokenService testService;
	
	@GetMapping(value = "test")
	public String home(Model model) {
		System.out.println(testService.getdata().get(0).getDate());
		return "testpage";
	}
}

 

- Service 생성

다음과 같은 Service를 작성한다.

@Service
public class BrokenService {

	@Autowired
	private testDAO testdao;

	public List<Test_Model> getData() {
		return testdao.getData();
	}
}

 

- DAO 생성

다음과 같은 DAO를 작성한다.

@Repository
public class BrokenDAO {
	
	@Autowired private SqlSession sqlSession;
	private static final String Namespace = "test.main.mapper.rmcMapper"; //rmcMapper가 있는 위치
	
	public List<Test_Model> getData() {
		return sqlSession.selectList(Namespace+".getData");
	}
}

4. 결론

mybatis를 사용할 경우 기존 방법은 DAO에 쿼리문이 섞여있다는 단점이 있었는데 쿼리를 완벽하게 분리하여 사용할 수 있다는 장점이 있다.

반응형
반응형

1. 스프링 시큐리티란?

  • authentication(인증) 과 authorization(권한 부여)를 제어하는 프레임워크
  • De-facto (정해진 표준은 아니지만 사실상 표준)
  • servlet filter를 기반으로함(리퀘스트를 가로채서 선처리하고 리스폰스를 가로채서 후처리함) ex)filter로 UTF-8 인코딩 가능
  • 필터로 등록된 DelegatingFilterProxy가 어떤 URL을 가로챌것인지 정한다


2. 스프링 시큐리티 실습하기 (커스텀 로그인)

 

1) pom.xml에 spring-security dependency 추가하기

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.2.1.RELEASE</version>
</dependency> 
<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.2.1.RELEASE</version
</dependency> 
<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.2.1.RELEASE</version>
</dependency>

 

2) web.xml에 filter추가

	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

 

3) security-context.xml 작성

/WEB-INF/spring/appServlet 경로에 security-context.xml을 작성한다. 먼저 name은 text, password는 test1234로 ROLE_USER를 만들고 /secured의 경로로 접근할경우 ROLE_USER인 사람만 접근할 수 있게 설정한다

<?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:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<security:authentication-manager>
		<security:authentication-provider>
			<security:user-service>
            	<security:user name="test" authorities="ROLE_USER" password="test1234"/>
            </security:user-service>
        </security:authentication-provider>
	</security:authentication-manager>


	<security:http use-expressions="true" auto-config="true">
		<security:intercept-url pattern="/secured/**"
			access="hasRole('ROLE_USER')" />
            
		<security:form-login login-page="/login" />
		<security:logout logout-url="/logout" />
	</security:http>
</beans>

 

4) web.xml 수정

다음과 같이 context-param내부에 security-context.xml경로를 추가한다

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring/root-context.xml
			/WEB-INF/spring/appServlet/security-context.xml
		</param-value>
	</context-param>

5) LoginController 작성

@Controller
public class LoginController {

  @RequestMapping(value=“/login”, method = RequestMethod.GET))
  public String login() {

  	return "login";
}

 

5) login.jsp 작성

다음과 같은 login.jsp를 작성한다 csrf 토큰값을 함께 사용하여 csfr공격에 대비한다

<form action="<c:url value="/login" />" method='POST'>

  <table>
    <tr><td>User:</td><td><input type='text' name='username' value=''></td>   </tr>
    <tr><td>Password:</td><td><input type='password' name='password' /></td>  </tr>
    <tr><td colspan='2'><input name="submit" type="submit“ value="Login" /></td> </tr>

    <input type="hidden"  name="${_csrf.parameterName}"value="${_csrf.token}"/>
  </table>

</form>

 

6) 결과

secured로 요청을 보내면 custom login form으로 요청이 전송되고 이를 지정된 ROLE_USER가 맞는지 판단함

 

7) 추가정보

로그인 실패 : /login?error로 요청이 전달됨

로그아웃 성공 : /login?logout으로 요청이 전달됨

따라서 다음과 같이 처리가능

@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(
    @RequestParam(value = "error", required = false) String error, 
    @RequestParam(value="logout", required=false) String logout, 
    Model model) {

    if (error != null) {
        model.addAttribute("errorMsg", "Invalid username and password");
    }

    if(logout != null) {
         model.addAttribute("logoutMsg", "You have been logged out successfully ");
     }

     return "login";

}

 

세션의 시간 설정 및 중복로그인 방지 방법 invalid-session-url = 세션 시간초과

max-sessions = 최대 로그인하는 수, expired-url 중복로그인시 보낼 url

	<security:session-management invalid-session-url="/login?timeout=1">
			<security:concurrency-control max-sessions="1" expired-url="/login" />
		</security:session-management>
반응형
반응형

1. AOP란?

만약 다음과 같이 Bean으로 만들 클래스 내부에 로깅, 트랜잭션, 실제 코드인 비즈니스 로직이 함께 있다고 생각해보자. 로깅, 트랜잭션, 비즈니스 로직 순서대로 작동하겠지만 이는 좋은 코드라고 할 수 없다. 따라서 로깅, 트랜잭션과 비즈니스 로직을 분리하기 위해 AOP가 존재한다

Bank 클래스

AOP는 다음 그림처럼 선처리, 후처리(런타임시 짜집기함)를 가능하게 지원하기 때문에 메인 Bean을 만드는 클래스를 따로 두고 로깅, 트랜잭션을 선처리 후처리로 다음과 같은 구조를 만드는 것이다.

 

다음 그림처럼 a.f()가 실직적인 타겟이되는 joinpoint가 되고 그림 앞에 보라색, 주황색이 선처리 후처리를 담당하는 어드바이스가 된다. 어드바이스는 joinpoint는 Pointcut이 가리키게 된다

다음 그림을 보면 조금더 이해하기 쉽다

AOP 구조 설명


2. AOP실습

#1) spring-aspect를 이용한 실습

1. pom.xml dependency추가

다음과 같은 디펜던시를 추가하면, Maven Dependencies에 spring-aspects라이브러리가 추가된 것을 확인할 수 있다.

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>4.2.5.RELEASE</version>
		</dependency>

 

2. Logger 클래스 추가

다음과 같은 Logger클래스를 추가한다.

public class Logger{
	public void aboutToSound() {
		System.out.println("Before: about to sound");
	}
}

 

3. animal.xml Namespaces 수정 및 aop추가

다음과 같이 Namespaces에 aop를 추가한다

aop 추가

aop추가를 완료하였다면 다음과 같은 코드를 추가한다 <aop:aspect ref="Logger">를 통해 Logger클래스를 Aspect로 이용하겠다는 의미이며, <aop:pointcut expression="execution(void kr.ac.hansung.helloDI.*.sound())" id="selectSound" />를 통해 helloDI패키지의 sound() 함수를 joinpoint로 지정하겠다는 의미이다. 이때 *은 와일드카드로서 어떤 클래스든 상관없다는 의미를 가진다. <aop:before method="aboutToSound" pointcut-ref="selectSound" />는 before어드바이스를 추가하겠다는 의미로 aboutToSound라는 메서드를 이용하며 ref로는 위에 선언한 pointcut의 id를 가진다. 따라서 pointcut은 jointpoint를 가르키고 advice는 그 pointcut을 가리킨다

	<aop:config>
		<aop:aspect ref="Logger" id="myAspect">
			<aop:pointcut
				expression="execution(void kr.ac.hansung.helloDI.*.sound())"
				id="selectSound" />
			<aop:before method="aboutToSound"
				pointcut-ref="selectSound" />
		</aop:aspect>
	</aop:config>

 

4. 실행

메인 함수를 실행하면 다음과 같은 결과를 확인할 수 있다. 메인 함수에서는 Logger빈을 사용하지 않았지만 다음과 같이 before advice가 실행된 것을 확인할 수 있다.

실행

 

#2) AOP 에노테이션을 이용한 실습

1. animal.xml수정

다음과 같이 animal.xml을 수정한다 기존 코드를 주석 처리하고 <aop:aspectj-autoproxy>를 추가함으로 에노테이션을 사용하겠다고 명시한다.

<!-- 	<aop:config>
		<aop:aspect ref="Logger" id="myAspect">
			<aop:pointcut
				expression="execution(void kr.ac.hansung.helloDI.*.sound())"
				id="selectSound" />
			<aop:before method="aboutToSound"
				pointcut-ref="selectSound" />
		</aop:aspect>
	</aop:config> -->

	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

 

2. Logger 클래스 수정

다음과 같이 Logger 클래스를 수정한다 @Aspect로 클래스가 Aspect라는 걸 명시하고 @Pointcut을 통해 sound() 메서드를 joinpoint로 지정하겠다는 것을 명시하고 @Before로 이전 어드바이스를 추가한다.

@Aspect
public class Logger{
	
	@Pointcut("execution(void kr.ac.hansung.helloDI.*.sound()")
	private void selectSound() {}
	
	@Before("selectSound()")
	public void aboutToSound() {
		System.out.println("Before: about to sound");
	}
}

 

3. 실행

모두 완료하였다면 다음과 같은 실행화면을 볼 수 있다

실행화면

반응형
반응형

1. Annotation이란?

앞 강의에서 DI란 무엇인지와 생성자를 이용하여 의존성 주입을 하는 방법을 실습해 보았다면 이번 강의에서는 Annotation을 이용하여 의존성 주입을 해볼 예정이다.

먼저 에노테이션이란 기존 XML을 이용하여 의존성 주입을 하는 것이 아닌 @Required 같은 태그를 이용하여 의존성 주입을 하는 것을 의미한다. 의존성 주입 에노테이션으로는 다음과 같은 3가지가 있다

 

#1 @Required

XML의 Bean의 property에 해당하는 부분 중 필수적인 부분을 명시할 때 다음과 같이 사용한다. 쉽게 말해 XML에 bean중 property가 꼭 있어야 하니 없으면 에러가 발생한다고 생각하면 좋다 즉 @required를 사용할때 xml에 property에 name에 해당하는 부분이 반드시 있어야 에러가 발생하지 않는다.

public class Boy{
private String name;

@required
public void setName(String name){
  this.name = name;
  }
  
}

 

#2 @Autowired

이전 강의에서 의존성 주입을 할 때 bean에 property를 사용하여 세터를 통한 주입을 했었다. 하지만 Class의 기존 세터 부분을 지우고 @Autowired 에노테이션을 추가하면 자동으로 의존성 주입이 이루어진다. 이는 다음 코드처럼 Boy클래스는 property를 사용하여 세터를 통해 bean을 생성했고 college라는 bean은 propery를 통해 boy라는 bean을 의존성 주입 했지만 College클래스에 @Autowired 에노테이션을 추가하고 세터부분을 지우고, 마찬가지로 bean의 property부분을 지우면 자동으로 의존성 주입이 이루어지는것을 확인할 수 있다.

public class Boy {
 private String name;
 private int age;
   
 //   getters and setters ...
}

public class College {
 
 @Autowired
 private Boy student; 
 
 //이부분부터
 public void setStudent(Boy aboy){
  this.stuendt = aboy;
 }
 //이부분까지 삭제
 
}

<bean id=“boy” class=“Boy”>
 <property name=“name” value=“Rony”/>
 <property name=“age” value=“10”/>
</bean>

<bean id=“college” class=“College”>
  <property name=“student” ref=“boy”/> //이부분 삭제
</bean>

 

#3 @Qualifier

만약 Autowired를 할때 다음과 같이 Boy 클래스의 bean이 두 개 있으면 어떤 걸 자동으로 Autowired를 할지 몰라 오류가 생긴다 따라서 이럴 때 @Qualifier를 사용한다. 다음과 같이 bean에는 qualifer의 value를 지정하고 Class에는 @Qualifier의 에노테이션과 함께 value를 설정하면 어떤 bean을 주입할지 정하게 된다

<bean id=“boy1” class=“Boy”>
 <qualifier value=“rony”/>
 <property name=“name” value=“Rony”/>
 <property name=“age” value=“10”/>
</bean>

<bean id=“boy2” class=“Boy”>
 <qualifier value=“tony”/>
 <property name=“name” value=“Tony”/>
 <property name=“age” value=“8”/>
</bean>

<bean id=“college” class=“College”>
</bean>


public class College {
 
@Autowired
@Qualifier(value=“tony”)
 private Boy student; 
 
  //   getters ...
}

 

#4 @Resource

@Qualifer가 value를 지정해서 의존성 주입을 시켜줬다면 Resource는 bean의 id로 의존성 주입을 해준다. 다음과 같이 사용할 수 있다.

public class College {
  
  @Resource(name=“boy1”)
  private Boy student; 
 
  //   getters and setters ...
}

 

#5 @Component

 

@Component는 Bean.xml에 빈을 사용한다 명시 하지 않아도 자동으로 클래스를 Bean으로 만들어주는 에노테이션이다

@Component
public class College {
  
  private Boy student; 
 
  //   getters and setters ...
}

2. Annotation 실습

실습할 예제는 이전 DI강의에서 사용했던 프로젝트로 실습하겠습니다.

#1) animal.xml수정

먼저 animal.xml을 다음과 같이 수정합니다. 생성자로 주입했던 constructor-arg 부분을 지워 주고 애노테이션을 사용한다는 코드를 추가합니다

<?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 http://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">
	<context:annotation-config></context:annotation-config>
	
	<bean id="dog" class="kr.ac.hansung.helloDI.Dog">
		<property name="myName" value="poodle"></property>
	</bean>

	<bean id="cat" class="kr.ac.hansung.helloDI.Cat">
		<property name="myName" value="bella"></property>
	</bean>

	<bean id="petOwner" class="kr.ac.hansung.helloDI.PetOwner">
		<constructor-arg ref="dog"></constructor-arg>
	</bean>
</beans>

 

#2)  @Autowired추가

PetOwner.java클래스의 생성자 부분을 지우고 다음과 같이 @Autowired에노테이션을 추가합니다

package kr.ac.hansung.helloDI;

import org.springframework.beans.factory.annotation.Autowired;

public class PetOwner {
	
		@Autowired
		private AnimalType animal;

		public void play() {
			animal.sound();
		}
}

다음과 같이 코드를 수정하고 Run 하게 되면 다음과 같은 에러가 발생하는 것을 확인할 수 있습니다. 앞서 공부한 것처럼 2개의 bean 중 어떤 bean을 주입할지 모르기 때문에 다음과 같은 error가 발생하는 것입니다. 따라서 2가지 방법을 통해 해결해보도록 하겠습니다.

error

#3) @Qualifier추가 및 animal.xml수정

다음과 같이 Qualifier에노테이션을 사용하여 다음과 같이 어떤 빈을 주입할지 선택합니다.

 

PetOwner.java

package kr.ac.hansung.helloDI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class PetOwner {
	
		@Autowired
		@Qualifier(value="cat")
		private AnimalType animal;

		public void play() {
			
			animal.sound();
		
		}
}

 

animal.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 http://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">
	<context:annotation-config></context:annotation-config>
	
	<bean id="dog" class="kr.ac.hansung.helloDI.Dog">
		<property name="myName" value="poodle"></property>
		<qualifier value="dog"></qualifier>
	</bean>

	<bean id="cat" class="kr.ac.hansung.helloDI.Cat">
		<property name="myName" value="bella"></property>
		<qualifier value="cat"></qualifier>
	</bean>

	<bean id="petOwner" class="kr.ac.hansung.helloDI.PetOwner">
	</bean>
</beans>

 

#4) 실행

수정을 완료하였다면 다음과 같은 실행 결과를 확인할 수 있다.

qualierfier 실행 성공

 

#5) @Resource 추가 및 animal.xml수정

@Qualifier대신 Resource에노테이션을 사용해보자 다음과 같이 animal.xml을 수정한다

 

PetOwner.java

package kr.ac.hansung.helloDI;
import javax.annotation.Resource;

public class PetOwner {
		@Resource(name="dog")
		private AnimalType animal;

		public void play() {
			
			animal.sound();
		
		}
}

 

animal.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 http://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">
	<context:annotation-config></context:annotation-config>
	
	<bean id="dog" class="kr.ac.hansung.helloDI.Dog">
		<property name="myName" value="poodle"></property>
	</bean>

	<bean id="cat" class="kr.ac.hansung.helloDI.Cat">
		<property name="myName" value="bella"></property>
	</bean>

	<bean id="petOwner" class="kr.ac.hansung.helloDI.PetOwner">
	</bean>
</beans>

 

#6) 실행

수정을 완료하고 실행하면 다음과 같은 결과를 확인할 수 있다.

Resource 성공


3. 정리

@Autowired를 사용하여 bean의 의존성 주입을 하며, 여러 빈이 있을 경우 Qualifier에노테이션을 사용하여 빈을 선택하거나, bean의 id를 통해 의존성 주입을 하는 @Resource 에노테이션을 사용할 수 있다.

반응형
반응형

1. DI(Dependency Injection)란?

DI는 말 그대로 의존성을 주입한다 라는 뜻이다. 쉽게 설명하면 JAVA에서 객체를 new를 이용하여 생성하는데 이렇게 사용하지 않고 외부에서 생성한 객체를 세터 또는 생성자를 통해 사용하겠다는 의미이다. 이를 의존성 주입이라 한다. 의존성 주입 방법에는 세터를 이용하거나 생성자를 이용한 방법 두가지가 있다. 예제로는 생성자를 이용한 방법으로 예제를 공부하겠다

DI 사용하지 않은 예시

그림처럼 DI를 이용하지 않고 new를 사용하여 객체를 생성하게 되면 PetOwner와 Dog간 강한 결합이 생기게 되어 도그를 수정하면 PetOwner가 수정될 수 있다.

 

DI

반면 다음과 같이 Bean Container를 이용하여 객체를 생성하고 의존성 주입을 시켜주면 결합이 강하지 않다는 장점이 생긴다. 이때 Bean Container는 XML로 이루어져 있다.

DI 설명

다음 그림처럼 메인함수에서는 ApplicationContext라는 BeanContainer를 생성하고 미리 작성된 xml에 따라 ApplicationContext는 Dog, Cat, PetOwner라는 객체를 생성하고 Dog, Cat을 PetOwner에 의존성 주입한다. 스프링은 new방식 대신 DI방식을 권장한다.


2. 의존성 주입 실습

#1 프로젝트 생성

File > New > Spring Legacy Project를 클릭하고 다음과 같은 Simple Spring Maven 프로젝트를 생성한다. 프로젝트명은 원하는 프로젝트명을 사용해도 무방하다. 이 실습에서는 helloDI라는 프로젝트명을 사용하겠다.

프로젝트 생성

#2 AnimalType, Cat, Dog 생성하기

src/main/java에 클래스와 인터페이스를 담을 패키지를 생성한다 패키지명은 자유로워도 좋다. 패키지를 생성하였다면 패키지 아래에 AnimalType.java라는 인터페이스를 생성한다

인터페이스 코드는 다음과 같다 인터페이스를 implements할 cat, dog클래스들이 사용할 sound라는 메소드를 정의하고 있다.

 

AnimalType.java

package kr.ac.hansung.helloDI;

public interface AnimalType {

	public void sound();

}

 

다음으로 Cat.java라는 클래스를 생성한다. 게터와 세터가 만들어져 있으며 AnimalType의 sound메소드를 사용하고 있다.

 

Cat.java

package kr.ac.hansung.helloDI;

public class Cat implements AnimalType {

	public String getMyName() {
		return myName;
	}

	public void setMyName(String myName) {
		this.myName = myName;
	}

	private String myName;

	@Override
	public void sound() {
		
		System.out.println("Cat name = " + myName + ":" + "Meow");
	}

}

 

마지막으로 Dog.java라는 클래스를 생성한다. 게터와 세터가 만들어져 있으며 AnimalType의 sound메소드를 사용하고 있다.

 

Dog.java

package kr.ac.hansung.helloDI;

public class Dog implements AnimalType {

	public String getMyName() {
		return myName;
	}

	public void setMyName(String myName) {
		this.myName = myName;
	}

	private String myName;

	@Override
	public void sound() {
		
		System.out.println("Dog name = " + myName + ":" + "Bow Wow");
	}

}

 

#3 PetOwner클래스 생성하기

petOwner클래스는 AnimalType의 animal을 받는다 이는 cat이나 dog를 받아서 사용하겠다는 의미이고 play라는 메소드와 생성자를 정의했다.

 

PetOWner.java

package kr.ac.hansung.helloDI;

public class PetOwner {

		private AnimalType animal;

		public PetOwner(AnimalType animal) {
			this.animal = animal;
		}
		
		public void play() {
			
			animal.sound();
		
		}
}

 

#4 animal.xml 생성하기

Bean Container가 생성하기 위해 참고할 xml파일을 생성한다 코드는 다음가 같다.

<bean id = "dog"> 부분이 dog라는 클래스의 객체를, <bean id = "cat"> 부분이 cat이라는 클래스의 객체를 <bean id = petOwner"> 부분이 petOwner의 객체를 생성하고 <constructor-arg ref = "dog">는 dog객체를 의존성 주입하겠다 라는 의미이며, <property name="myName" value="poddle">는 도그의 myName의 값을 poodle로 주겠다는 의미이다.

 

animal.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="dog" class="kr.ac.hansung.helloDI.Dog">
		<property name="myName" value="poodle"></property>
	</bean>

	<bean id="cat" class="kr.ac.hansung.helloDI.Cat">
		<property name="myName" value="bella"></property>
	</bean>

	<bean id="petOwner" class="kr.ac.hansung.helloDI.PetOwner">
		<constructor-arg ref="dog"></constructor-arg>
	</bean>
</beans>

 

#5 MainApp.java작성

마지막으로 메인 함수인 MainApp.java를 다음과 같이 작성한다. ApplicationContext가 animal.xml을 바라보게 하고

petOwner의 person이 context의 getBean함수를 통해 객체를 가져와 사용하는 모습이다.

package kr.ac.hansung.helloDI;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

	public static void main(String[] args) {

		ClassPathXmlApplicationContext context = 
				new ClassPathXmlApplicationContext("/kr/ac/hansung/helloDI/conf/animal.xml");
		
		PetOwner person = (PetOwner) context.getBean("petOwner");
		person.play();
		
		context.close();
	}

}

 

#5 프로젝트 Run

프로젝트를 Run 하게 되면 다음과 같은 결과를 확인할 수 있다.

결과화면

 

사용자는 animal.xml에서 정의한 대로 dog, cat, petOwner의 객체를 먼저 생성하고, 이후 dog를 petOwner에 주입하였으니 결과 화면에는 dog가 보이게 된다 만약 cat을 주입하고 싶다면 constructor-arg의 ref = cat으로 수정해주면 된다

반응형
반응형

1. MVC 아키텍처란?

  • Model(Java Beans) 객체로 생각, 데이터를 나타냄
  • View (JSP) 사용자가 상태를 볼 수 있는 View page를 의미
  • Controller (Servlet) 뷰와 모델 사이에서 실질적으로 request를 처리하는 부분

MVC패턴

그림과 같은 MVC패턴은 다음과 같은 5가지 단계로 진행된다

1) 브라우저의 request를 Servlet으로 전달함

2) 객체를 생성하여 서블릿의 결과를 저장함

3) view페이지를 선택함

4) JSP 페이지에 객체를 전달함

5) JSP 페이지를 브라우저에 Response 함


2. MVC 패턴 실습하기

MVC패턴을 실제 프로젝트로 실습해 보자.

 

#1 프로젝트 생성

https://diqmwl-programming.tistory.com/18?category=740999의 프로젝트 생성 부분을 참고하여 MVCexample이라는 프로젝트를 생성한다

 

#2 index.jsp생성

다음 그림과 같이 WebContent폴더에 index.jsp를 생성한다

index.jsp생성

 

생성한 index.jsp는 로그인하기, 도움말이라는 링크를 제공하는 페이지로 다음과 같은 코드를 작성한다.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>MVC Example</title>
</head>
<body>
MVC 예제 페이지 입니다.
	<p><a href="/MVCexample/home?action=login"> 로그인하기 </a></p>
	<p><a href="/MVCexample/home?action=help"> 도움말 </a></p>

</body>
</html>

 

코드를 생성하고 프로젝트를 실행한다면 index.jsp는 다음과 같이 실행된다.

index.jsp 실행

 

#3 Home 서블릿 생성

파일 작성을 완료하였다면 로그인하기, 도움말의 링크를 처리하기 위한 Home이라는 Servlet을 생성하기 위해 MVCeample >> Java Resources >> src >> controller라는 패키지를 생성한다.

패키지 생성을 완료하였다면 아래 그림과 같이 Home이라는 Servlet을 생성한다

서블릿 생성 1

 

index.jsp의 링크가 home으로 되어있으므로 URL Mapping을 다음과 같이 /home로 수정한다

서블릿 생성 2
서블릿 생성 3

서블릿 생성이 완료되었다면 다음과 같이 코드를 작성한다.

코드를 살펴보면 action이라고 request 받은 데이터를 String action에 저장하고 이 값이 login일 경우 view폴더의 loginform.jsp를, help일 경우 help.jsp, 이외의 경우는 error.jsp를 경로로 저장하게 된다.

이후 RequestDispatcher을 이용하여 설정한 경로로 forward 시켜주는 방식이다

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Home
 */
@WebServlet("/home")
public class Home extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Home() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		String page = null;
		
		if(action.equals("login")) {
			page = "/view/loginform.jsp";
		}
		else if(action.equals("help")) {
			page = "/view/help.jsp";
		}
		else {
			page = "/view/error.jsp";
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(page);
		dispatcher.forward(request, response);
	}

}

 

#4 view폴더, loginform.jsp, help.jsp error.jsp 생성

코드를 작성하고 현재 view 폴더와 loginform.jsp, help.jsp, error.jsp를 만들지 않았으므로 생성해주도록 한다.

먼저 WebContent 아래에 view라는 폴더를 생성시킨다. 이후 아래 그림처럼 loginform.jsp, help.jsp, error.jsp를 생성하고 다음과 같은 코드를 작성한다

view 폴더 구성

loginform.jsp

//loginform.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>
This is Login Page.

<form action="/MVCexample/doLogin" method="get">
	customer ID(id1, id2, id3, id4, id5)<br/>
	<input type="text" name="customerId"/> <br/>
	
	<input type="submit" value="submit"/> <br/>
</form>
</body>
</html>

 

help.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>
This is help Page.
</body>
</html>

 

error.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>
This is error Page.
</body>
</html>

모두 작성을 완료하였다면 index.jsp에서 링크를 클릭 시 다음과 같이 forward 된 것을 확인할 수 있다.

loginform.jsp

 

#5 Model 작성

loginform에서 사용자가 입력하는 id의 실질적인 객체를 만들기 위해 Model을 생성한다 먼저 MVCexample >> Java Resources >> src >> model 패키지를 생성한다. 이후 아래 사진과 같이 Customer 클래스를 생성한다

 

model 생성

생성한 Class의 코드는 다음과 같다 id, name, email을 가지고 있으며 Customer이라는 생성자와, 각각의 게터, 세터 메소드가 정의되어있다.

package model;

public class Customer {

	private String id;
	private String name;
	private String email;
	
	public Customer(String id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
}

 

#6 Service 생성

실제로 만든 모델에 데이터를 저장하거나, 데이터를 읽어오거나 하는 함수들이 정의된 서비스이다. 사용자의 요청이 들어왔을 때 서블릿에서 이를 처리하는 함수를 구현해도 상관없으나 Service로 분리하여 보다 보기 좋은 코드를 구현한다

model 생성과 같은 방법으로 MVCexample >> Java Resources >> src >> service 패키지를 생성한다. 이후 다음 그림처럼 CustomerService 클래스를 생성한다

service 생성

실제 코드는 다음과 같다. 먼저 CustomerService를 생성하면 customers라는 Map을 생성한다 이때 String은 id, 값으로는 Customer 모델을 받고 customers 객체가 생성될 때 id1~id5의 정보를 미리 저장해 놓는다. 또한 DoLogin 서블릿에서 사용할 findCustomer함수를 정의한다 이는 검색한 아이디가 있을 경우 id의 cusomer을 반환하고 없을 경우 null을 반환한다.

 

package service;

import java.util.HashMap;
import java.util.Map;

import model.Customer;

public class CustomerService {
	
	private Map<String, Customer> customers;

	public CustomerService() {
		customers = new HashMap<String, Customer>();
		
		addCustomer( new Customer("id1", "test1", "test1@naver.com"));
		addCustomer( new Customer("id2", "test2", "test2@naver.com"));
		addCustomer( new Customer("id3", "test3", "test3@naver.com"));
		addCustomer( new Customer("id4", "test4", "test4@naver.com"));
		addCustomer( new Customer("id5", "test5", "test5@naver.com"));
	}
	
	public void addCustomer(Customer customer) {
		customers.put(customer.getId(), customer);
	}
	
	public Customer findCustomer(String id) {
		if(id != null) {
			return (customers.get(id.toLowerCase()));
		}
		else{
			return null;
		}
	}
	
}

 

#6 DoLogin 서블릿 작성

loginform.jsp에서 사용자가 정해진 id를 입력하면 이를 실질적으로 처리할 서블릿인 DoLogin 서블릿을 생성한다.

다음 그림과 같이 URL Mapping을 /doLogin으로 생성한다.

DoLogin 서블릿 생성

DoLogin의 코드는 다음과 같다. loginform.jsp에서 사용자가 입력한 customerId의 값을 저장하고

CustomerService의 객체를 선언한다. 다음으로 findCustomer함수를 사용하여 사용자가 입력한 결과를 Customer라는 Model객체에 저장하여 이를 setAttribute라는 함수를 통해 customer라는 이름으로 저장하여 success.jsp로 forward 한다.

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 model.Customer;
import service.CustomerService;

/**
 * Servlet implementation class DoLogin
 */
@WebServlet("/doLogin")
public class DoLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String customerId = request.getParameter("customerId");
		
		CustomerService service = new CustomerService();
		Customer customer = service.findCustomer(customerId);
		request.setAttribute("customer", customer);
		
		String page;
		if(customer == null) {
			page = "/view/error.jsp";
		}
		else {
			page = "/view/success.jsp";
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(page);
		dispatcher.forward(request, response);
	
	}

}

 

#7 success.jsp생성

view폴더에 success.jsp를 생성하고 다음과 같은 코드를 작성한다. ${}는 JSP EL으로서 변수를 사용하는 방법이다.

넘겨받은 customer를 다음과 같이 화면에 출력하는 코드이다

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>
This is Login Success page.

<ul>
<li> Name : ${customer.id }</li>
<li> Name : ${customer.name }</li>
<li> Name : ${customer.email }</li>
</ul>
</body>
</html>

모두 완료하였을 경우 다음과 같은 결과 화면을 확인할 수 있다

success.jsp

반응형
반응형

1. JSP란?

Java Server Pages로서 정적 HTML과 동적인 컨텐츠를 섞어놓은 기술 서블릿 처럼 동적인 페이지를 기술 할 수 있다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
<LINK REL=STYLESHEET
	HREF="JSP-Style.css"
    TYPE="text/css">
</HEAD>
<BODY>
Thanks for ordering <%= request.getParameter("title") %>!
</BODY>
</HTML>

다음은 JSP예시이다. <%= request.getParameter("title")%> 부분이 HTML 내부에 동적인 JAVA코드가 삽이되어있는 부분이다. JSP 가 실행되면 서블릿(Servlet) 으로 변환되며 웹 어플리케이션 서버에서 동작되면서 필요한 기능을 수행하고

그렇게 생성된 데이터를 웹페이지와 함께 클라이언트로 응답한다.


2. JSP 와 Servlet의 차이

JSP는 HTML 내부에 JAVA코드를 넣어 처리하고 Servlet은 JAVA코드내에 HTML을넣어 표시한다. 따라서 Servlet은 JSP보다 코드를 읽고 사용하기에 불편하다는 단점이 존재한다 따라서 Servlet은 데이터를 프로세싱 하기에 적합하고, JSP는 데이터를 보여주기에 적합하다


3. JSP 문법

1) JSP Expression

<%= 내용 %> 으로서 out 객체를 통해 print해주는 역할을 한다.

 

2) JSP Scriptlets

<% Java Code %> 로서 좀 더 복잡한 기능 구현을 하고 싶다면 <%  %>사이에 JAVA코드를 넣어서 사용가능하다

ex) <% if(a == 1) out.println("aa"); %>

 

3) JSP Declarations

<%! private int count = 0; %> 처럼 필드, 메소드를 정의하는 방법이다. 사용자는 정의한 count 를

<%= count %>를 통해 출력하거나 사용할 수 있다.

 

4)JSP Directive

JSP전체 구조에 영향을 미친다

JSP 서블릿 컨테이너에 지시를 하는 역할을한다

 

#1 page Directive

페이지 지시는 JSP페이지의 가장 위에 적어주며  import하거나 페이지에 명령을 내리는곳에 사용한다

<%@ page import = "java.util.*" %>

<%@ page contentType = "text/html" %>

 

#2 include Directive

<%@ include file = "test_url"> 모든 페이지 하단부에 있는 주소같은 부분을 복사 붙여넣기 하여 사용하는것은 좋지않은 방법이다 따라서 이러한 include를 통하여 사용하는것이 좋다.

 

#3 taglib Directive

태그를 모아놓은 라이브러리로서 외부의 라이브러리 파일을 JSP내에 HTML이나 XML태그처럼 사용할 수 있게 함

<%@ taglib   uri=http://java.sun.com/jsp/jstl/core    prefix=c"  %> 이처럼 prefix로 c라고 등록해놓고 사용

<c:out value="Hello World"> </c:out>

 

5) JSP Action

XML 구분의 문법을 사용하여 서블릿 엔진을 컨트롤한다

 

#1 <jsp:include>action

현재 JSP 페이지에 다른 리소스를 포함시키는데 사용.

<jsp:include page="/jsp/common/uppermenu.jsp" flush="true">

</jsp:include>

 

#2 <jsp:forward>action

다른 리소스(JSP, html 또는 Servlet)로 요청을 전달하는데 사용.

<jsp:forward page=“/display.jsp" />

 

#3 <jsp:useBean>action

자바의 Bean(객체)를 생성한다.

<jsp:useBean id="customer" class=“package.class  scope="request"> </jsp:useBean>

Scope = 언제까지 유효한지를 의미 Request오면 만들고 끝나면 사라짐

 

#4 <jsp:setProperty>action

자바 Bean(객체)의 속성을 정의한다

<jsp:setProperty name="myName" property="someProperty" value=“abc”/>

 

#5 <jsp:getProperty>action

자바 Bean(객체)의 값을 가져온다

<jsp:getProperty name="myName" property="someProperty" />

반응형

+ Recent posts