Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

wintertreey 님의 블로그

JSTL DB연동, Servlet 연습 본문

JSP

JSTL DB연동, Servlet 연습

wintertreey 2024. 7. 3. 09:23

DB연동 연습

<h2>상품 정보(Beans: 전통적 방법으로 출력)</h2>
<table border="1">
<tr>
	<th>코드</th><th>품명</th><th>수량</th><th>단가</th>
</tr>
<%
ArrayList<SangpumDto> list= connclass.getDataAll();
for(SangpumDto s:list){
%>
	<tr>
		<td><%=s.getCode() %></td>
		<td><%=s.getSang() %></td>
		<td><%=s.getSu() %></td>
		<td><%=s.getDan() %></td>
	</tr>
<%	
}
%>
</table>
<br>
<h2>상품정보(Beans:EL, JSTL로 출력)</h2>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%ArrayList<SangpumDto> list2= connclass.getDataAll(); %>
<table border="1">
	<tr>
		<th>코드</th><th>품명</th><th>수량</th><th>단가</th>
	</tr>
<c:forEach var="s" items="<%=list2 %>">
	<tr>
		<td>${s.code}</td>
		<td>${s.sang}</td>
		<td>${s.su}</td>
		<td>${s.dan}</td>
	</tr>
</c:forEach>
</table>

 

Servlet 연습

 

TestJstl.java

@WebServlet("/TestJstl")
public class TestJstl extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String irum = "홍길동";
		request.setAttribute("irum", irum);
		
		Person person = new Person();
		person.setName("한국인");
		request.setAttribute("person", person);
		
		Student student = new Student();
		student.setAge(22);
		request.setAttribute("student", student);
		
		String[] ani = {"댕댕이", "냥이", "뽀미"};
		request.setAttribute("animal", ani);
		
		String[] foods = {"당근", "시금치", "오이"};
		List<Object> list = new ArrayList<Object>();
		list.add(ani);
		list.add(foods);
		request.setAttribute("list", list);
		
		//response.sendRedirect("testjstl.jsp?irum=irum&person=person&list=list");
		//이렇게 적으면, 첫번째적은 irum만 넘어간다.
		request.getRequestDispatcher("testjstl.jsp").forward(request, response);
	}

 

testjstl.jsp

전통적: 안녕 <%=request.getAttribute("irum") %>
<%
out.println(request.getAttribute("irum"));
%>
<br>
EL: 반가워 ${irum } ${requestScope.irum }
<br> <br>
전통적:  
<% Person p = (Person)request.getAttribute("person"); %>  
<%=p.getName() %>  
<% Student s= (Student)request.getAttribute("student"); %>
<%=s.getAge() %> 
<br>
EL: ${person.name} ${student.age}
<br><br>
동물 : ${animal[0]} ${animal[1]} ${animal["2"]}
<br><br>
<c:if test="${list != null }">
	<c:forEach var="a" items="${list }">
		${a[0]}, ${a[1]}, ${a[2]}
	</c:forEach>
</c:if>
<br>
<c:if test="${list != null }">
	<c:forEach var="a" items="${list }">
		<c:forEach var="b" items="${a }">
		${b }
		</c:forEach>
	</c:forEach>
</c:if>
<br>
<c:choose>
	<c:when test="${list eq null }">자료없음</c:when>
	<c:otherwise>자료있음</c:otherwise>
</c:choose>

 

 

예외 처리 <br>
<c:catch var="myErr">
	<%
	int a = 10/0;
	out.println("a: "+a);
	%>
</c:catch>
<c:if test="${myErr != null }">
	에러 발생 : ${myErr.message }
</c:if>
<hr>
계속
<br>
다른 문서 포함<br>
include 지시어 사용: <%@include file="poham.jsp" %>
<br>
jstl 사용: <c:import url="poham.jsp"></c:import>


 

ProductList.java

@WebServlet("/ProductList")
public class ProductList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Product> products = new ArrayList<Product>();
		products.add(new Product("아메리카노", 2000.0, "짱 시원해요", new Date()));
		products.add(new Product("카페라떼", 2500.0, "짱 부드러워요", new Date()));
		products.add(new Product("수박주스", 3000.0, "편하게 마셔요", new Date()));
		products.add(new Product("망고블랜디드", 4000.0, "짱 달콤해요", new Date()));
		
		request.setAttribute("products", products);
		request.getRequestDispatcher("/pshow.jsp").forward(request, response);
	}

 

pshow.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>   
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> 
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.expensive {
	color: red;
	font-weight: bold;
}
</style>
</head>
<body>
<h2>* 제품목록 *</h2>
<c:choose>
	<c:when test="${empty products}">
		<p>제품이 없어요.</p>
	</c:when>
	<c:otherwise>
		<table border="1">
		 <thead>
		  <tr>
		  	<th>제품명</th><th>가격</th><th>설명</th><th>출시일</th>
		  </tr>
		 </thead>
		 <tbody>
		 <c:forEach var="pro" items="${products }">
		 	<tr>
		 		<td>${pro.name}</td> 
		 		<td class='<c:if test="${pro.price >= 3000.0 }">expensive</c:if>'>
		 			${pro.price}
		 		</td>
		 		<td>${pro.description}</td>
		 		<td>${pro.releaseDate}</td>
		 	</tr>
		 </c:forEach>
		 </tbody>
		</table>
	</c:otherwise>
</c:choose>
<h2>제품 통계</h2>
<c:set var="totalProducts" value="${fn:length(products)}"/>
<c:set var="totalPrice" value="0"/>
<c:forEach var="p" items="${products}" varStatus="status">
  <c:set var="totalPrice" value="${totalPrice+ p.price}"/>
</c:forEach>
<p>전체건수: ${totalProducts}</p>
<p>가격평균: <fmt:formatNumber value="${totalPrice / totalProducts}" type="currency" /></p>
<h3> 제품 설명 </h3>
<ul>
	<c:forEach var="p" items="${products}">
		<li><c:out value="${fn:substring(p.description, 0, 5)}"/></li>
	</c:forEach>
</ul>
</body>
</html>

 


JSTL연동 결과 출력하기

<sql:setDataSource var="ds" url="jdbc:mariadb://localhost:3306/test"
driver="org.mariadb.jdbc.Driver"
user="root" password="123"
/>

<sql:query var="rs" dataSource="${ds}">
	select * from sangdata where code >= ? and code <= ?
	<sql:param value="1"/>
	<sql:param value="3"/>
</sql:query>

<table border="1">
 <tr>
 	<th>코드</th><th>품명</th><th>수량</th><th>단가</th>
 </tr>
<c:forEach var="r" items="${rs.rows}">
  <tr>
    <td>${r.code}</td>
    <td>${r.sang}</td>
    <td>${r.su}</td>
    <td>${r.dan}</td>
  </tr>
</c:forEach>
</table>

 

'JSP' 카테고리의 다른 글

JSTL  (0) 2024.07.03
Redirect 리다이렉트 vs Forward 포워드 방식  (0) 2024.07.02
MVC Model2: DB 연동하기  (0) 2024.07.02
MVC Model2: 인터페이스를 사용한 Controller  (0) 2024.07.01
빌드 관리 도구 maven gradle  (0) 2024.07.01