[0504]Java Web開発プロセス🌞


⭐Back-end


JSP


以下の機能を実現するために、コード全体の主な変更部分のみを作成します.

ページ数のみによるページング


list.jsp
<nav class="pager mt-3">
	<h1 class="d-none">페이저</h1>
	<div class="button">이전</div>
	<ul>
		<%for(int i=0; i<5; i++) {%> <!-- 1. 횟수를 수정 -->
               		<!-- 2. lastPage보다 출력되는 게 클 경우 안 나오게 if문 조건처리 -->
			<%if(lastPage >= i+1)  {%> 
				<li><a class="<%=page_ == i+1 ? "text-strong" : "" %>" href="list.jsp?p=<%=i+1 %>&f=<%=field %>&q=<%=query %>"><%=i+1 %></a></li> <!--이렇게 해서 사용자가 검색한 결과 내에서 paging 할 수 있게 하기-->
			<%} %>
		<%} %> 
	<div class="button">다음</div>
</nav>

表の作成


detail.jsp
<table border="1">
      <tr>
        <th>제목</th>  <!-- 컬럼 내에서의 제목: th -->
        <td colspan="3">HI</td> <!-- DB에 해당되는 내용 나오게 하기 -->
      </tr>
      <tr>
        <th>작성일</th>
        <td colspan="3">2021-03-25</td>
      </tr>
      <tr>
        <th>작성자</th>
        <td>admin</td>
        <th>조회수</th>
        <td>25</td>
      </tr>
      <tr>
        <th>첨부파일</th>
        <td colspan="3">test.zip</td>
      </tr>
      <tr>
        <td colspan="4">
          안녕하세요<br>
          인사 드립니다!<br>
        </td>
      </tr>
</table>
<div>
      <a href="list.jsp">목록</a>
</div>

投稿の詳細を表示


list.jsp
<td class="truncate text-align-left"><a href="detail.jsp?id=<%=n.getId()%>"><%=n.getTitle()%></a></td> <!--id를 querystring으로 함께 보내자-->
NoticeService.java
public Notice get(int id) throws ClassNotFoundException, SQLException {
		
	String url = "jdbc:oracle:thin:@hi.namoolab.com:1521/xepdb1";
	String sql = "SELECT * FROM NOTICE WHERE ID = " + id; // 문자열 + 정수 -> 문자열 변환
		
	Class.forName("oracle.jdbc.OracleDriver"); 
	Connection con = DriverManager.getConnection(url, "NEWLEC", "11111"); // 서블릿 프로세스가 끝나면 연결이 끊어짐
	Statement st = con.createStatement();
	ResultSet rs = st.executeQuery(sql);
		
	Notice notice = null;
		
	if(rs.next()) {
			
		// Notice 데이터
		String title = rs.getString("title");
		String writerId = rs.getString("writer_id");
		String content = rs.getString("content");
		Date regDate = rs.getDate("regDate");
		int hit = rs.getInt("hit");
		String files = rs.getString("files");

		notice = new Notice();
		notice.setId(id);
		notice.setTitle(title);
		notice.setWriterId(writerId);
		notice.setContent(content);
		notice.setRegDate(regDate);
		notice.setHit(hit);
		notice.setFiles(files);
	}
		
	rs.close();
	st.close();
	con.close();

	return notice;
 }
detail.jsp
<%
	String id_ = request.getParameter("id"); // 사용자에게 아이디 받기
	int id = Integer.parseInt(id_); // 무조건 id 값이 오게 해서 id 값 념겨주기

	NoticeService noticeService = new NoticeService();
	Notice notice = noticeService.get(id); // 특정한 notice 관련 정보(단일 객체로 얻어오기)를 얻어와야하니까 where절에서 부르기 위한 id를 통해 notice 정보 달라고 하기
 	System.out.println(notice);
 %>  
<table border="1">
      <tr>
        <th>제목</th>  <!-- 컬럼 내에서의 제목: th -->
        <td colspan="3"><%=notice.getTitle() %></td> <!-- NoticeService에서 구현한 코드로 notice에 채워진 값 가져오기 -->
      </tr>
      <tr>
        <th>작성일</th>
        <td colspan="3"><%=notice.getRegDate() %></td>
      </tr>
      <tr>
        <th>작성자</th>
        <td><%=notice.getWriterId() %></td>
        <th>조회수</th>
        <td><%=notice.getHit() %></td>
      </tr>
      <tr>
        <th>첨부파일</th>
        <td colspan="3">test.zip</td>
      </tr>
      <tr>
        <td colspan="4">
          <%=notice.getContent() %>
            </td>
      </tr>
