일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 자바 계산기
- 자바
- 자바알고리즘
- 계산기
- 숫자정렬
- 오름차순정렬
- 버블소트
- 자바 #java #이클립스 #eclipse #switch #switch문 #사칙연산 #계산기 #calculator #간단한계산기
- 자바GUI
- 이클립스 #이클립스단축키 #자바 #자바단축키
- GUI
- Eclipse
- annotation
- 이클립스
- Swing
- 어노테이션
- Spring
- MVC
- 스프링
- 버블정렬
- 배열정렬
- 알고리즘
- Java
- 내림차순정렬
- 계산기GUI
- Today
- Total
온 코딩
[MVC] (온라인 쇼핑몰) - index.html에서 바로 Servlet연결하기 본문
준비
1. Action.java
ActionFactory와 연결되는 각종(command)Action.java 객체들이 상속 받는 인터페이스
서블릿에 요청이 들어올 경우 :
NonageServlet.java -> ActionFactory.java -> (command)Action.java -> 요청사항 처리 / 화면이동!
package com.hhw.controller.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
public void excute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
//다른 ~~~action.java에서 구현 받는 interface
}
2. ActionFactory.java
요청에 따른 (command)Action.java 객체를 생성하고 반환하는 클래스
싱글톤 형식으로 사용
package com.hhw.controller;
import com.hhw.controller.action.Action;
public class ActionFactory {
//싱글톤 형식으로 코딩
private static ActionFactory instance = null;
public ActionFactory() {
super();
}
public static ActionFactory getInstance() {
if(instance == null) {
instance = new ActionFactory();
}
return instance;
}//getInstance() 종료
public Action getAction(String command) {
Action action = null;
//요청 사항에 따른 ~~Action.java 객체 반환
if(command.equals("index")) {
// action = new ~~~~Action();
}
return action;
}//getAction() end
}
3. NonageServlet.java
서블릿 파일!
넘어오는 command에 따라 ActionFactory.java를 사용해 필요한 (command)Action.java 객체를 전달받고
요청사항을 전달함
package com.hhw.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hhw.controller.action.Action;
/**
* Servlet implementation class NonageServlet
*/
@WebServlet("/NonageServlet")
public class NonageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public NonageServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter("command");
System.out.println("웹 브라우저로부터 요청 받음 : "+ command);
// ActionFactory 객체 생성 및 요청사항 전달
ActionFactory af = ActionFactory.getInstance();
Action action = af.getAction(command);
//command값에 따라 필요한 ~~~~action객체를 만든다
// 요청사항을 전달
if(action != null) {
action.excute(request, response);
}
//
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request, response);
}
}
index.html에서 바로 Servlet호출하기
기존에 footer.jsp /header.jsp를 include된 index.jsp를 바로 호출하는 방법이 아니라,
index.html에서 바로 servlet을 통해 index.jsp를 호출하는 방법으로 만들 예정!
+ include : <%@ include file="header.jsp" %>
1. web.xml 파일 수정하기
- 프로젝트 자체를 실행했을 때, index.html 파일을 로딩하기 위함
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>shopping_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
2. index.html
<meta http-equiv="refresh" content="0;url=NonageServlet?command=index"> 태그 추가
--> 서블렛에 요청을 통해 index.jsp 로 연결 됨
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0;url=NonageServlet?command=index">
<title>index.html</title>
</head>
<body>
</body>
</html>
<!--
html의 <meta> 태그를 이용하여 서블릿에게 요청 사항을 전달
1. http-equiv : 요청사항에 대한 결과를 받기 전 웹 브라우저를 마치 새로 고침(F5)하는 것처럼
초기화 할 수 있는 값을 설정 => "refresh"
2. content : 요청할 주소(즉, 대상)
url=대상
url=대상?파라미터명=전달값
여러가지 값을 전달 할 경우,
url=대상?파라미터명=전달값&파라미터명=전달값....
요청사항은 doGet이 받음
Servlet에서 command='index'로 IndexAction()객체를 만들어 index.jsp로 전달
-->
shopping_test 프로젝트 구동
index.html 의 <meta> 태그를 이용하여
NonageServlet?command=index와 같이
NonageServlet에게 요청사항을 전달
=> NonageServlet의 doGet(request, response)메서드의 request 내의 param영역에 command=index가 전달 됨
=> doGet() 메서드 내에서는 전달 받은 parameter를 추출하여 요청사항을 확인
=> 확인된 요청사항("index")를 ActionFactory에게 전달하여 요청사항을 처리할 수 있는 객체를 반환 받음
(ActionFactory객체의 getAction()메서드를 통해 요청이 전달 됨 )
=> 반환받은 객체(Action 인터페이스를 구현받은 클래스)의 처리 메서드인 execute()를 통해 요청 사항 처리를 위임
=> 해당 객체의 excute()메서드는 요청사항을 처리하고, 결과화면으로 이동
+IndexAction.java
package com.hhw.controller.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexAction implements Action {
public IndexAction() {
}
@Override
public void excute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "/index.jsp";
/*
* 신규 상품 목록과 베이트 상품 목록을 조회하여 결과 값을
* request의 attribute영역에 저장하여 응답 처리
*
* ProductDAO() 클래스를 생성하여 처리할 예정
* */
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
'복습 ARCHIVE > 모델별 프로젝트' 카테고리의 다른 글
[Spring] 기본 개념 및 구조 (0) | 2021.06.09 |
---|---|
[Model2](게시판) 완성본 및 화면 (0) | 2021.06.08 |
[Model1] test_poll / 투표시스템_파일첨부 (0) | 2021.06.08 |
JSP Model1 / Model2 (0) | 2021.06.08 |
MVC 패턴 (0) | 2021.05.26 |