본문 바로가기
programming/MakinGProJect

게시판 만들기 15 화면에 목록 표시하기 자바 스프링프레임워크 사용

by 개코 - 개발과 코딩 2021. 10. 29.

이전에 목록을 위한 데이터를 화면에 표시했다. 하지만 목록이라 보기엔 어색하다. 이 조회된 데이터를 가지고 목록으로 만들어 웹페이지에 표시를 해 줄 차례이다. 목록은 텍스형과 사진형이 있지만 여기서는 텍스트형으로 진행한다.

게시판 만들기 15 화면에 목록 표시하기
자바 스프링프레임워크 사용

목록은 사람들이 웹페이지에서 가장 많이 보는 항목이다.

데이터의 나열이며 목록처럼 보이지 않지만 동일한 항목들이 나열된 형태를 가진다.

이전에 데이터를 조회하여 화면에 대충 표시하는 것을 했다.

이제는 이 데이터를 가공하여 화면에 목록처럼 보이도록 할 것이다.

ModelAndView와 JSTL

ModelAndView는 스프링프레임워크의 컨트롤러에서 웹페이지에 데이터를 보내주는 역할을 한다.

JSTL은 jsp 구문으로 ModelAndView의 값을 화면에 보여주는 역할을 한다.

JSTL은 jsp 구문으로 서버단에서 렌더링되는 언어이다.

데이터 덩어리가 서버에서 렌더링되어 내려오는 것이기 때문에 동기방식이기도 하다.

비동기는 나중에 다루기로 하자.

목록 테이블 생성

컨트롤러에서 조회된 데이터를 목록으로 표시하기 위해 table 형태의 태그를 만들어 주어야 한다.

예술적인 코딩은 생각하지 말고 화면에 나올수 있는 형태로 먼저 가공을 하도록 하자.

package com.crd.test.Template;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.google.gson.Gson;

/**
 * Handles requests for the application home page.
 */
@Controller
public class Template1Controller {
	
	@Autowired
	private Template2Service gService;
	
	private static final Logger logger = LoggerFactory.getLogger(Template1Controller.class);
	
	/**
	 * url 최초진입
	 */
	@RequestMapping(value = "/template", method = RequestMethod.GET)
	public String BoardList(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		int vCount = 0;
		String vRetList = null;
		List<Template0Model> vList;
		StringBuffer vStringBuffer = new StringBuffer();
				
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		Template0Model vModel = new Template0Model();
				
		try {
			
			vModel = gService.RequestData(
						new Template0Model("")
					);
			
			vList = gService.SelectListTemplate(
					new Template0Model("")
				);
			
			vCount = vList.size();
			
			for(Template0Model lpModel : vList){				
				vStringBuffer.append("<tr>");
				vStringBuffer.append("<td>"+lpModel.getTitle()+"</td>");
				vStringBuffer.append("</tr>");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			vModel.setDataObject("에러발생" + e.getMessage());	
		}
		
		model.addAttribute("serverTime", formattedDate + " STS 실행 테스트");
		model.addAttribute("serverResult", vModel.getDataObject());
		model.addAttribute("serverResultListCount", vCount);
		model.addAttribute("serverResultListData", vRetList);
		model.addAttribute("serverResultListRenderData", vStringBuffer.toString());
		
		return "template/template";
	}
}

위의 코드에서 봐야 할 부분이 있다.

  • SelectListTemplate
    데이터를 조회하는 사용자 정의 메서드
  • for( Template0Model lpModel : vList )
    조회한 데이터를 반복하여 html 테이블 형태로 만들어 주는 부분
  • model.addAttribute("serverResultRenderData", ...)
    웹페이지에 렌더링될 html 테이블 부분

화면에 출력

이제 화면에 데이터를 출력해 보도록 하자.

modelandview 부분에 html 테이블로 만든 문자열을 넣었다.

이것을 html 에서 jstl 구문으로 화면에 표시해 줄 것이다.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- html5 기본템플릿 -->
<!DOCTYPE html>

    <!-- head -->
    <head>
    	
    	<!-- 한글 깨짐 방지 -->
		<meta charset="UTF-8">
        
        <!-- meta SEO 컨텐츠 -->
        <meta name="title" content="목록화면">
        <meta name="description" content="목록화면입니다.">
        <meta name="keywords" content="목록">
        <meta name="author" content="개코">
        <meta name="copyright" content="개코">
        <!-- // -->

        <!-- meta 반응형 웹표준 -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- // -->

        <!-- 스타일 -->
        <style></style>
        <!-- // -->

    </head>
    <!-- // -->

    <!-- body -->
    <body>
        <p>
        	${serverTime}
        </p>
        <p>
        	${serverResult}
        </p>
        <p>
        	${serverResultListCount}
        </p>
        <p>
        	${serverResultListData}
        </p>
        <table>
        	<thead>
        		<tr>
        			<td>제목</td>
        		</tr>
        	</thead>
        	<tbody>
        		${serverResultListRenderData}
        	</tbody>
        </table>
    </body>
    <!-- // -->

    <!-- 자바스크립트 -->
    <script type="text/javascript"></script>
    <!-- // -->

</html>

위의 코드에서 table 태그의 위치를 보자.

${ ... } 구문으로 되어 있는 부분이 컨트롤러에서 보내주는 값이다.

modelAndView 의 키를 작성한 부분이다.

화면을 보도록 하자.

테이블 형태로 렌더링되어 화면에 잘 나타나고 있는 것을 알 수 있다.

 

반응형

댓글