public void execute() {
request.setCharacterEncoding("utf-8");
String email = request.getParameter("email");
String pw = request.getParameter("pw");
memberDTO dto1 = new memberDTO(email, pw);
memberDAO dao = new memberDAO();
memberDTO dto = dao.Login(dto1);
String nextpage = "";
if(dto != null) {
HttpSession session = request.getSession();
session.setAttribute("dto", dto);
response.sendRedirect("main.jsp");
}else {
response.sendRedirect("LoginFalse.jsp");
}
}
메소드 안에는 컨트롤러 안에 있던 코드들을 모두 잘라와서 붙여준다.
→ request와 response부분에서 다 오류남.
일반 자바 클래스 파일은 request/response가 없어서.
LoginService login = new LoginService();
login.execute(request, response);
servlet이 가지고 있는 request/response를 class에 빌려주기.
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
...
}
메소드 괄호 안에서 request와 response를 받아준다.
이 때, request/response 부분에서 런타임 오류 발생
→ 메서드 괄호 뒷쪽에 throws ServletException, IOException 붙여주기
→ throws : 예외처리
try-catch : try 안쪽 부분만 예외처리됨(그 밖에 있는 다른 부분은 예외처리 안됨).
throws : 메소드 안에 있는 전체 코드에 예외처리가 걸림(예외처리가 필요하지 않은 부분까지 예외처리가 됨). 사용하기에는 편하지만 메모리적으로는 훨씬 비효율적이다.
** throws를 사용하고싶지 않다면 하나하나의 코드에 try-catch문을 걸어주면 된다.
public interface Command {
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
설계도라고도 한다.
여러 사람이 같이 만들면 메서드 이름, 변수 이름, 파일 이름 등이 다 달라져버린다. 여러명의 개발자가 동시에 개발을 할 때 하나의 정해진 규칙을 가지고 개발을 할 수 있다.
** interface는 기능을 정의하는 구역이 아닌 그냥 규칙이다. 중괄호 필요 없음!
public class LoginService implements Command{
...
}
Command com = null;
String nextpage = null;
if(command.equals("LoginCon.do")) {
com = new LoginService();
nextpage = com.execute(request, response);
}
부모의 이름으로 자식을 형변환하기
컨트롤러의 if문 안을 upcasting으로 바꿔준다.
모든 클래스들이 implements Command를 하고 있으니까 Command com = null;로 전역변수 설정해주고 com = new LoginService();로 자식을 생성하면서 부모로 형변환 시켜준다.
** 여러개의 객체 생성이 가능하다.