</table>

⭐Front-end


CSS


リストGridを使用して実装


list.html
<section class="open-lecture-content">
    <h1>강의 목록</h1>
      <ul> <!--박스를 a 태그가 감쌀 수 없음-->
          <li>
              <a class="title" href="">오라클 프로그래밍</a> <!--제목이 먼저 오게 하기 -->
              <img src="../images/lecture/img-oracle-sm.png">
              <span class="price">
                  <span>99000원</span>
                  <span><span>10000</span></span>
              </span>
              <span class="info">
                  <span>newlec</span>
                  <span>수정일: 2017-01-01</span>
              </span>
          </li>
      </ul>
</section>
style.css
.open-lecture-content li {
    display: grid;
    height: 90px;
    /*width: 100%; /*default*/
    grid-template-columns: 90px 1fr; /*grid 열*/
    grid-template-rows: repeat(3, 1fr); /*grid 행*/
    grid-template-areas:
    "img title"
    "img price"
    "img info";
    background: url(../images/lecture/bg-title-normal-box.png) no-repeat right bottom;
}

.open-lecture-content li>.title {
    grid-area: title;
}

.open-lecture-content li>img {
    /* float: left;  */
    grid-area: img;
    width: 100%;
}

.open-lecture-content li>.price {
    grid-area: price;
}

.open-lecture-content li>.info {
    grid-area: info;
}

結果画面



AJAX


以下の機能を実現するために、コード全体の主な変更部分のみを記述します.

ページをクリックすると、コンソールウィンドウにページ投稿情報が出力されます。


ex1.html
 <div class="pager"> <!--페이저 구현을 위한 html 코드-->
     <ul>
         <li><a href="">1</a></li> <!-- a태그: 버튼 역할 -->
         <li><a href="">2</a></li>
         <li><a href="">3</a></li>
         <li><a href="">4</a></li>
         <li><a href="">5</a></li>
     </ul>
</div>
NoticeList.java
@WebServlet("/api/notice/list")
public class NoticeList extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		
		try {
			String p = req.getParameter("p"); // 사용자가 페이지 클릭 시 querystring으로 페이지 값 전달
			int page = 1; // 기본값 설정
			
			if(p != null && !p.equals(""))
				page = Integer.parseInt(p); 
			
			NoticeService noticeService = new NoticeService();
			List<Notice> list = noticeService.getList(page, "title", "");
			
			out.println(list); // println이 알아서 toString()으로 변환해서 출력해줌
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
}
ex1.js
window.addEventListener("load", function() {
    var section = document.querySelector("#ex10");
    var pager = section.querySelector(".pager");
	
	pager.onclick = function(e) {
		e.preventDefault();
		
      		// 사용자가 클릭한 것이 a 태그 엘리먼트가 아니라면 함수 동작X
		if(e.target.tagName != "A") 
			return;
		
		// 클릭한 페이지 번호	
		var page = e.target.innerText;
			
		var request = new /*window.*/XMLHttpRequest(); 
      	        // 사용자의 요청이 완료됐을 때 콘솔창에 응답 텍스트 출력
		request.onload = function(e) {
			console.log(request.responseText);
		};
			
		request.open("GET", `../api/notice/list?p=${page}`, true);
		request.send(null);
	}
});

結果画面


コンソールウィンドウから出力される内容は、データベース内の任意のデータであるが、個人情報が含まれているため、隠されている.左側のWebブラウザのページをクリックすると、そのページに表示される投稿に関する情報が右側のコンソールウィンドウに出力されます.

🐥の最後の部分


今日も昨日のようにJSPでDBデータを使ってページのさまざまな機能を実現しています.昨日は授業と少し骨が折れました.昨夜授業の流れを復習したせいか、今日はもっと楽になりました.また、午後はAJAXでバックエンドデータを取得して画面に印刷する練習もしました.
数ヶ月前、Webバックエンドの開発について全く知らずにYouTubeの講座を聞いて実習をしました.当時理解していなかった内容は塾に通っていたときによく理解していたので、勉強を重ねることが大切でした.🙂 今は授業で学んだことを徐々にチームプロジェクトに応用し、実戦練習をしなければならない.