160527: 52회차
종료하기 전 티스토리 네이버 로그아웃 할 것
1. 툴
동일
추가시:
2. 폴더
동일
추가시:
3. 사용할 사이트
동일
추가시:
4. 공부하는 것
- Annotation 설정은 코드에 설정정보를 입력함으로써 설정파일을 사용하지 않거나
설정파일 크기를 줄이는데 유용합니다.
- @Autowired - 의존하는 객체 주입 (필드,메소드/setter,생성자 에서 사용)
- @Resource - 의존하는 객체 주입(필드,setter 에서 사용)
- @PostConstruct - 객체 생성후 호출
- @PreDestroy - 객체가 소멸되기 바로전 호출
- @Qualifier - 자동설정 제한하며, 수식어를 값으로 가짐
- @Required - 필수 프로퍼티를 명시 (setter 메소드에서 사용)
1. Annotation 예제 확인
- 스프링 프로젝트의 설정
Project Type: Spring Project --> Simple Spring Utility Project
Name: AnnoTest
Package: spring.sts.annotation
Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드
됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다.
packate: spring.sts.annotation
import javax.annotation.PostConstruct;
import org.springframework.context.support.AbstractApplicationContext;
>>>>>> annotation.xml
- @Component - @Repository, @Service 를 포괄적으로 사용
- @Controller - @Component가 대신 사용될수 없음

- @Service - business logic 의 서비스 패턴 클래스 에서 사용
- @Repository - database access logic의 DAO 패턴 클래스 에서 사용
[02] xml설정파일에 등록없이 빈으로 사용가능한 스캔
1. <context:component-scan>
- @Component, @Service, @Controller가 적용된 클래스를 자동으로 등록해줍니다.
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="spring.sts.annotation.*" />
</beans>
2. <context:include-filter>
<context:exclude-filter>
- 자동스캔대상에 포함시킬 클래스와 포함시키지 않을 클래스를 구체적으로
명시할 수 있습니다.
<context:component-scan base-package="sts.hello.semple">
<context:include-filter type="regex" expression="
.*Mgr"/>
<context:exclude-filter type="aspectj" expression="
..*Mgr"/>
</context:component-scan>
- regex:정규표현식
- aspectj:Aspectj표현식
@Controller - 클래스 타입에만 적용되며,웹 요청처리에 사용
@RequestMapping - 컨트롤러가 처리할 요청 URL을 명시하는데 사용(클래스,메소드)
1) 컨트롤러 메소드의 매개변수(파라메터) 타입

2) 컨트롤러 메소드의 리턴값 타입

@PathVariable - Parameter를 URL형식으로 받기
ex) 1)일반 get방식으로 서버에서 값 확인
http://127.0.0.1:8000/test?menu=board


2) @PathVariable 를 이용하여 서버에서 값 확인
http://127.0.0.1:8000/test/board


