본문 바로가기

Web[웹]/Spring Framework

[Spring] Service & Dao 객체 구현 : MVC 프로젝트 (1)

 

Service & DAO 객체 구현

 

이번에 구현해볼 객체는 Service & DAO 구간이다.

 

 

 

 

먼저,  spring regacy project를 통해 웹 어플리케이션을 만들어주자.

 

 

그냥 프로젝트를 만들고 바로 서버를 통해 실행을 해보면 한글처리가 안됬음을 알 수 있다. 이를 따로 한글처리를 해주어야 한다.

 

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>
	<init-param>
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>encodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

 

 

 

이제 실습해볼 3개의 로그인 html을 만들 것인데, src/main/webapp/resources/html/ 에 'index.html', 'memJoin.html', 'login.html' 을 다음과 같이 만들어주며, 바로 view 밑에 jsp 파일 'memJoinOk.jsp', 'memLoginOk.jsp'도 만들어 주자.

 

 

 

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Main</h1>
    <a href="/test/resources/html/memJoin.html">JOIN</a>
    &nbsp;&nbsp;
    <a href="/test/resources/html/login.html">LOGIN</a>
</body>
</html>
<!-- memJoin.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Member Join</h1>
    <form action="/test/memJoin" method="post">
        ID : <input type="text" name="memId"><br />
        PW : <input type="password" name="memPw"><br />
        MAIL : <input type="text" name="memMail"><br />
        PHONE : <input type="text" name="memPhone1" size="5"> -
		        <input type="text" name="memPhone2" size="5"> -
		        <input type="text" name="memPhone3" size="5"><br />
        <input type="submit" value="Join">
        <input type="reset" value="Cancel">
    </form>
    <a href="/test/resources/html/login.html">LOGIN</a>
    &nbsp;&nbsp;
    <a href="/test/resources/html/index.html">MAIN</a>
</body>
</html>
<!-- login.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Login</h1>
    <form action="/test/memLogin" method="post">
        ID : <input type="text" name="memId"><br>
        PW : <input type="password" name="memPw"><br>
        <input type="submit" value="Login">
    </form>
    <a href="/test/resources/html/memJoin.html">JOIN</a>
    &nbsp;&nbsp;
    <a href="/test/resources/html/index.html">MAIN</a>
</body>
</html>

 

 

 

 

 

이어서 view 에도 jsp 파일 2개를 추가해보자.

 

<!-- memJoinOk.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1>memJoinOk</h1>
	ID : ${memId}<br />
	PW : ${memPw}<br />
	Mail : ${memMail}<br />
	Phone : ${memPhone}<br />
	
	<a href="/test/resources/html/memJoin.html">Go MemberJoin</a>
</body>
</html>
<!-- memLoginOk.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1>memLoginOk</h1>
	ID : ${memId}<br />
	PW : ${memPw}<br />
	
	<a href="/test/resources/html/index.html">Go Main</a>
</body>
</html>

 

이어서 src/main/java/com/opentogether/test/ 에 member 패키지를 추가해줘서 그 안에 Member.java 파일을 만들어 주며, 또 그 밑에 패키지 controller, dao, service를 만들어 다음 파일들을 만들어주자.

 

 

/* Member.java */
package com.opentogether.test.member;

public class Member {
	private String memId;
	private String memPw;
	private String memMail;
	private String memPhone1;
	private String memPhone2;
	private String memPhone3;
	
	public String getMemId() {
		return memId;
	}
	public void setMemId(String memId) {
		this.memId = memId;
	}
	public String getMemPw() {
		return memPw;
	}
	public void setMemPw(String memPw) {
		this.memPw = memPw;
	}
	public String getMemMail() {
		return memMail;
	}
	public void setMemMail(String memMail) {
		this.memMail = memMail;
	}
	public String getMemPhone1() {
		return memPhone1;
	}
	public void setMemPhone1(String memPhone1) {
		this.memPhone1 = memPhone1;
	}
	public String getMemPhone2() {
		return memPhone2;
	}
	public void setMemPhone2(String memPhone2) {
		this.memPhone2 = memPhone2;
	}
	public String getMemPhone3() {
		return memPhone3;
	}
	public void setMemPhone3(String memPhone3) {
		this.memPhone3 = memPhone3;
	}
}

 

/* MemberController.java */
package com.opentogether.test.member.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
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.opentogether.test.member.Member;
import com.opentogether.test.member.service.MemberService;

@Controller
public class MemberController {

	MemberService service;
	
	@RequestMapping(value="/memJoin", method=RequestMethod.POST)
	public String memJoin(Model model, HttpServletRequest request) {
		String memId = request.getParameter("memId");
		String memPw = request.getParameter("memPw");
		String memMail = request.getParameter("memMail");
		String memPhone1 = request.getParameter("memPhone1");
		String memPhone2 = request.getParameter("memPhone2");
		String memPhone3 = request.getParameter("memPhone3");
		
		service.memberRegister(memId, memPw, memMail, memPhone1, memPhone2, memPhone3);
		
		model.addAttribute("memId", memId);
		model.addAttribute("memPw", memPw);
		model.addAttribute("memMail", memMail);
		model.addAttribute("memPhone", memPhone1 + " - " + memPhone2 + " - " + memPhone3);
		
		return "memJoinOk";
	}
	
