2022. 10. 10. 15:29ㆍDev.Program/Java & Spring
> 회원정보조회
< MemberController.java >
@RequestMapping(value = "/member/info", method = RequestMethod.GET) public String info(HttpSession session, Model model) { String id = (String)session.getAttribute("id"); MemberBean mb = memberService.getMember(id); model.addAttribute("mb", mb); return "/member/info"; } |
< MemberService.java >
public MemberBean getMember(String id); |
< MemberServiceImpl.java >
@Override public MemberBean getMember(String id) { System.out.println("MemberServiceImpl - userCheck()"); return memberDAO.getMember(id); } |
< MemberDAO.java >
public MemberBean getMember(String id); |
< MemberDAOImpl.java >
@Override public MemberBean getMember(String id) { System.out.println("MemberDAOImpl - getMember()"); return sqlSession.selectOne(namespace+".getMember", id); } |
< memberMapper.xml >
<select id="getMember" resultType="com.itwillbs.domain.MemberBean"> SELECT * FROM member WHERE id=#{id} </select> |
> 회원정보 업데이트
< MemberController.java >
// 회원정보 업데이트 @RequestMapping(value = "/member/update", method = RequestMethod.GET) public String update(HttpSession session, Model model) { String id = (String)session.getAttribute("id"); MemberBean mb = memberService.getMember(id); model.addAttribute("mb", mb); return "/member/updateForm"; } // 회원정보 업데이트 @RequestMapping(value = "/member/update", method = RequestMethod.POST) public String updatePost(MemberBean mb) { MemberBean mb2 = memberService.userCheck(mb); if(mb2!=null) { memberService.updateMember(mb); } else { model.addAttribute("msg", "입력하신 정보가 일치하지 않습니다"); return "/member/msg"; } return "redirect:/member/main"; } |
< MemberService.java >
public void updateMember(MemberBean mb); |
< MemberServiceImpl.java >
@Override public void updateMember(MemberBean mb) { System.out.println("MemberServiceImpl - updateMember()"); memberDAO.updateMember(mb); } |
< MemberDAO.java >
public Object updateMember(MemberBean mb); |
< MemberDAOImpl.java >
@Override public Object updateMember(MemberBean mb) { System.out.println("MemberDAOImpl - updateMember()"); return sqlSession.update(namespace+".updateMember", mb); } |
< memberMapper.xml >
<update id="updateMember"> UPDATE member SET name=#{name} WHERE id=#{id} </update> |
> 회원정보 삭제
< MemberController.java >
// 회원정보 삭제 @RequestMapping(value = "/member/delete", method = RequestMethod.GET) public String delete() { return "/member/deleteForm"; } // 회원정보 삭제 @RequestMapping(value = "/member/delete", method = RequestMethod.POST) public String deletePost(MemberBean mb, HttpSession session) { MemberBean mb2 = memberService.userCheck(mb); if(mb2!=null) { memberService.deleteMember(mb); session.invalidate(); } else { model.addAttribute("msg", "입력하신 정보가 일치하지 않습니다"); return "/member/msg"; } return "redirect:/member/main"; } |
< MemberService.java >
public void updateMember(MemberBean mb); |
< MemberServiceImpl.java >
@Override public void deleteMember(MemberBean mb) { System.out.println("MemberServiceImpl - deleteMember()"); memberDAO.deleteMember(mb); } |
< MemberDAO.java >
public void deleteMember(MemberBean mb); |
< MemberDAOImpl.java >
@Override public void deleteMember(MemberBean mb) { System.out.println("MemberDAOImpl - deleteMember()"); sqlSession.delete(namespace+".deleteMember", mb); } |
< memberMapper.xml >
<delete id="deleteMember"> DELETE FROM member WHERE id=#{id} </delete> |
> 회원정보 전체조회
< MemberController.java >
// 회원정보 전체조회 @RequestMapping(value = "/member/list", method = RequestMethod.GET) public String list(Model model) { List<MemberBean> memberList = memberService.getMemberList(); model.addAttribute("memberList", memberList); return "/member/list"; } |
< MemberService.java >
public List<MemberBean> getMemberList(); |
< MemberServiceImpl.java >
@Override public List<MemberBean> getMemberList() { System.out.println("MemberServiceImpl - getMemberList()"); return memberDAO.getMemberList(); } |
< MemberDAO.java >
public List<MemberBean> getMemberList(); |
< MemberDAOImpl.java >
@Override public List<MemberBean> getMemberList() { System.out.println("MemberDAOImpl - getMemberList()"); return sqlSession.selectList(namespace+".getMemberList"); } |
< memberMapper.xml >
<select id="getMemberList" resultType="com.itwillbs.domain.MemberBean"> SELECT * FROM member </select> |
======== BoardController.java
- StudyJSP 에서 board 파일들만 가져오기
< BoardController.java >
@RequestMapping(value = "/board/write", method = RequestMethod.GET) public String insert() { // views/board/writeForm.jsp 이동 return "/board/writeForm"; } |
- 이동
======== BoardBean.java
- StudyJSP 에서 가져오기
======== BoardService.인터페이스 / BoardServiceImpl.java 만들기
package com.itwillbs.service; public interface BoardService { } |
- 인터페이스 틀 만들기
package com.itwillbs.service; import org.springframework.stereotype.Service; @Service public class BoardServiceImpl implements BoardService { } |
- implements 틀 만들기
======== BoardDAO.인터페이스 / BoardDAOImpl.java 만들기
package com.itwillbs.dao; public interface BoardDAO { } |
- BoardDAO 틀 만들기
package com.itwillbs.dao; import org.springframework.stereotype.Repository; @Repository public class BoardDAOImpl implements BoardDAO { } |
- 임플리먼츠
======== boardMapper.xml
- memberMapper 복사해서 쓰기
< BoardController.java >
@Controller public class BoardController { @Inject private BoardService boardService; @RequestMapping(value = "/board/write", method = RequestMethod.GET) public String insert() { // views/board/writeForm.jsp 이동 return "/board/writeForm"; } @RequestMapping(value = "/board/write", method = RequestMethod.POST) public String insertPost(BoardBean bb) { boardService.insertBoard(bb); return "redirect:/board/list"; } } |
- inject
< BoardService.java >
public void insertBoard(BoardBean bb); |
< BoardServiceImpl.java >
@Inject private BoardDAO boardDAO; @Override public void insertBoard(BoardBean bb) { boardDAO.insertBoard(bb); } |
< BoardDAO.java >
public void insertBoard(BoardBean bb); |
< BoardDAOImpl.java >
@Inject private SqlSession sqlSession; private static String namespace="com.itwillbs.mapper.BoardMapper"; @Override public void insertBoard(BoardBean bb) { sqlSession.insert(namespace+".insertBoard", bb); } |
< boardMapper.xml >
<mapper namespace="com.itwillbs.mapper.BoardMapper"> <select id="getMaxNum" resultType="java.lang.Integer"> SELECT MAX(num) FROM board </select> <insert id="insertBoard"> INSERT INTO board(num,name,pass,subject,content,readcount,date,file,re_ref,re_lev,re_seq) VALUES(#{num},#{name},#{pass},#{subject},#{content},#{readcount},#{date},#{file},#{re_ref},#{re_lev},#{re_seq}) </insert> </mapper> |
< Controller.java >
@RequestMapping(value = "/board/list", method = RequestMethod.GET) public String list(Model model) { // List<BoardBean> boardList = getBoardList List<BoardBean> boardList= boardService.getBoardList(); // model 저장 model.addAttribute("boardList",boardList); // views/board/list.jsp 이동 return "/board/list"; } |
< Service.java >
public List<BoardBean> getBoardList(); |
< ServiceImpl.java >
@Override public List<BoardBean> getBoardList() { return boardDAO.getBoardList(); } |
< DAO.java >
public List<BoardBean> getBoardList(); |
< DAOImpl.java >
@Override public List<BoardBean> getBoardList() { return sqlSession.selectList(namespace+".getBoardList"); } |
< Mapper.xml >
<select id="getBoardList" resultType="com.itwillbs.domain.BoardBean"> SELECT * FROM board </select> |
< list.jsp >
<table border="1"> <tr><td>글번호</td><td>글제목</td><td>작성자</td><td>조회수</td><td>작성일</td></tr> <c:forEach var="bb" items="${boardList }"> <tr><td>${bb.num }</td><td>${bb.name }</td><td>${bb.subject }</td> <td>${bb.readcount }</td><td>${bb.date }</td></tr> </c:forEach> </table> |
- 이렇게 여러 개 나오는데 우리는 페이징 처리할 거!
======== domain 패키지 안에 PageBean.java 만들기
- 페이지 관련은 여기서 다 관리할 것!
package com.itwillbs.domain; public class PageBean { private int count; private int pageSize; private String pageNum; private int currentPage; private int startRow; private int endRow; private int pageCount; private int pageBlock; private int startPage; private int endPage; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getPageNum() { return pageNum; } public void setPageNum(String pageNum) { this.pageNum = pageNum; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getStartRow() { return startRow; } public void setStartRow(int startRow) { this.startRow = startRow; } public int getEndRow() { return endRow; } public void setEndRow(int endRow) { this.endRow = endRow; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getPageBlock() { return pageBlock; } public void setPageBlock(int pageBlock) { this.pageBlock = pageBlock; } public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; } public int getEndPage() { return endPage; } public void setEndPage(int endPage) { this.endPage = endPage; } } |
> POST 방식일 때는 데이터가 자동으로 담겨지지만, GET 방식일 때는 안담아짐!
- POST 방식이라 이렇게 BoardBean이라고 하면 자동으로 찾아서 담지만
- GET 방식은 아님! 따로 생성해서 담아줘야함! (매개변수로 안담아옴)
< Controller.java >
@RequestMapping(value = "/board/list", method = RequestMethod.GET) public String list(Model model, HttpServletRequest request) { // PageBean pb 객체생성 PageBean pb=new PageBean(); // 한화면에 보여줄 가져올 글 개수 설정 pb.setPageSize(10); // 현페이지 번호 가져오기 pageNum 파라미터 가져오기 String pageNum=request.getParameter("pageNum"); // 현페이지 번호가 없으면 "1"페이지로 설정 if(pageNum==null) { pb.setPageNum("1"); }else { pb.setPageNum(pageNum); } // List<BoardBean> boardList = getBoardList List<BoardBean> boardList= boardService.getBoardList(pb); // model 저장 model.addAttribute("boardList",boardList); // views/board/list.jsp 이동 return "/board/list"; } |
< Service.java >
public List<BoardBean> getBoardList(PageBean pb); |
< ServiceImpl.java >
@Override public List<BoardBean> getBoardList(PageBean pb) { // pageSize, pageNum 저장 // pageNum => 정수형으로 변경 pb.setCurrentPage(Integer.parseInt(pb.getPageNum())); // 10개씩 잘라서 1페이지 시작하는 행번호 구하기 // int startRow=(currentPage-1)*pageSize+1; 디비단 -1 pb.setStartRow((pb.getCurrentPage()-1)*pb.getPageSize()); // int endRow=currentPage*pageSize; return boardDAO.getBoardList(pb); } |
- DB 단에서는 -1 하면 안됨! (변수명만 들어가야함)
< DAO.java >
public List<BoardBean> getBoardList(PageBean pb); |
< DAOImpl.java >
@Override public List<BoardBean> getBoardList(PageBean pb) { return sqlSession.selectList(namespace+".getBoardList",pb); } |
< Mapper.xml >
<select id="getBoardList" resultType="com.itwillbs.domain.BoardBean"> SELECT * FROM board ORDER BY re_ref DESC, re_seq ASC limit #{startRow},#{pageSize} </select> |
- 여기선 -1 하거나 하면 안되기 때문에 그 부분은 Service 에서 처리해줌
- 10개씩 나옴!
< Service.java >
public Integer getBoardCount(); |
<ServiceImpl.java >
@Override public Integer getBoardCount() { return boardDAO.getBoardCount(); } |
< DAO.java >
public Integer getBoardCount(); |
< DAOImpl.java >
@Override public Integer getBoardCount() { return sqlSession.selectOne(namespace+".getBoardCount"); } |
< Mapper.xml >
<select resultType="java.lang.Integer" id="getBoardCount"> SELECT COUNT(*) FROM board </select> |
< Controller.java >
// count setCount()호출 시 pageCount pageBlock startPage endPage 값 설정(계산만 하고 DB 작업은 필요 없음) pb.setCount(boardService.getBoardCount()); // model 저장 model.addAttribute("boardList", boardList); model.addAttribute("pb", pb); |
- 이 두 줄 추가!
- setCount() 호출 시 계산하도록 함수 만들어줄 것
< PageBean.java >
public void setCount(int count) { this.count = count; // count setCount()호출 시 pageCount pageBlock startPage endPage 값 설정(계산만 하고 DB 작업은 필요 없음) init(); } public void init() { // 전체 페이지수 구하기 pageCount= count / pageSize + (count%pageSize==0?0:1); // 한화면에 보여줄 페이지 개수 pageBlock=10; // 한화면에 보여줄 시작페이지 번호 구하기 startPage=(currentPage-1)/pageBlock*pageBlock+1; // 한화면에 보여줄 끝페이지 번호 구하기 endPage=startPage+pageBlock-1; if(endPage > pageCount){ endPage=pageCount; } } |
- 페이징 처리!
< list.jsp >
<h1>글목록 [ 전체글개수 : ${pb.count} ]</h1> |
- 전체글개수 가져와지는지 보기
< list.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>WebContent/board/list.jsp</h1> <h3><a href="<c:url value='/board/write'/>">글쓰기</a></h3> <h1>글목록 [ 전체글개수 : ${pb.count } ]</h1> <table border="1"> <tr><td>글번호</td><td>글제목</td><td>작성자</td><td>조회수</td><td>작성일</td></tr> <c:forEach var="bb" items="${boardList }"> <tr><td>${bb.num }</td><td>${bb.subject }</td><td>${bb.name }</td> <td>${bb.readcount }</td><td>${bb.date }</td></tr> </c:forEach> <% //답글이면 level.gif re.gif 보이기 // int wid=0; // if(bb.getRe_lev()>0){ // lev 1 => 10 2=>20 // wid=bb.getRe_lev()*10; %> <img src="level.gif" width="<%//=wid%>" height="15"> <img src="re.gif"> <% // } %> </table> <c:if test="${pb.startPage > pb.pageBlock}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage - pb.pageBlock}'/>">[이전]</a> </c:if> <c:forEach var="i" begin="${pb.startPage }" end="${pb.endPage }" step="1"> <a href="<c:url value='/board/list?pageNum=${i}'/>">${i }</a> </c:forEach> <c:if test="${pb.endPage < pb.pageCount}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage + pb.pageBlock}'/>">[다음]</a> </c:if> </body> </html> |
- 이미지를 제외한 나머지 부분 해보기
- 페이징 처리되서 나옴!
> 이미지 처리
- webapp > resources > img 폴더 만들기
- ======== img 폴더
- level.gif / re.gif 옮기기
< list.jsp >
<c:forEach var="bb" items="${boardList }"> <tr><td>${bb.num }</td> <td> <c:if test="${bb.re_lev > 0}"> <c:set var="wid" value="${bb.re_lev * 10}"></c:set> <img src="<c:url value='/resources/img/level.gif'/>" width="${wid}"> <img src="<c:url value='/resources/img/re.gif'/>"> </c:if> ${bb.subject }</td><td>${bb.name }</td> <td>${bb.readcount }</td><td>${bb.date }</td></tr> </c:forEach> |
- 이미지 파일이 있는 곳을 지정함
- 들여쓰기도 설정
- 답글과 답글의답글 구분가능
< list.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>WebContent/board/list.jsp</h1> <h3><a href="<c:url value='/board/write'/>">글쓰기</a></h3> <h1>글목록 [ 전체글개수 : ${pb.count } ]</h1> <table border="1"> <tr><td>글번호</td><td>글제목</td><td>작성자</td><td>조회수</td><td>작성일</td></tr> <c:forEach var="bb" items="${boardList }"> <tr><td>${bb.num }</td> <td> <c:if test="${bb.re_lev > 0}"> <c:set var="wid" value="${bb.re_lev * 10}"></c:set> <img src="<c:url value='/resources/img/level.gif'/>" width="${wid}"> <img src="<c:url value='/resources/img/re.gif'/>"> </c:if> <a href="<c:url value='/board/content?num=${bb.num}&pageNum=${pb.pageNum}'/>"> ${bb.subject }</a> </td><td>${bb.name }</td> <td>${bb.readcount }</td><td>${bb.date }</td></tr> </c:forEach> </table> <c:if test="${pb.startPage > pb.pageBlock}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage - pb.pageBlock}'/>">[이전]</a> </c:if> <c:forEach var="i" begin="${pb.startPage }" end="${pb.endPage }" step="1"> <a href="<c:url value='/board/list?pageNum=${i}'/>">${i }</a> </c:forEach> <c:if test="${pb.endPage < pb.pageCount}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage + pb.pageBlock}'/>">[다음]</a> </c:if> </body> </html> |
- a태그 추가! 최종 코드!
> 글 디테일 화면 혼자 해보기
< BoardController.java >
@RequestMapping(value = "/board/content", method = RequestMethod.GET) public String content(Model model, HttpServletRequest request) { int num = Integer.parseInt(request.getParameter("num")); int pageNum = Integer.parseInt(request.getParameter("pageNum")); BoardBean bb = boardService.getContent(num); model.addAttribute("bb", bb); model.addAttribute("pageNum", pageNum); return "/board/content"; } |
- pageNum 도 가져가야함!
< BoardService.java >
public BoardBean getContent(int num); |
< BoardServiceImpl.java >
@Override public BoardBean getContent(int num) { return boardDAO.getContent(num); } |
< BoardDAO.java >
public BoardBean getContent(int num); |
< BoardDAOImpl.java >
@Override public BoardBean getContent(int num) { return sqlSession.selectOne(namespace+".getContent",num); } |
< boardMapper.xml >
<select id="getContent" resultType="com.itwillbs.domain.BoardBean"> SELECT * FROM board WHERE num=#{num} </select> |
< content.jsp >
<body> <h1>views/board/content.jsp</h1> <table border="1"> <tr><td>글번호</td><td>${bb.num }</td><td>작성일</td><td>${bb.date }</td></tr> <tr><td>글쓴이</td><td>${bb.name }</td><td>조회수</td><td>${bb.readcount }</td></tr> <tr><td>제목</td><td colspan="3">${bb.subject }</td></tr> <tr><td>파일</td><td colspan="3"> <a href="../upload/<%//=bb.getFile() %>"><%//=bb.getFile() %></a> <img src="../upload/<%//=bb.getFile() %>" width="100" height="100"> <a href="file_down.jsp?file_name=<%//=bb.getFile() %>"><%//=bb.getFile() %></a></td></tr> <tr><td>내용</td><td colspan="3">${bb.content }</td></tr> <tr><td colspan="4"> <input type="button" value="답글쓰기" onclick="location.href='/board/reWriteForm.jsp?num=${bb.num }&re_ref=${bb.re_ref }&re_lev=${bb.re_lev }&re_seq=${bb.re_seq }'"> <input type="button" value="글수정" onclick="location.href='/board/updateForm.jsp?num=${bb.num }&pageNum=${pageNum }'"> <input type="button" value="글삭제" onclick="location.href='/board/deleteForm.jsp?num=${bb.num }&pageNum=${pageNum }'"> <input type="button" value="글목록" onclick="location.href='/board/list.jsp?pageNum=${pageNum }'"></td></tr> </table> </body> |
< FunWeb >
>>>>>>>> FunWeb
- Next
- com.itwillbs.FunWeb
- Finish
< 기본 세팅하기 >
> JDK 설정
- 프로젝트 우클릭 - Properties
- 1.8버전
- 1.8버전
< pom.xml >
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> |
- 설치하기(코드 추가)
< web.xml >
<filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
- 한글설정(코드 추가)
< servlet-context.xml >
<context:component-scan base-package="com.itwillbs.controller" /> <context:component-scan base-package="com.itwillbs.service" /> <context:component-scan base-package="com.itwillbs.dao" /> |
- 추가
- Project2 에서 4개 복사해오기
< root-context.xml >
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/jspdb1"/> <property name="username" value="jspid"/> <property name="password" value="jsppass"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:/mybatis-config.xml"/> <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> |
- DB 연동하는 코드 추가
- Project2 에서 mappers 파일이랑 mybatis-config.xml 파일 가져오기
- 작동시켜보면 이렇게 시작화면 나와야함(이클립스 켜져있으면 끄고 작동시키기)
>>>>>>>> 이렇게 하면 기본세팅은 끝! (준비완료단계)
- classes(X) ⇒ resources(O) 파일 에는 이미지 파일, views 에는 jsp 파일 들어감
- classes 아니고 위에 resources 에 넣기ㅠㅠㅠㅠ
< MemberController.java >
@RequestMapping(value = "/member/insert", method = RequestMethod.GET) public String insert() { // views/member/join.jsp 이동 return "/member/join"; } |
- 수정
- 실행화면 ( css 가 다 깨져서 나온다 )
> 스타일을 연결시켜줘야함
< join.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" type="text/css"> <link href="<c:url value='/resources/css/subpage.css'/>" rel="stylesheet" type="text/css"> |
- 태그 라이브러리 추가 후 경로 설정해주기
< top.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <header> <% // String id = (String)세션값 가져오기 String id=(String)session.getAttribute("id"); // 세션값 없으면 login join // 있으면 ..님 logout if(id==null){ %><div id="login"><a href="../member/login.jsp">login</a> | <a href="../member/join.jsp">join</a></div><% }else{ %><div id="login"><%=id %>님 | <a href="../member/logout.jsp">logout</a> | 회원정보수정</div><% } %> <div class="clear"></div> <!-- 로고들어가는 곳 --> <div id="logo"><img src="<c:url value='/resources/images/logo.gif'/>" width="265" height="62" alt="Fun Web"></div> <!-- 로고들어가는 곳 --> <nav id="top_menu"> <ul> <li><a href="../main/main.jsp">HOME</a></li> <li><a href="../company/welcome.jsp">COMPANY</a></li> <li><a href="#">SOLUTIONS</a></li> <li><a href="../center/notice.jsp">CUSTOMER CENTER</a></li> <li><a href="#">CONTACT US</a></li> </ul> </nav> </header> |
< bottom.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <footer> <hr> <div id="copy">All contents Copyright 2011 FunWeb 2011 FunWeb Inc. all rights reserved<br> Contact mail:funweb@funwebbiz.com Tel +82 64 123 4315 Fax +82 64 123 4321</div> <div id="social"><img src="<c:url value='/resources/images/facebook.gif'/>" width="33" height="33" alt="Facebook"> <img src="<c:url value='/resources/images/twitter.gif'/>" width="34" height="34" alt="Twitter"></div> </footer> |
- 경로설정 후 깨짐 없이 잘나옴
< join.jsp >
<form action='<c:url value='/member/insert'/>' id="join" name="fr" method="post"> |
- form action 부분도 경로 수정!
< MemberController.java >
@RequestMapping(value = "/member/login", method = RequestMethod.GET) public String login() { return "/member/login"; } |
- 우리는 login.jsp 로 가야하므로 여기 경로 수정
< login.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" type="text/css"> <link href="<c:url value='/resources/css/subpage.css'/>" rel="stylesheet" type="text/css"> |
- 태그 라이브러리랑 css 경로 맞춰주기
<form action="<c:url value='/member/login'/>" id="join" name="fr" method="post"> |
- form action 에 경로도 수정
- 로그인 페이지가 잘 나오면 성공!
>
- msg.jsp 파일 가져오기(Project2에서)
< MemberController.java >
@RequestMapping(value = "/member/login", method = RequestMethod.POST) public String loginPost(MemberBean mb, HttpSession session, Model model) { System.out.println(mb.getId()); System.out.println(mb.getPass()); System.out.println("로그인처리"); // 리턴값 MemberBean mb2 = userCheck(mb); MemberBean mb2 = memberService.userCheck(mb); // 아이디 비밀번호 일치하면 mb2 회원정보 모두 가져오기 if(mb2!=null) { // 일치 // 세션값 생성 "id", id session.setAttribute("id", mb.getId()); return "redirect:/member/main"; } else { // 아이디 없음, 비밀번호 틀림 model.addAttribute("msg", "입력하신 정보가 일치하지 않습니다"); // views/member/msg.jsp 이동 return "/member/msg"; } } // 메인으로 이동 @RequestMapping(value = "/member/main", method = RequestMethod.GET) public String main() { return "/main/main"; } |
- main 폴더 내의 main.jsp 로 이동하게끔 경로 설정
< main.jsp >
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" type="text/css"> <link href="<c:url value='/resources/css/subpage.css'/>" rel="stylesheet" type="text/css"> |
- 태그 라이브러리 추가 및 css 경로 설정
- 로그인해서 main 에서 이렇게 ***님 하고 뜨면 성공!
<script src="<c:url value='/resources/script/jquery-3.5.0.js'/>"></script> <img src="<c:url value='/resources/images/main_img.jpg'/>" width="971" height="282"> |
- 두개 경로도 수정!
< HomeController.java >
@RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { return "redirect:/member/main"; } |
- 시작페이지 메인페이지로 설정
< top.jsp >
<a href="<c:url value='/member/login'/>"> <a href="<c:url value='/member/logout'/>"> |
< 파일 업로드 : 설정하기 >
> 코드 복사해오기
< pom.xml >
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> |
- pom.xml 에 추가
< servlet-context.xml >
- CommonsMultipartResolver
- id 도 자동완성
<!-- 파일 업로드 프로그램 설정 --> <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <beans:property name="maxUploadSize" value="10485760"/> <!-- 10메가까지 --> </beans:bean> <!-- 업로드 폴더 설정 --> <beans:bean id="uploadPath" class="java.lang.String"> <!-- 업로드 경로 : 자기 컴퓨터에 맞게 설정 \ 는 특수문자로 인식하기 위해 \\ 로 두번적음 --> <beans:constructor-arg value="C:\\Users\\ITWILL\\Documents\\workspace-sts-3.9.12.RELEASE\\FunWeb\\src\\main\\webapp\\resources\\upload"/> </beans:bean> |
< BoardController.java >
@RequestMapping(value = "/board/fwrite", method = RequestMethod.GET) public String finsert() { // views/board/writeForm.jsp 이동 return "/center/fwriteForm"; } @RequestMapping(value = "/board/fwrite", method = RequestMethod.POST) public String finsertPost(BoardBean bb) { boardService.insertBoard(bb); return "redirect:/center/list"; } |
- 추가
< fwriteForm.jsp >
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> |
- 태그라이브러리 추가
<link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" type="text/css"> <link href="<c:url value='/resources/css/subpage.css'/>" rel="stylesheet" type="text/css"> |
- css 경로 설정
<form action="<c:url value='/board/fwrite'/>" method="post" enctype="multipart/form-data"> |
- 폼액션 경로설정
< BoardController.java >
- 파일 저장할 곳 가져오기
- 스프링에서 제공하는 프로그램
- 실제 파일은 MultipartFile 인 file 에 있다(file.getBytes())
- 이걸 복사해서 uploadPath 안에 saveName(랜덤이름)을 넣어줄 거(=target)
@RequestMapping(value = "/board/fwrite", method = RequestMethod.POST) public String finsertPost(HttpServletRequest request, MultipartFile file) throws Exception { System.out.println("/board/fwrite finsertPost"); // 첨부파일 받아서 => upload 폴더에 넣음 System.out.println("원파일이름 : " + file.getOriginalFilename()); System.out.println("파일크기 : " + file.getSize()); System.out.println("파일타입 : "+ file.getContentType()); // System.out.println("첨부파일 : " + file.getBytes()); // 첨부파일 자체 // 모든 파일 이름 랜덤하게 변경하기 => 동일한 파일 이름이 들어오면 파일이름 변경 UUID uid = UUID.randomUUID(); String saveName = uid.toString() + "_" + file.getOriginalFilename(); System.out.println(saveName); // 파일을 업로드 폴더에 넣기(복사) File target = new File(uploadPath, saveName); FileCopyUtils.copy(file.getBytes(), target); // BoardBean 객체 생성 BoardBean bb = new BoardBean(); // => 멤버변수 <- 파라미터 가져와서 저장 bb.setName(request.getParameter("name")); bb.setPass(request.getParameter("pass")); bb.setSubject(request.getParameter("subject")); bb.setContent(request.getParameter("content")); bb.setFile(saveName); boardService.insertBoard(bb); return "redirect:/board/list"; } |
- /board/list 로 넘어가면 center 폴더의 notice로 넘어가게 바꿔주기!
> 실행해보기
- 글쓰기
- 콘솔창
- 데이터 추가하면 이렇게 파일 들어간 거 볼수있다(내가 넣은 파일 : 데이터추가.txt)
- center 폴더에 level.gif / re.gif 넣기
<%@page import="java.text.SimpleDateFormat"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" type="text/css"> <link href="<c:url value='/resources/css/subpage.css'/>" rel="stylesheet" type="text/css"> <!--[if lt IE 9]> <![endif]--> <!--[if IE 6]> <script src="../script/DD_belatedPNG_0.0.8a.js"></script> <script> /* EXAMPLE */ DD_belatedPNG.fix('#wrap'); DD_belatedPNG.fix('#main_img'); </script> <![endif]--> </head> <body> <div id="wrap"> <!-- 헤더들어가는 곳 --> <!-- 헤더들어가는 곳 --> <jsp:include page="../inc/top.jsp"/> <!-- 헤더들어가는 곳 --> <!-- 본문들어가는 곳 --> <!-- 메인이미지 --> <div id="sub_img_center"></div> <!-- 메인이미지 --> <!-- 왼쪽메뉴 --> <nav id="sub_menu"> <ul> <li><a href="../center/notice.jsp">Notice</a></li> <li><a href="#">Public News</a></li> <li><a href="../center/fnotice.jsp">Driver Download</a></li> <li><a href="#">Service Policy</a></li> </ul> </nav> <!-- 왼쪽메뉴 --> <!-- 게시판 --> <article> <h1>Notice</h1> <table id="notice"> <tr><th class="tno">No.</th> <th class="ttitle">Title</th> <th class="twrite">Writer</th> <th class="tdate">Date</th> <th class="tread">Read</th></tr> <c:forEach var="bb" items="${boardList }"> <tr><td>${bb.num }</td> <td> <c:if test="${bb.re_lev > 0}"> <c:set var="wid" value="${bb.re_lev * 10 }"/> <img src="<c:url value='/resources/images/center/level.gif'/>" width="${wid }"> <img src="<c:url value='/resources/images/center/re.gif'/>"> </c:if> <a href="<c:url value='/board/content?num=${bb.num}&pageNum=${pb.pageNum}'/>">${bb.subject }</a></td><td>${bb.name }</td> <td>${bb.readcount }</td><td>${bb.date }</td></tr> </c:forEach> </table> <div id="table_search"> <c:if test="${empty sessionScope.id}"> <input type="button" value="글쓰기" class="btn" onclick="location.href=<c:url value='/board/write'/>"> <c:redirect url="./login"/> </c:if> </div> <div id="table_search"> <form action="noticeSearch.jsp" method="post"> <input type="text" name="search" class="input_box"> <input type="submit" value="search" class="btn"> </form> </div> <div class="clear"></div> <div id="page_control"> <c:if test="${pb.startPage > pb.pageBlock}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage - pb.pageBlock}'/>">Prev</a> </c:if> <c:forEach var="i" begin="${pb.startPage}" end="${pb.endPage}" step="1"> <a href="<c:url value='/board/list?pageNum=${i}'/>">${i }</a> </c:forEach> <c:if test="${pb.endPage < pb.pageCount}"> <a href="<c:url value='/board/list?pageNum=${pb.startPage + pb.pageBlock}'/>">Next</a> </c:if> </div> </article> <!-- 게시판 --> <!-- 본문들어가는 곳 --> <div class="clear"></div> <!-- 푸터들어가는 곳 --> <jsp:include page="../inc/bottom.jsp" /> <!-- 푸터들어가는 곳 --> </div> </body> </html> |
'Dev.Program > Java & Spring' 카테고리의 다른 글
[Spring] - (6) ajax, AOP (0) | 2022.10.10 |
---|---|
[Spring] - (4)MyBatis / 설정 및 연동 (0) | 2022.10.09 |
[Spring] - (3)데이터베이스 연동 (0) | 2022.10.09 |
[Spring] - (2) (0) | 2022.10.09 |
[Spring] - (1)설치 및 설정하기 (0) | 2022.10.09 |