@RequestParam - Form페이지에서 넘어오는 파라메터를 받을수 있다.
- key=value 형태로 넘어오는 파라미터를 맵핑 된 메소드의 매개변수
값으로 설정
1) 해당 파라미터가 없다면 HTTP 400 - Bad Request 가 전달 된다.
2) file의 경우는 <input type="file" name="file" /> 에 매핑 된다.
public String edit( @RequestParam("id") int id,
@RequestParam("title") String title,
@RequestParam("file") MultipartFile file ) {...}
3) 맵 형태로 받으면 모든 파라미터 이름은 맵의 키에 파라미터 값은 맵의 값에
담긴다.
public String add( @RequestParam Map<String, String> params ) {...}
4) 파라미터가 필수가 아니라면 required = false 로 지정하면 된다.
이때 파라미터가 없으면 NULL이 들어간다. default 값을 지정 할 수도 있다.
public void view( @RequestParam(value = "id",
required = false,
defaultValue = "0" ) int id) {..}.
@ModelAttribute - 파라미터를 Object(DTO) 형태로 받을때 사용
ex) public void update( @ModelAttribute("board") Board board) {...}
@SessionAttributes - 세션상에서 model의 정보를 유지하고 싶을 경우 사용
@RequestBody - HTTP body 부분만 전달 한다. XML 이나 JSON 으로 출력 할
경우 사용
@Value
1) 프로퍼티값이나 properties파일의 값을 필드나 파라미터에 적용한다.
@Value("${eng.url}")
String engUrl;
@RequestMapping(..)
public String gotoEng() {
return this.engUrl;
}
}
2) 위는 프로퍼티중 eng.url 의 값을 String engUrl에 매핑 시켰으며 메소드의
파라미터에도 적용 된다.
return engUrl;
}
3) Project Type: Spring Project --> Simple Spring Utility Project
Name: ValueTest
Package: spring.annotation.value
Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드
됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다.
>>>> ExampleService .java
package spring.annotation.value;
>>>>>> Test.java
[02] @MVC 기반 Spring MVC 프로젝트
1.Project Type: Spring Project --> Spring MVC Project
Name: mvc_book
Package: spring.mvc.book
Library: 프로젝트 생성시 관련 Spring 라이브러리가 자동으로 다운로드
됩니다. 작업 컴퓨터는 인터넷에 연결되어 있어야 합니다.
- 프로젝트 구성
/mvc_book/src/main/java : Java class 저장 폴더
/mvc_book/src/main/webapp/resources : CSS, JS, Image등의 리소스
/mvc_book/src/main/webapp/WEB-INF : Web 환경 설정
/mvc_book/src/main/webapp/WEB-INF/spring : Spring 환경 설정
/mvc_book/src/main/webapp/WEB-INF/views : Spring jsp file
>>>> web.xml (한글처리용 필터추가)
:
:
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
:
:
>>>> BookCon.java
package spring.mvc.book;
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.servlet.ModelAndView;
import java.text.DecimalFormat;
@Controller
@RequestMapping("/book.s3")
public class BookCon {
public BookCon(){
System.out.println("BookCon 객체 생성" );
}
@RequestMapping(method=RequestMethod.GET)
protected ModelAndView execute(Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("/book/form"); // form.jsp
return mav;
}
@RequestMapping(method=RequestMethod.POST)
protected ModelAndView execute(String bookname, String name, String publisher, int pay) {
DecimalFormat df = new DecimalFormat("###,###,###");
}
>>>>src/main/webapp/WEB-INF/spring/appServlet/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 http://www.springframework.org/schema/mvc/spring-mvc.xsd
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.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="/**" location="/" />
<!-- 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="spring.mvc.book" />
</beans:beans>
>>>>>>src/main/webapp/book/images/logo_kyobo.gif
- 홈페이지에서 다운로드
>>>>>src/main/webapp/WEB-INF/views/book/form.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE> 도서 주문 신청 </TITLE>
</HEAD>
<BODY>
<img src="${pageContext.request.contextPath}/book/images/logo_kyobo.gif" width="20%">
<br><br>
[[ 도서 주문 신청 ]]<br>
<form name="frmCreate"
action="./book.s3"
method="post">
책 제목:<input type="text" name="bookname" value="개구리의 기도" style="width: 252px; "/><br>
저자 : <input type="text" name="name" value="앤서니 드 멜로"/><br>
출판사 : <input type="text" name="publisher" value="분도"/><br>
가격 : <input type="text" name="pay" value="12000"/><br>
<input type="submit" name="btnSubmit" value="주문" />
</form>
</BODY>
</HTML>
>>>>>src/main/webapp/WEB-INF/views/book/proc.jsp
2. 서비스 파일의 생성 확인
D:/rfid02/spring/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mvc_book/resources 폴더에
JSP 관련 파일이 통합되어 들어감
[03] Local 저장소의 변경
- 메이븐은 기본적으로 저장소를 운영체제의 계정을 따라 생성된다.
'C:/Users/STU/.m2' 하지만 이경로는 개발환경이 바뀌면 불편함으로 수동으로
저장소를 지정할 수 있다.
- 기본 경로에있는 jar 파일이 인식이 안되는 경우 인식이됨.
- 라이브러리를 운영체제로부터 분리하여 이동가능.
1. Maven 설정 파일의 생성
>>>>> F:/eGov/spring/maven/settings.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository> F:/eGov/spring/maven</localRepository>
<interactiveMode>true</interactiveMode>
<usePluginRegistry>false</usePluginRegistry>
<offline>false</offline>
<pluginGroups>
<pluginGroup>org.codehaus.mojo</pluginGroup>
</pluginGroups>
</settings>
2. Eclipse 설정
Eclipse STS -> Window -> Preferences -> Maven -> User Settings
- User Settings: settings.xml
3. STS를 재시작하면 새로운 저장소로 jar를 다운 받는다.
4. 실행
http://localhost:8000/book/home
1) 최초 프로젝트 생성시 마지막 패키지 이름이 URL Path(Root Context Path)으로 지정
Package: sts.mvc.book
URL: http://localhost:8089/book/
[참고] 변경이 필요한경우
Servers --> Tomcat v7.0 Server at localhost-config --> server.xml
<Context docBase="sts_mvc" path="/book" reloadable="true" source="org.eclipse.jst.jee.server:sts_mvc_book"/></Host>
부분의 path 속성의 값을 path="/bookcbd" 부분을 변경
URL: http://localhost:8000/bookcbd/
-------------------------------------------------------------------
--------------------------------
maven->user settings
경로 변경
2. 서비스 파일의 생성 확인
D:/rfid02/spring/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mvc_book/resources 폴더에
JSP 관련 파일이 통합되어 들어감
[03] Local 저장소의 변경
- 메이븐은 기본적으로 저장소를 운영체제의 계정을 따라 생성된다.
'C:/Users/STU/.m2' 하지만 이경로는 개발환경이 바뀌면 불편함으로 수동으로
저장소를 지정할 수 있다.
- 기본 경로에있는 jar 파일이 인식이 안되는 경우 인식이됨.
- 라이브러리를 운영체제로부터 분리하여 이동가능.
1. Maven 설정 파일의 생성
>>>>> F:/eGov/spring/maven/settings.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository> F:/eGov/spring/maven</localRepository>
<interactiveMode>true</interactiveMode>
<usePluginRegistry>false</usePluginRegistry>
<offline>false</offline>
<pluginGroups>
<pluginGroup>org.codehaus.mojo</pluginGroup>
</pluginGroups>
</settings>
5. 수업
진도:
hw:
6. 할것
'Programming' 카테고리의 다른 글
160531: 54회차 (0) | 2016.05.31 |
---|---|
160530: 53회차 (0) | 2016.05.30 |
160526: 51회차 (0) | 2016.05.26 |
160525: 50회차 (0) | 2016.05.25 |
160524: 49회차 (0) | 2016.05.24 |