* FrontController 패턴
1. Client의 요청을 집중 시키는 앞단 client
-> Controller들의 공통 로직을 앞단에서 처리
-> 모든 client의 요청을 한 곳에 집중시킴
* Front Controller : Controller의 공통적인 작업을 모아서 처리한다.(사 전 : Filter, 사 후)
[실습]
dynamic web project
- member_servlet_fc
copy
src
member.dto
member.model.dao
member.model.exception
member.model.service
member.util
servlet
package : member.controller
Class name : MemberFrontController
url-pattern : /controller
interace
package : member.controller
name : Controller
package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
//모든 Controller 클래스의 type이 되는 interface
// 컨트롤러 로직 처리 메소드를 선언
public interface Controller {
public ForwardDTO execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
package member.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class LoginController implements Controller{
public ForwardDTO execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
//1. 요청파라미터 조회
String id = request.getParameter("id");
String password = request.getParameter("password");
//서비스 instance 받아오기
MemberManageService memberManageService = MemberManageService.getInstance();
ForwardDTO forwardDTO = null;
try {
MemberDTO mto = memberManageService.getMemberById(id);
//아이디가 맞는 경우
if(mto!=null){
//아이디가 맞고 비밀번호도 맞는 경우
if(mto.getPassword().equals(password)){
//세션으로 로그인 정보 넘기기
HttpSession httpSession = request.getSession();
httpSession.setAttribute("memberDTO", mto);
forwardDTO = new ForwardDTO("/res/login_success.jsp", false);
}
else{//아이디는 맞고 비밀번호는 틀린경우
request.setAttribute("error_message", "비밀번호가 틀립니다.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
}else{//아이디도 틀리고 비밀번호도 틀린경우
request.setAttribute("error_message", "아이디가 틀립니다.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
} catch (SQLException e) {
e.printStackTrace();
forwardDTO = new ForwardDTO( "/res/error.jsp", false);
request.setAttribute("error_message", e.getMessage());
}
return forwardDTO;
}
}
package member.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
//FrontController 서블릿
public class MemberFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MemberFrontController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Controller 수행 전 작업(공통) - 한글처리
request.setCharacterEncoding("utf-8");
//Controller 로직 처리 - Controller 로직 호출
String command = request.getParameter("command");//클라이언트가 어떤 요청을 했는지 조회
Controller controller = null;
if(command.equals("login")){
controller = new LoginController();
}
ForwardDTO forwardDTO = null;
try {
forwardDTO = controller.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
//Controller 수행 후 작업(공통) - 응답(View로 수행 이동)
if(forwardDTO.isRedirect()){
response.sendRedirect(forwardDTO.getUrl());
}else{
RequestDispatcher requestDispatcher = request.getRequestDispatcher(forwardDTO.getUrl());
requestDispatcher.forward(request, response);
}
}
}
package member.dto;
//url값을 가지고 있는 DTO
public class ForwardDTO {
private String url;
private boolean redirect;//true-리다이렉트, false - 요청디스패치
public ForwardDTO() {
super();
// TODO Auto-generated constructor stub
}
public ForwardDTO(String url, boolean redirect) {
super();
this.url = url;
this.redirect = redirect;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
@Override
public String toString() {
return "ForwardDTO [url=" + url + ", redirect=" + redirect + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (redirect ? 1231 : 1237);
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ForwardDTO other = (ForwardDTO) obj;
if (redirect != other.redirect)
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${sessionScope.memberDTO != null }">
<jsp:forward page="/res/member_details.jsp"/>
</c:if>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<c:if test="${requestScope.error_message!=null }">
<font color="red">${requestScope.error_message }</font>
</c:if><br>
<body>
<jsp:include page="/menu.jsp"/>
<form action="/${initParam.context_root }/controller" method="post">
<input type="hidden" name="command" value="login">
<table>
<tr>
<td><h2>로그인</h2><p></td>
</tr>
<tr>
<td>id</td><td><input type="text" name="id"></td>
</tr>
<tr>
<td>password</td><td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="로그인"><input type="reset" value="초기화"></td>
</tr>
</table>
</form>
</body>
</html>
<%@page import="member.dto.MemberDTO"%>
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
${sessionScope.memberDTO.id } 님환영합니다.<p>
이름 : ${sessionScope.memberDTO.name }<br>
패스워드 : ${sessionScope.memberDTO.password }<br>
주민번호 : ${sessionScope.memberDTO.registerNumber1 }-${sessionScope.memberDTO.registerNumber2 }<br>
마일리지 : ${sessionScope.memberDTO.mileage }<br>
<a href='/${initParam.context_root }/logout'>로그아웃</a>
<a href='/${initParam.context_root }/getMemberInfo'>회원정보조회(로그인한 회원의 정보)</a>
<!--<input type="button" value="회원정보조회" onClick="location.href='/${initParam.context_root }/getMemberInfo'"> -->
</body>
</html>
* 결과보기
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<a href='/${initParam.context_root }/index.jsp'>메인페이지</a>
<c:choose>
<c:when test="${sessionScope.memberDTO == null }">
<a href='/${initParam.context_root }/register_form.jsp'>회원가입폼</a>
<a href="/${initParam.context_root }/login_form.jsp">로그인폼</a>
<a href="/${initParam.context_root }/search_form.jsp">검색</a>
</c:when>
<c:otherwise>
<a href='/${initParam.context_root }/controller?command=logout'>로그아웃</a>
<a href="/${initParam.context_root }/getMemberInfo">회원정보조회</a>
<a href="/${initParam.context_root }/modifyForm">회원정보 수정</a>
<a href="/${initParam.context_root }/removeMember">회원 탈퇴</a>
</c:otherwise>
</c:choose>
<a href="/${initParam.context_root }/getAllMemberInfo">전체 회원정보 조회</a>
<hr width="700" align="left" noshade="noshade">
<%@page import="member.dto.MemberDTO"%>
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
${sessionScope.memberDTO.id } 님환영합니다.<p>
이름 : ${sessionScope.memberDTO.name }<br>
패스워드 : ${sessionScope.memberDTO.password }<br>
주민번호 : ${sessionScope.memberDTO.registerNumber1 }-${sessionScope.memberDTO.registerNumber2 }<br>
마일리지 : ${sessionScope.memberDTO.mileage }<br>
<a href='/${initParam.context_root }/controller?command=logout'>로그아웃</a>
<a href='/${initParam.context_root }/getMemberInfo'>회원정보조회(로그인한 회원의 정보)</a>
<!--<input type="button" value="회원정보조회" onClick="location.href='/${initParam.context_root }/getMemberInfo'"> -->
</body>
</html>
package member.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
//FrontController 서블릿
public class MemberFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MemberFrontController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Controller 수행 전 작업(공통) - 한글처리
request.setCharacterEncoding("utf-8");
//Controller 로직 처리 - Controller 로직 호출
String command = request.getParameter("command");//클라이언트가 어떤 요청을 했는지 조회
Controller controller = null;
if(command.equals("login")){
controller = new LoginController();
}else if(command.equals("logout")){
controller = new LogoutController();
}
ForwardDTO forwardDTO = null;
try {
forwardDTO = controller.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
//Controller 수행 후 작업(공통) - 응답(View로 수행 이동)
if(forwardDTO.isRedirect()){
response.sendRedirect(forwardDTO.getUrl());
}else{
RequestDispatcher requestDispatcher = request.getRequestDispatcher(forwardDTO.getUrl());
requestDispatcher.forward(request, response);
}
}
}
package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
public class LogoutController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
//로그인 여부 체크
MemberDTO memberDTO = (MemberDTO) session.getAttribute("memberDTO");
if (memberDTO != null) {
session.invalidate(); //세션을 지우기
} else {
request.setAttribute("error_message", "먼저 로그인 해주세요");
}
return new ForwardDTO("/login_form.jsp", false);
}
}
* 결과보기
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-15 MVC를 활용한 게시판만들기 (0) | 2012.05.15 |
---|---|
2012-5-15 MVC를 활용한 회원관리 프로그램(FrontController 사용) (0) | 2012.05.15 |
2012-5-14 MVC모델을 활용한 회원정보 수정,삭제 (0) | 2012.05.14 |
2012-5-13 MVC를 활용한 회원관리 전체 소스 (0) | 2012.05.13 |
2012-5-13 MVC패턴을 활용한 이름으로 회원 조회하기(like 사용) (0) | 2012.05.13 |