본문 바로가기
Servlet-Jsp

workout (운동기록프로그램 myBatis) #1

by 지민재 2022. 8. 11.
반응형
SMALL
우선 web.xml 추가 

설정코드가 복잡하기 때문에 Servers 에서 web.xml 들어가보면 설정 코드 복사해서 사용

 

 

<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

</web-app>

 

controllers 패키지 생성 

 

위 패키지를 메인으로 쓸 거라서 webapp에서 main 폴더에 index.jps 생성 후 연동을 시킬 목적입니다.

<%@ page contentType="text/html; charset=utf-8" %>

위 코드 작성 해놓았습니다. 

 

controllers 패키지에 IndexController 클래스 생성 

 

IndexController의 서블릿 구성 
package controllers;

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;

public class IndexController extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		RequestDispatcher rd = req.getRequestDispatcher("/main/index.jsp");
		rd.forward(req, resp);
	}
	
}
HttpServlet 상속 받고 상단에 소스에 implement methon 클릭 후 doGet 오버라이딩 받는다. 그리고 RequestDispatcher 를 통해 /main/index.jsp 를 가져온다. 

여기서 RequestDispatcher 란 ? 

RequestDispatcher는 클라이언트로부터 최초에 들어온 요청을 JSP/Servlet 내에서 원하는 자원으로 요청을 넘기는 역할을 수행하거나, 특정 자원에 처리를 요청하고 처리 결과를 얻어오는 기능을 수행하는 클래스입니다. 즉 /commin.jsp 로 들어온 요청을 commin.jsp 내에서 RequestDispatcher를 사용하여 index.jsp로 요청을 보낼 수 있습니다. 또는 commin.jsp에서 index.jsp로 처리를 요청하고 index.jsp에서 처리한 결과 내용을 commin.jsp의 결과에 포함시킬 수 있습니다. 요청을 보내는 방법으로는 RequestDispatcher.forward()와 RequestDispatcher.include() 두 가지 방법이 있습니다.
 

출처: https://dololak.tistory.com/502 [코끼리를 냉장고에 넣는 방법:티스토리]

 

WEB-INF 에 tags - layouts 폴더 생성 그리고 공통적으로 layout을 쓸 common.tag 생성

 

 

<%@ tag description="공통 레이아웃" pageEncoding="UTF-8"%>
<%@ tag body-content="scriptless"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
	<jsp:doBody />
</body>
</html>
<%@ tag description="공통 레이아웃"  %> << 이 부분은 태그가 많이 때문에 어떤 태그인지 설명 
body-content="scriptless" 태그안에 내용물이 많이 때문에 scriptless 로 선언해주었다.

<jsp:doBody />란 
몸체에 전달받은 내용을 그래도 출력한다. 
태그 파일이 <jsp:attribute> 태그를 이용해서 속성 값을 전달 받는 경우에 <jsp:doBody > 사용해서 몸체 내용을 전달할 수 있다. 

 

서블릿 작성 
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">


<servlet>
<servlet-name>index.servlet</servlet-name>
<servlet-class>controllers.IndexController</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>index.servlet</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>
</web-app>

 

index.jsp 에 출력 코드 작성 해보기
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="layout" tagdir="/WEB-INF/tags/layouts" %>

<layout:common>
<h1>본문 출력!</h1>
</layout:common>

잘 출력된다면 이상 없는겁니다 !! 

 

이제 헤더와 푸터를 외부에서 접근가능 하도록 만들어 하나의 브라우저에 출력해 볼 것입니다.
<%@ tag description="공통 레이아웃" pageEncoding="UTF-8"%>
<%@ tag body-content="scriptless"%>
<%@ attribute name="header" fragment="true"%>
<%@ attribute name="footer" fragment="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
	<jsp:invoke fragment="header" />
	
	<jsp:doBody />

	<jsp:invoke fragment="footer"/>
</body>
</html>

 

 

header 와 footer 를 태그형태로 접근하게 하는 방법은 attribute 사용하는 방법이다. 하나의 부분으로써 특정조건에 발생시킬 수 있다. 즉 common.jsp 가 아니라 다른곳에서 attribute 로써 접근 하면 교차 가능하기 때문에 외부의 태그형태로1

 

이제 외부인 index.jsp 에서  header 와 footer 에 접근하는 방법

 

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="layout" tagdir="/WEB-INF/tags/layouts"%>

<layout:common>

	<jsp:attribute name="header">
	<h1>헤더!</h1>
	</jsp:attribute>
	
	<jsp:attribute name="footer">
	<h1>푸터!</h1>
	</jsp:attribute>
	
	<jsp:body>

	<h1>본문 출력!</h1>

	</jsp:body>

</layout:common>

좀 더 편하게 쓰기 위해서 layouts 에 main.tag를 만들어 태그안에 태그를 넣어주는 방식으로 진행해보았다. 

 

main.tag
<%@ tag description="공통 레이아웃" pageEncoding="UTF-8"%>
<%@ tag body-content="scriptless"%>
<%@ taglib prefix="layout" tagdir="/WEB-INF/tags/layouts"%>

<layout:common>

	<jsp:attribute name="header">
	<header>
	<h1>운동기록프로그램</h1>
	</header>
	<nav>
	<a href="#">운동 추가</a>
	<a href="#">운동 수정</a>
	<a href="#">운동 삭제</a>
	</nav>
	</jsp:attribute>

	<jsp:attribute name="footer">
	<footer>
	&copy; Copyright...
	</footer>
	</jsp:attribute>

	<jsp:body>
<main>
	<jsp:doBody />
</main>
	</jsp:body>

</layout:common>
index.jsp
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="layout" tagdir="/WEB-INF/tags/layouts"%>

<layout:main>
<h1>운동!</h1>
</layout:main>
코드가 더 간결해졌다. !! 그리고 정상적으로 출력된다.

 

static 폴더안에 css 와 js 를 생성하였다. 

 

css 와 js 를 적용시킬건데 페이지마다 유연하게 적용하기 위해서 아래 코드를 작성하였다.

 

<%@ tag description="공통 레이아웃" pageEncoding="UTF-8"%>
<%@ tag body-content="scriptless"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="header" fragment="true"%>
<%@ attribute name="footer" fragment="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/xeicon@2.3.3/xeicon.min.css">
<link rel="stylesheet" type="text/css" href="<c:url value="/static/css/style.css"/>"/>

<c:if test="${!empty addCss}">
<c:forEach var="css" items="${addCss}">
<link rel="stylesheet" type="text/css" href="<c:url value="/static/css/"/>${css}.css"/>
</c:forEach>
</c:if>

<script src="<c:url value="/static/js/common.js"/>"></script>
<c:if test="${!empty addJs}">
<c:forEach var="js" items="${addJs}">
<script src="<c:url value="/static/js/"/>${js}.js"></script>
</c:forEach>
</c:if>

<title>${empty title ? "게시판" : title}</title>


</head>
<body>
	<jsp:invoke fragment="header" />
	
	<jsp:doBody />

	<jsp:invoke fragment="footer"/>
</body>
</html>

 

package controllers;

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;

public class IndexController extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String[] addCss = {"text1", "text2"};
		req.setAttribute("addCss", addCss);
		
		String[] addJs = {"text3", "text4"};
		req.setAttribute("addJs", addJs);
		
		RequestDispatcher rd = req.getRequestDispatcher("/main/index.jsp");
		rd.forward(req, resp);
	}
	
}

<c:if test="${!empty addJs}"> //값이 비어 있지 않으면
<c:forEach var="js" items="${addJs}"> //추가 

 

댓글