	@RequestMapping(value="/memLogin", method=RequestMethod.POST)
	public String memLogin(Model model, HttpServletRequest request) {
		
		String memId = request.getParameter("memId");
		String memPw = request.getParameter("memPw");
		
		Member member = service.memberSearch(memId, memPw);
		
		try {
			model.addAttribute("memId", member.getMemId());
			model.addAttribute("memPw", member.getMemPw());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return "memLoginOk";
	}
	
}
/* IMemberDao.java */
package com.opentogether.test.member.dao;

import com.opentogether.test.member.Member;

public interface IMemberDao {
	void memberInsert(String memId, String memPw, String memMail, 
                      String memPhone1, String memPhone2, String memPhone3);
	Member memberSelect(String memId, String memPw);
	void memberUpdate();
	void memberDelete();
}
/* MemberDao.java */
package com.opentogether.test.member.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.opentogether.test.member.Member;


public class MemberDao implements IMemberDao {

	private HashMap<String, Member> dbMap;
	
	public MemberDao() {
		dbMap = new HashMap<String, Member>();
	}
	
	@Override
	public void memberInsert(String memId, String memPw, String memMail, String memPhone1, 
                             String memPhone2, String memPhone3) {
		System.out.println("memberInsert()");
		System.out.println("memId : " + memId);
		System.out.println("memPw : " + memPw);
		System.out.println("memMail : " + memMail);
		System.out.println("memPhone : " + memPhone1 + " - " + memPhone2 + " - " + memPhone3);
		
		Member member = new Member();
		member.setMemId(memId);
		member.setMemPw(memPw);
		member.setMemMail(memMail);
		member.setMemPhone1(memPhone1);
		member.setMemPhone2(memPhone2);
		member.setMemPhone3(memPhone3);
		
		dbMap.put(memId, member);
		
		Set<String> keys = dbMap.keySet();
		Iterator<String> iterator = keys.iterator();
		
		while (iterator.hasNext()) {
			String key = iterator.next();
			Member mem = dbMap.get(key);
			System.out.print("memberId:" + mem.getMemId() + "\t");
			System.out.print("|memberPw:" + mem.getMemPw() + "\t");
			System.out.print("|memberMail:" + mem.getMemMail() + "\t");
			System.out.print("|memberPhone:" + mem.getMemPhone1() + " - " + 
							   mem.getMemPhone2() + " - " + 
							   mem.getMemPhone3() + "\n");
		}
		
	}

	@Override
	public Member memberSelect(String memId, String memPw) {
		Member member = dbMap.get(memId);
		
		return member;
	}

	@Override
	public void memberUpdate() {

	}

	@Override
	public void memberDelete() {

	}

}
/* IMemberService.java */
package com.opentogether.test.member.service;

import com.opentogether.test.member.Member;

public interface IMemberService {
	void memberRegister(String memId, String memPw, String memMail, String memPhone1, 
                        String memPhone2, String memPhone3);
	Member memberSearch(String memId, String memPw);
	void memberModify();
	void memberRemove();
}
/* MemberService.java */
package com.opentogether.test.member.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.opentogether.test.member.Member;
import com.opentogether.test.member.dao.MemberDao;


public class MemberService implements IMemberService {

	@Autowired
	MemberDao dao;
	
	@Override
	public void memberRegister(String memId, String memPw, String memMail,
			String memPhone1, String memPhone2, String memPhone3) {
		System.out.println("memberRegister()");
		System.out.println("memId : " + memId);
		System.out.println("memPw : " + memPw);
		System.out.println("memMail : " + memMail);
		System.out.println("memPhone : " + memPhone1 + " - " + memPhone2 + " - " + memPhone3);
		
		dao.memberInsert(memId, memPw, memMail, memPhone1, memPhone2, memPhone3);
	}

	@Override
	public Member memberSearch(String memId, String memPw) {
		System.out.println("memberSearch()");
		System.out.println("memId : " + memId);
		System.out.println("memPw : " + memPw);
		
		Member member = dao.memberSelect(memId, memPw);
		
		return member;
	}

	@Override
	public void memberModify() {
		
	}

	@Override
	public void memberRemove() {
		
	}

}

 

여기까지 구성했으면, 서비스 객체구현을하는 여러 방법들을 알아보자.

 

방법 1. new 연산자를 이용한 service 객체 생성 및 참조

위와 같이 생성하면, 순수 자바만을 이용해서 생성한 객체이므로 스프링 취지와는 다르다.

 

 

방법 2. 스프링 설정파일을 이용한 서비스 객체 생성 및 의존 객체 자동 주입

 

servlet-context.xml 파일에 서비스 객체를 생성한 후에 의존 객체를 @Autowired를 통해 자동주입을 할 수있다.

 

 

방법3. 어노테이션을 이용해서 서비스 객체 생성 및 의존 객체 자동 주입

 

이 방법은 가장 실무에서 많이 쓰이는 방법으로, 따로 스프링 설정파일 없이, 해당 객체 위에 어노테이션을 명시해주는 것이다.

 

이제, 마지막으로 DAO 객체를 구현하는 방법을 알아보자.