-
스프링 서버프로그램 구현기타/과제 2021. 2. 16. 16:58
프로그램 목표
회원관련 테이블과 다른 테이블의 연동
구현기능
회원 개개인의 독립적인 가계부 게시판 (작성, 수정, 삭제)
회원제 게시판 (작성, 수정, 삭제, 답글)
회원 기능 (회원가입, 로그인)
servlet-context.xml 설정
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 스프링의 여러가지 값들을 사용하기 편하게 설정해주는 것 --> <annotation-driven /> <!-- resources폴더 안의 소스를 사용할 수 있게 해준다 --> <resources mapping="/resources/**" location="/resources/" /> <resources mapping="/resources/css" location="/resources/css/" /> <!-- 웹상 앞뒤 경로를 만들어 준다 list라고 날렸을 경우 자동으로 /WEB-INF/views/list.jsp 이렇게 만들어준다 --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <!-- 베이스 패키지를 어디서부터 스캔할지 정해준다 --> <context:component-scan base-package="com.sjw.mybatisboard" /> <context:component-scan base-package="com.javalec.spring_security_pjt" /> <!-- 오라클 db연동부분 --> <beans:bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" /> <beans:property name="username" value="mvcboard" /> <beans:property name="password" value="mvcboard" /> </beans:bean> <beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource"></beans:property> <beans:property name="mapperLocations" value="classpath:com/sjw/mybatisboard/mapper/*.xml"></beans:property> </beans:bean> <beans:bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <beans:constructor-arg index="0" ref="sqlSessionFactory"> </beans:constructor-arg> </beans:bean> </beans:beans>
스프링은 크게 xml, jsp페이지, controller, service, dao, dto로 나뉘는 것 같다
mapper에서 쿼리문을 작성
jsp페이지에서 실제 눈에 보이는 틀을 구성
controller에서 서로 프로그램들을 연결 및 제어
service는 실제 동작되는 프로그램들
인터페이스 dao는 실행되는 동작들을 정의
dto에서는 데이터베이스의 객체를 만들어준다 (get, set, toString)
HBContoller
//컨트롤러라고 붙여줘야 스캔이 된다. //클래스에도 맵핑이 가능 @Controller @RequestMapping("/homebook") public class HBContoller { IBoarderService service; //디비정보 SqlSession sqlSession; @Autowired public void setSqlSession(SqlSession sqlSession) { this.sqlSession = sqlSession; // 혹 다른쪽에서 필요하면 사용하려고 임의의 클래스에 템플릿을 지정했음 Constant.sqlSession = this.sqlSession; } //가계부 목록 @RequestMapping("/HBlist") public String HBlist(HttpSession session, HttpServletRequest request, Model model) { System.out.println("list()"); model.addAttribute("request", request); //저장된 객체값을 가져온다 model.addAttribute("session", session); //저장된 세션값을 넣을 공간 service = new HBListService(); service.execute(model); return "homebook/HBlist"; } }
참고하자면 컨트롤러에 등록하지 않은 jsp페이지로는 넘어갈 수 없다
새로운 페이지를 만들었을 때 @RequestMapping("/페이지명") 해주는 걸 잊지 않기
HBListService
public class HBListService implements IBoarderService { private SqlSession sqlSession=Constant.sqlSession; public HBListService() {} @Override public void execute(Model model) { HDao dao = sqlSession.getMapper(HDao.class); Map<String, Object> map = model.asMap(); HttpServletRequest request = (HttpServletRequest) map.get("request"); HttpSession session = (HttpSession) map.get("session"); //저장된 세션값을 가져오는 부분 String mid = (String) session.getAttribute("id"); if(mid==null) { ArrayList<HDto> htos = dao.HBAllList(); model.addAttribute("list", htos); System.out.println(mid); }else { ArrayList<HDto> htos = dao.HBlist(mid); model.addAttribute("list", htos); System.out.println(mid); } } }
세션의 사용법을 조금 알게 된 부분
목록을 불러오는 쿼리문
<!-- 가계부 목록 --> <select id="HBlist" parameterType="string" resultType="com.sjw.mybatisboard.dto.HDto"> select serialno, mId, day, section, accounttitle, remark, revenue, expense from homebook where mId = #{param1} order by day desc </select>
HBlist.jsp
<div class="title"><%=xid%>님 가계부 목록</div> <table class="hb_list_table"> <thead> <tr> <th>번호</th> <th>작성자</th> <th>날짜</th> <th>분류</th> <th>결제항목</th> <th>비고</th> <th>수입</th> <th>지출</th> <th>수정/삭제</th> </tr> </thead> <tbody> <c:forEach items="${list}" var="HBlist" > <tr> <td>${HBlist.serialno}</td> <td>${HBlist.mId }</td> <td>${HBlist.day}</td> <td>${HBlist.section}</td> <td>${HBlist.accounttitle}</td> <td>${HBlist.remark}</td> <td>${HBlist.revenue}</td> <td>${HBlist.expense}</td> <td> <a class="abtn" href="HBcontent_view?serialno=${HBlist.serialno}">수정</a> <a class="abtn" href="HBdelete?serialno=${HBlist.serialno}">삭제</a> </td> </tr> </c:forEach> </tbody> </table> <div class="txt_cn pdt20"><a href="HBwrite_view">가계부작성</a></div>
목록은 forEach문으로 받아서 돌렸다.
서비스에서 model.addAttribute("list", htos) list라고 모델 객체를 만들었고
jsp로 불러올때는 "list"를 ${}안에 넣어주면 불러올 수 있다. ${객체.필드} 하면 원하는 필드를 불러올 수 있다.
그리고 core 태그에 관하여
게시판을 만들다 보면 본인글만 수정 삭제가 가능해야한다
이걸 어떻게 구현할까 하다가 if문을 이용해 저장된 세션 id값과 작성한 글 id가 같다면 버튼이 보이게 만들어 주었다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page import="com.sjw.mybatisboard.dto.*" %> <%@ page import="com.sjw.mybatisboard.service.*" %> <%@ page import="com.sjw.mybatisboard.dao.*"%> <%@ page import="java.sql.*"%> <%@ page import="java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@include file="header.jsp"%> <div class="title">게시물 읽기 및 수정</div> <form action="modify" method="post"> <table class="hb_form_table"> <input type="hidden" name="bId" value="${content_view.bId}"> <tr> <td> 번호 </td> <td> ${content_view.bId} </td> </tr> <tr> <td> 히트 </td> <td> ${content_view.bHit} </td> </tr> <tr> <td> 이름 </td> <td>${content_view.bName}</td> </tr> <tr> <td> 제목 </td> <td> <input type="text" name="bTitle" value="${content_view.bTitle}"></td> </tr> <tr> <td> 내용 </td> <td> <textarea rows="10" name="bContent" >${content_view.bContent}</textarea></td> </tr> <tr > <td colspan="2"> <div class="hidden"><c:set var="ids" value="${content_view.bName}"/></div> <% String wid = (String) pageContext.getAttribute("ids"); if(xid.equals(wid)){ %> <input type="submit" value="수정"> <a href="delete?bId=${content_view.bId}">삭제</a> <% } else{ %> <a href="reply_view?bId=${content_view.bId}">답변</a> <% } %> <a href="list">목록보기</a> </td> </tr> </table> </form> </body> </html>
만일 인클루드가 안될 경우 pom.xml에서 추가해주면 된다
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
var="변수명" value="${변수로 만들 모델객체 필드명}"
<c:set var="ids" value="${content_view.bName}"/>
jstl 변수를 jsp 변수로 만드는 방법은 pageContext.getAttribute("jstl변수이름")
문자열을 비교하는 거라 ==보단 이퀄스를 사용했다
<% String wid = (String) pageContext.getAttribute("ids"); if(xid.equals(wid)){ %> <input type="submit" value="수정"> <a href="delete?bId=${content_view.bId}">삭제</a> <% } else{ %> <a href="reply_view?bId=${content_view.bId}">답변</a> <% } %>
<tr> <td> 내용 </td> <td> <% String wid = (String) pageContext.getAttribute("ids"); if(xid.equals(wid)){ %> <textarea rows="10" name="bContent" >${content_view.bContent}</textarea> <% } else{ %> ${content_view.bContent} <% } %> </td> </tr>
그러면 아래와 같이 같은 페이지라도 보이는 버튼과 내용이 다르다
더 간단하거나 깔끔한 방법은 아직 찾을 수 없었다 ㅠㅠ
'기타 > 과제' 카테고리의 다른 글
[데이터사이언스] 빅데이터 관련 과제 (0) 2021.04.19 TCP / UDP 통신에 관하여 (0) 2021.01.18 리눅스 명령어 치트시트 정리 (0) 2021.01.15 2020.11.30 시험문제 풀이 (sql 질의 작성) (0) 2020.11.27 JDBC를 이용해 테이블 만들기 과제2 (0) 2020.11.24