Spring - 출력문, DI(Dependecy Injection)

2020. 9. 15. 15:17Spring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
 
<P>  The time on the server is ${serverTime}. </P>
</body>
</html>
 
//-------------FrontController---------------------
package com.itwillbs.myweb;
 
import javax.inject.Inject;
 
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 com.itwillbs.domain.MemberBean;
import com.itwillbs.service.MemService;
 
@Controller
public class MemController {
    //멤버변수
    private MemService memService;
    //1. 생성자를 통해서 값을 받을 수 있음
    //2. set 메서드를 통해서 값을 받을수 있음
    @Inject
    public void setMemService(MemService memService) {
        this.memService = memService;
    }
    
    
    @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String insert(Model model) {
        
        
        //model 스프링 제공파일 데이터 담아서 이동
        model.addAttribute("msg""member insert" );
        
        //WEB-INF/view/insertForm.jsp 이동
        
        
        return "insertForm";
    }
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insertPost(MemberBean mb) {
        
        //POST 방식일때 자동으로 insertForm에 있는 내용을 가져옴
        System.out.println(mb.getId());
        System.out.println(mb.getPass());
        System.out.println(mb.getName());
        
        //처리작업 memserviceImpl(insertmember(mb) 현시스템날짜-> mb 저장
        //1. 클래스 단독 객체 생성 메서드호출 수정-> 여러군데 수정
        //객체 생성(MemController 가 MemService 에 의존관계)
//        MemServiceImpl memServiceImpl=new MemServiceImpl();
        //메서드 호출
//        memServiceImpl.insertMember(mb);
        //2.부모클래스(인터페이스) 준비 자식클래스 메서드 오버라이딩()->한군데만 수정 
        // ->부모=자식 객체생성
//        MemService memService=new MemServiceImpl();
        // 메서드호출
//        memService.insertMember(mb);
        
        //3.자식클래스 스프링 xml 에서 객체 생성 
        //필요로 하는 클래스 MemController에 전달(주입)
        //MemController가 MemServiceImpl에 의존관계 주입
        memService.insertMember(mb);
        
        //디비작업 memdaoimp(insertmember(mb) insert
        //WEB-INF/view/insertForm.jsp 이동
        
        
        return "redirect:login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(Model model) {
        
        model.addAttribute("msg","반가워");
        
        return "loginForm";
    }
    //         /login POST   main 가상주소 이동
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String loginPost() {
        
        
        return "redirect:main";
    }
    //        /main  GET    main.jsp 이동
    @RequestMapping(value = "/main",method = RequestMethod.GET)
    public String main() {
        
        
        return "main";
    }
}
 
//------------------------------Service---------------------------------
 
package com.itwillbs.service;
 
import org.springframework.stereotype.Service;
 
import com.itwillbs.dao.MemDAO;
import com.itwillbs.domain.MemberBean;
@Service
public class MemServiceImpl implements MemService {
    private MemDAO memDAO;
    public void setMemDAO(MemDAO memDAO) {
        this.memDAO = memDAO;
    }
    @Override
    public void insertMember(MemberBean mb) {
        System.out.println("MemServiceImpl insertMember()");
        //디비작업 MemDAOImp(insertMember(mb)) insert
        //1. 클래스 단독 객체생성 메서드호출 수정-> 여러군데 수정
        //MemDAOImp 객체생성
//        MemDAOImp memDAOImp=new MemDAOImp();
        //insertMember(mb) 메서드 호출
//        memDAOImp.insertMember(mb);
        
        //2. 부모클래스(인터페이스) 준비, 자식클래스 메서드 오버라이딩()=> 한군데 수정
//        MemDAO memDAO=new MemDAOImp();
//        memDAO.insertMember(mb);
        
        //3.
        memDAO.insertMember(mb);
    }
}
 
//---------------------------DAO--------------------------------
 
package com.itwillbs.dao;
 
import org.springframework.stereotype.Repository;
 
import com.itwillbs.domain.MemberBean;
@Repository
public class MemDAOImp implements MemDAO {
    @Override
    public void insertMember(MemberBean mb) {
        System.out.println("MemberDAOImp insertMember");
        
    }
}
 
//-----------------------Interface Service------------------
 
 
package com.itwillbs.service;
 
import com.itwillbs.domain.MemberBean;
 
public interface MemService {
    //추상메서드 정의
    public void insertMember(MemberBean mb);
}
//-------------------Interface DAO---------------
package com.itwillbs.dao;
 
import com.itwillbs.domain.MemberBean;
 
public interface MemDAO {
    public void insertMember(MemberBean mb);
}
 
//----------------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="memController" class="com.itwillbs.myweb.MemController">
        <property name="memService" ref="memService"/>
        </bean>
        <bean id="memService" class="com.itwillbs.service.MemServiceImpl">
        <property name="memDAO" ref="memDAO"/>
        </bean>
        <bean id="memDAO" class="com.itwillbs.dao.MemDAOImp"></bean>
</beans>
 
 
 
 
cs

 

JSP와 다르게 출력문은 ${}으로 출력이 가능하므로 헷갈려하지 말도록 하자. 

MVC2와 다르게 Servlet 에서 get, post 방식에 따라 메서드를 따로 만들어 줘야 하고 

@(어노테이션)이 굉장히 중요한 역할을 한다는 것이다. @RequestMapping,@Controller

이런식으로 명확히 표현을 해줘야 하고, MVC2 에서는 포워딩을 위해 인터페이스와 클래스를 따로 만들어 계속 

초기화를 시켜가며 해야 하지만 Spring 에서는 그럴 필요 없이 어노테이션으로 value를 선언하여 주소 값을 리딩하고

return으로 포워딩을 정해주기만 하면 끝나는 간단한 방식이다. 처음 접하면 어색하니 좀 더 연습을 해서 익숙해져야 하겠다. 그리고 DI를 위해서 root-context.xml 즉 XML 파일을 이제부터 건드려야 한다. bean 태그로 객체를 선언해주고 이름과 참조 주소를 입력해주면 끝난다. 간단하게 한 줄을 선언 함으로써 계속 객체를 생성할 필요 없이 멤버 변수로 선언만 해준다면 계속 사용이 가능하기 때문에 효율적으로 사용이 가능하고 수정이 필요할 때도 여러 군데를 손볼 필요 없이 간단하게 한 군데만 수정이 되면 되기 때문에 유지보수 측면에서도 훌륭하다. Spring을 겁내지 말고 잘 다뤄 보도록 하자.

'Spring' 카테고리의 다른 글

Spring - Maven  (0) 2020.09.18
Spring - Connection  (0) 2020.09.18
Spring - jstl(JSP Standard Tag Library)  (0) 2020.09.18
Spring - servlet-context.xml  (0) 2020.09.15