728x90
Spring - 게시판 만들기 (목록, 글쓰기, 상세보기, 수정, 삭제 구현)
1. 프로젝트 환경설정, 테이블 생성
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <!-- 프로젝트 이름, 컨텍스트 패스 --> <artifactId>spring02</artifactId> <name>spring02</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.8</java-version> <!-- 최신 버전은 4.3.3이지만 호환성을 위해 4.3.0으로 조정함 --> <org.springframework-version>4.3.0.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.7.21</org.slf4j-version> </properties> <repositories> <!-- oracle관련 --> <repository> <id>codelds</id> <url>https://code.lds.org/nexus/content/groups/main-repo</url> </repository> </repositories> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</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> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency> <dependency> <groupId>org.bgee.log4jdbc-log4j2</groupId> <artifactId>log4jdbc-log4j2-jdbc4</artifactId> <version>1.16</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <!-- logback 로깅 관련 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project> | cs |
root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!-- 드라이버 클래스 이름이 변경됨 --> <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property> <!-- 연결문자열에 log4jdbc가 추가됨 --> <property name="url" value="jdbc:log4jdbc:oracle:thin:@localhost:1521:orcl" /> <property name="username" value="spring" /> <property name="password" value="1234" /> </bean> <!-- SqlSessionFactory 객체 주입 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:/mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property> </bean> <!-- SqlSession 객체 주입 --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> </beans> | cs |
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 http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <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> <!-- 스프링 빈을 태그로 등록하지 않고 자동으로 검색(auto scan) --> <context:component-scan base-package="com.example.spring02" /> </beans:beans> | cs |
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.example.spring02" /> </typeAliases> </configuration> | cs |
테이블 생성 sql
-- 게시판 테이블 생성 create table tbl_board( bno number not null, -- 게시물 번호 title varchar2(200) not null, -- 제목 content varchar2(4000), -- 내용 writer varchar2(50) not null, -- 이름 regdate date default sysdate, -- 작성일자 viewcnt number default 0, -- 조회수 primary key(bno) -- 기본키 설정 ); | cs |
2. 게시판 목록, 글쓰기, 상세보기(조회수 증가처리), 수정, 삭제 처리
01) Controller(흐름제어)
BoardController
package com.example.spring02.controller.board; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.example.spring02.model.board.dto.BoardVO; import com.example.spring02.service.board.BoardService; @Controller // 현재 클래스를 컨트롤러 빈(bean)으로 등록 @RequestMapping("/board/*") public class BoardController { // 의존관계 주입 => BoardServiceImpl 생성 // IoC 의존관계 역전 @Inject BoardService boardService; // 01. 게시글 목록 @RequestMapping("list.do") public ModelAndView list() throws Exception{ List<BoardVO> list = boardService.listAll(); // ModelAndView - 모델과 뷰 ModelAndView mav = new ModelAndView(); mav.setViewName("board/list"); // 뷰를 list.jsp로 설정 mav.addObject("list", list); // 데이터를 저장 return mav; // list.jsp로 List가 전달된다. } // 02_01. 게시글 작성화면 // @RequestMapping("board/write.do") // value="", method="전송방식" @RequestMapping(value="write.do", method=RequestMethod.GET) public String write(){ return "board/write"; // write.jsp로 이동 } // 02_02. 게시글 작성처리 @RequestMapping(value="insert.do", method=RequestMethod.POST) public String insert(@ModelAttribute BoardVO vo) throws Exception{ boardService.create(vo); return "redirect:list.do"; } // 03. 게시글 상세내용 조회, 게시글 조회수 증가 처리 // @RequestParam : get/post방식으로 전달된 변수 1개 // HttpSession 세션객체 @RequestMapping(value="view.do", method=RequestMethod.GET) public ModelAndView view(@RequestParam int bno, HttpSession session) throws Exception{ // 조회수 증가 처리 boardService.increaseViewcnt(bno, session); // 모델(데이터)+뷰(화면)를 함께 전달하는 객체 ModelAndView mav = new ModelAndView(); // 뷰의 이름 mav.setViewName("board/view"); // 뷰에 전달할 데이터 mav.addObject("dto", boardService.read(bno)); return mav; } // 04. 게시글 수정 // 폼에서 입력한 내용들은 @ModelAttribute BoardVO vo로 전달됨 @RequestMapping(value="update.do", method=RequestMethod.POST) public String update(@ModelAttribute BoardVO vo) throws Exception{ boardService.update(vo); return "redirect:list.do"; } // 05. 게시글 삭제 @RequestMapping("delete.do") public String delete(@RequestParam int bno) throws Exception{ boardService.delete(bno); return "redirect:list.do"; } } | cs |
02) Service(비지니스로직, DB연동 이외의 작업)
BoardService(인터페이스)
package com.example.spring02.service.board; import java.util.List; import javax.servlet.http.HttpSession; import com.example.spring02.model.board.dao.BoardDAO; import com.example.spring02.model.board.dto.BoardVO; public interface BoardService { // 01. 게시글 작성 public void create(BoardVO vo) throws Exception; // 02. 게시글 상세보기 public BoardVO read(int bno) throws Exception; // 03. 게시글 수정 public void update(BoardVO vo) throws Exception; // 04. 게시글 삭제 public void delete(int bno) throws Exception; // 05. 게시글 전체 목록 public List<BoardVO> listAll() throws Exception; // 06. 게시글 조회 public void increaseViewcnt(int bno, HttpSession session) throws Exception; } | cs |
BoardServiceImpl(인터페이스 구현 클래스)
게시글 쓰기처리(태그문자 처리, 공백문자 처리, 줄바꿈 문자처리)
게시글 조회수 증가 처리(일정 시간동안 조회수 증가하지 않도록 처리)
package com.example.spring02.service.board; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Service; import com.example.spring02.model.board.dao.BoardDAO; import com.example.spring02.model.board.dto.BoardVO; @Service public class BoardServiceImpl implements BoardService { @Inject BoardDAO boardDao; // 01. 게시글쓰기 @Override public void create(BoardVO vo) throws Exception { String title = vo.getTitle(); String content = vo.getContent(); String writer = vo.getWriter(); // *태그문자 처리 (< ==> < > ==> >) // replace(A, B) A를 B로 변경 title = title.replace("<", "<"); title = title.replace("<", ">"); writer = writer.replace("<", "<"); writer = writer.replace("<", ">"); // *공백문자 처리 title = title.replace(" ", " "); writer = writer.replace(" ", " "); // *줄바꿈 문자처리 content = content.replace("\n", "<br>"); vo.setTitle(title); vo.setContent(content); vo.setWriter(writer); boardDao.create(vo); } // 02. 게시글 상세보기 @Override public BoardVO read(int bno) throws Exception { return boardDao.read(bno); } // 03. 게시글 수정 @Override public void update(BoardVO vo) throws Exception { boardDao.update(vo); } // 04. 게시글 삭제 @Override public void delete(int bno) throws Exception { boardDao.delete(bno); } // 05. 게시글 전체 목록 @Override public List<BoardVO> listAll() throws Exception { return boardDao.listAll(); } // 06. 게시글 조회수 증가 @Override public void increaseViewcnt(int bno, HttpSession session) throws Exception { long update_time = 0; // 세션에 저장된 조회시간 검색 // 최초로 조회할 경우 세션에 저장된 값이 없기 때문에 if문은 실행X if(session.getAttribute("update_time_"+bno) != null){ // 세션에서 읽어오기 update_time = (long)session.getAttribute("update_time_"+bno); } // 시스템의 현재시간을 current_time에 저장 long current_time = System.currentTimeMillis(); // 일정시간이 경과 후 조회수 증가 처리 24*60*60*1000(24시간) // 시스템현재시간 - 열람시간 > 일정시간(조회수 증가가 가능하도록 지정한 시간) if(current_time - update_time > 5*1000){ boardDao.increaseViewcnt(bno); // 세션에 시간을 저장 : "update_time_"+bno는 다른변수와 중복되지 않게 명명한 것 session.setAttribute("update_time_"+bno, current_time); } } } | cs |
03) Model(비지니스 로직, DB연동 작업)
BoardVO(데이터 저장 클래스)
package com.example.spring02.model.board.dto; import java.util.Date; public class BoardVO { private int bno; // 게시글 번호 private String title; // 게시글 제목 private String content; // 게시글 내용 private String writer; // 게시글 작성자 private Date regdate; // 게시글 작성일자 util.Date private int viewcnt; // 게시글 조회수 // Getter/Setter public int getBno() { return bno; } public void setBno(int bno) { this.bno = bno; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } public int getViewcnt() { return viewcnt; } public void setViewcnt(int viewcnt) { this.viewcnt = viewcnt; } // toString() @Override public String toString() { return "BoardVO [bno=" + bno + ", title=" + title + ", content=" + content + ", writer=" + writer + ", regdate=" + regdate + ", viewcnt=" + viewcnt + "]"; } } | cs |
BoardDAO(인터페이스)
package com.example.spring02.model.board.dao; import java.util.List; import com.example.spring02.model.board.dto.BoardVO; public interface BoardDAO { // 01. 게시글 작성 public void create(BoardVO vo) throws Exception; // 02. 게시글 상세보기 public BoardVO read(int bno) throws Exception; // 03. 게시글 수정 public void update(BoardVO vo) throws Exception; // 04. 게시글 삭제 public void delete(int bno) throws Exception; // 05. 게시글 전체 목록 public List<BoardVO> listAll() throws Exception; // 06. 게시글 조회 증가 public void increaseViewcnt(int bno) throws Exception; } | cs |
BoardDAOImpl(인터페이스 구현 클래스)
package com.example.spring02.model.board.dao; import java.util.List; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.example.spring02.model.board.dto.BoardVO; @Repository // 현재 클래스를 dao bean으로 등록 public class BoardDAOImpl implements BoardDAO { @Inject SqlSession SqlSession; // 01. 게시글 작성 @Override public void create(BoardVO vo) throws Exception { SqlSession.insert("board.insert", vo); } // 02. 게시글 상세보기 @Override public BoardVO read(int bno) throws Exception { return SqlSession.selectOne("board.view", bno); } // 03. 게시글 수정 @Override public void update(BoardVO vo) throws Exception { SqlSession.update("board.updateArticle", vo); } // 04. 게시글 삭제 @Override public void delete(int bno) throws Exception { SqlSession.delete("board.deleteArticle",bno); } // 05. 게시글 전체 목록 @Override public List<BoardVO> listAll() throws Exception { return SqlSession.selectList("board.listAll"); } // 게시글 조회수 증가 @Override public void increaseViewcnt(int bno) throws Exception { SqlSession.update("board.increaseViewcnt", bno); } } | cs |
boardMapper.xml(mybatis mapper)
게시글 작성 쿼리 - nvl(A, B) : A가 null 이면 B, null이 아니면 A
게시글 조회수 증가처리 쿼리 - 조회수(초기값=0) = 조회수 + 1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="board"> <!-- 01. 게시글 전체 목록 조회 --> <select id="listAll" resultType="com.example.spring02.model.board.dto.BoardVO"> SELECT bno, title, content, writer, regdate, viewcnt FROM tbl_board ORDER BY bno desc, regdate desc </select> <!-- 02. 게시글 작성 --> <insert id="insert"> INSERT INTO tbl_board ( bno, title, content, writer ) VALUES ( (SELECT NVL(MAX(bno)+1, 1)FROM tbl_board), #{title}, #{content}, #{writer} ) </insert> <!--03. 게시글 상세보기 조회 --> <select id="view" resultType="com.example.spring02.model.board.dto.BoardVO"> SELECT * FROM tbl_board WHERE bno = #{bno} </select> <!-- 04. 게시글 조회수 증가처리 --> <update id="increaseViewcnt"> UPDATE tbl_board SET viewcnt = viewcnt + 1 WHERE bno = #{bno} </update> <!-- 05. 게시글 수정처리 --> <update id="updateArticle"> UPDATE tbl_board SET title = #{title}, content = #{content}, writer = #{writer} WHERE bno = #{bno} </update> <!-- 06. 게시글 삭제처리 --> <delete id="deleteArticle"> DELETE FROM tbl_board WHERE bno = #{bno} </delete> </mapper> | cs |
04) VIew(화면)
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>게시글 목록</title> <%@ include file="../include/header.jsp" %> <script> $(document).ready(function(){ $("#btnWrite").click(function(){ // 페이지 주소 변경(이동) location.href = "${path}/board/write.do"; }); }); </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>게시글 목록</h2> <button type="button" id="btnWrite">글쓰기</button> <table border="1" width="600px"> <tr> <th>번호</th> <th>제목</th> <th>이름</th> <th>작성일</th> <th>조회수</th> </tr> <c:forEach var="row" items="${list}"> <tr> <td>${row.bno}</td> <td><a href="${path}/board/view.do?bno=${row.bno}">${row.title}</a></td> <td>${row.writer}</td> <td> <!-- 원하는 날짜형식으로 출력하기 위해 fmt태그 사용 --> <fmt:formatDate value="${row.regdate}" pattern="yyyy-MM-dd HH:mm:ss"/> </td> <td>${row.viewcnt}</td> </tr> </c:forEach> </table> </body> </html> | cs |
실행화면
view.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>게시글 작성</title> <%@ include file="../include/header.jsp" %> <script> $(document).ready(function(){ $("#btnDelete").click(function(){ if(confirm("삭제하시겠습니까?")){ document.form1.action = "${path}/board/delete.do"; document.form1.submit(); } }); $("#btnUpdete").click(function(){ //var title = document.form1.title.value; ==> name속성으로 처리할 경우 //var content = document.form1.content.value; //var writer = document.form1.writer.value; var title = $("#title").val(); var content = $("#content").val(); var writer = $("#writer").val(); if(title == ""){ alert("제목을 입력하세요"); document.form1.title.focus(); return; } if(content == ""){ alert("내용을 입력하세요"); document.form1.content.focus(); return; } if(writer == ""){ alert("이름을 입력하세요"); document.form1.writer.focus(); return; } document.form1.action="${path}/board/update.do" // 폼에 입력한 데이터를 서버로 전송 document.form1.submit(); }); }); </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>게시글 보기</h2> <form name="form1" method="post"> <div> <!-- 원하는 날짜형식으로 출력하기 위해 fmt태그 사용 --> 작성일자 : <fmt:formatDate value="${dto.regdate}" pattern="yyyy-MM-dd a HH:mm:ss"/> <!-- 날짜 형식 => yyyy 4자리연도, MM 월, dd 일, a 오전/오후, HH 24시간제, hh 12시간제, mm 분, ss 초 --> </div> <div> 조회수 : ${dto.viewcnt} </div> <div> 제목 <input name="title" id="title" size="80" value="${dto.title}" placeholder="제목을 입력해주세요"> </div> <div> 내용 <textarea name="content" id="content" rows="4" cols="80" placeholder="내용을 입력해주세요">${dto.content}</textarea> </div> <div> 이름 <input name="writer" id="writer" value="${dto.writer}" placeholder="이름을 입력해주세요"> </div> <div style="width:650px; text-align: center;"> <!-- 게시물번호를 hidden으로 처리 --> <input type="hidden" name="bno" value="${dto.bno}"> <button type="button" id="btnUpdete">수정</button> <button type="button" id="btnDelete">삭제</button> </div> </form> </body> </html> | cs |
실행화면
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>게시글 작성</title> <%@ include file="../include/header.jsp" %> <script> $(document).ready(function(){ $("#btnSave").click(function(){ //var title = document.form1.title.value; ==> name속성으로 처리할 경우 //var content = document.form1.content.value; //var writer = document.form1.writer.value; var title = $("#title").val(); var content = $("#content").val(); var writer = $("#writer").val(); if(title == ""){ alert("제목을 입력하세요"); document.form1.title.focus(); return; } if(content == ""){ alert("내용을 입력하세요"); document.form1.content.focus(); return; } if(writer == ""){ alert("이름을 입력하세요"); document.form1.writer.focus(); return; } // 폼에 입력한 데이터를 서버로 전송 document.form1.submit(); }); }); </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>게시글 작성</h2> <form name="form1" method="post" action="${path}/board/insert.do"> <div> 제목 <input name="title" id="title" size="80" placeholder="제목을 입력해주세요"> </div> <div> 내용 <textarea name="content" id="content" rows="4" cols="80" placeholder="내용을 입력해주세요"></textarea> </div> <div> 이름 <input name="writer" id="writer" placeholder="이름을 입력해주세요"> </div> <div style="width:650px; text-align: center;"> <button type="button" id="btnSave">확인</button> <button type="reset">취소</button> </div> </form> </body> </html> | cs |
실행화면