본문 바로가기
CLASS/SPRING,JSTL

#6-4 / JSTL - database 연결

by hingu 2024. 7. 15.
⚡ 타이틀
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="cr" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:setDataSource 
var="db"
driver="com.mysql.cj.jdbc.Driver" 
url="jdbc:mysql://localhost:3306/cms"
user="hana"
password="hana1234" />

<!-- 요렇게도 쓰고 -->
<!-- <sql:query var="ps" sql="select * from coupon" dataSource="${db}" /> --!>

<!-- 요렇게도 쓰는데 이걸 더 추천 -->
<cr:set var="table" value="coupon"/>
<cr:set var="order" value="order by cidx desc"/>
<sql:query var="ps" dataSource="${db}">
	select * from ${table} ${order} 
</sql:query>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jstl로 database 연결</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0">
	<thead>
		<tr>
			<th>쿠폰명</th>
			<th>할인율</th>
			<th>사용가능 여부</th>
			<th>사용기한</th>
			<th>제작일</th>
		</tr>
	</thead>
	<tbody>
		<cr:forEach var="row" items="${ps.rows}">
			<cr:set var="cpname_length" value="${fn:length(row['cpname'])}" />
			<tr>
				<!-- 범위 글자수 이상이 되었을 경우 말줄임표가 나오도록 하는 부분 -->
				<cr:if test="${cpname_length>5}">
					<cr:set var="jum" value="dfsdf..."/>
				</cr:if>
				<td>${fn:substring(row['cpname'],0,10)}${jum}</td>
				<td>${row['cprate']}%</td>
				<td>${row['cpuse']}</td>
				<td>${row['cpdate']}</td>
				<td>${fn:substring(row['indate'],0,10)}</td>
			</tr>
		</cr:forEach>
	</tbody>
</table>
</body>
</html>