▶<sql>
create table board
(
idx int not null auto_increment,
title varchar(100) not null,
writer varchar(100) not null,
content varchar(2000) not null,
indate datetime default now(),
count int default 0,
primary key(idx)
);
insert into board(title, writer, content)
values('스프링 게시판','최지연', '스프링 게시판 만들기');
insert into board(title, writer, content)
values('스프링 게시판','관리자', '스프링 게시판 만들기');
select * from board;
▶<Board.java>
package com.smhrd.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data // Getter/Setter/toString
@NoArgsConstructor
public class Board {
// 1. Class 필드명 == Table 컬럼
// 2. 기본생성자
// 글번호
private int idx;
// 제목
private String title;
// 작성자
private String writer;
// 내용
private String content;
// 작성일
private String indate;
// 조회수
private int count;
}
▶<boardList.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 lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>SpringMVC01</h2>
<div class="panel panel-default">
<div class="panel-heading">게시판 만들기</div>
<div class="panel-body">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td>글번호</td>
<td>제목</td>
<td>작성자</td>
<td>작성일</td>
<td>조회수</td>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="vo">
<tr>
<td>${vo.idx}</td>
<td>${vo.title}</td>
<td>${vo.writer}</td>
<td>${vo.indate}</td>
<td>${vo.count}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button onclick="window.location.href='boardForm.do'" class="btn btn-sm btn-success">글작성</button>
</div>
<div class="panel-footer">지능형 IoT 8차 최지연</div>
</div>
</div>
</body>
</html>
▶<boardForm.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 lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>SpringMVC01</h2>
<div class="panel panel-default">
<div class="panel-heading">게시판 만들기</div>
<div class="panel-body">
<form class="form-horizontal" action="boardInsert.do" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="title">title:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="title"
placeholder="Enter title" name="title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="writer">writer:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="writer"
placeholder="Enter writer" name="writer">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="content">content:</label>
<div class="col-sm-10">
<textarea rows="10" id="content" class="form-control" name="content"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">지능형 IoT 8차 최지연</div>
</div>
</div>
</body>
</html>
▶<BoardMapper.java>
package com.smhrd.mapper;
import java.util.List;
import com.smhrd.domain.Board;
// DAO를 interface로 만든다
public interface BoardMapper {
// ********** 연결된 xml파일이랑 이름이 같아야함
// DB 연결은 다른 파일에서 진행
// 추상메서드
// Spring에서 쓸때는 추상메서드만 만들고, mapper.xml이랑 맵핑
// 메서드 이름 <--> xml의 id mapping
public List<Board> boardList();
// resultType ==> 리턴타입
// parameterType ==> 매개변수
public int boardInsert(Board vo);
}
▶ <BoardMapper.xml>
<?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="com.smhrd.mapper.BoardMapper">
<select id="boardList" resultType="com.smhrd.domain.Board">
select * from board
</select>
<insert id="boardInsert" parameterType="com.smhrd.domain.Board">
insert into board(title, writer, content)
values(#{title}, #{writer}, #{content})
</insert>
</mapper>
▶< web.xml >
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
▶< 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.3.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- mybatis-config.xml 역할을 하는 객체 ( DB 연결 정보 저장 ) -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mysql"></property>
<property name="username" value="root"></property>
<property name="password" value="12345"></property>
</bean>
<!-- DBCP 생성 -->
<!--HikariCP Configration-->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig"/>
</bean>
<!-- DBCP + Mapper interface -> DAO구현 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--
*********
interface, xml을 찾음
-->
<mybatis-spring:scan base-package="com.smhrd.mapper"/>
</beans>
▶< 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 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.smhrd</groupId>
<artifactId>web</artifactId>
<name>SpringMVC01</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.3.14.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<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>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<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</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<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>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<!-- 롬복 라이브러리 설치 -->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- MysqlDB <-> 프로젝트 연결 시켜줄 코드-->
<!--https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- jdbc driver <-> spring 연결 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- MyBatis사용 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- MyBatis를 더 편하게 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- DBCP관리를 해줄 라이브러리 -->
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</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.8</source>
<target>1.8</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>
▶< index.jsp >
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%--
/ 경로로 요청 하면 index.jsp가 열림
이름을 index.jsp로 할것
webapp 폴더에 만들 것
--%>
<jsp:forward page="boardList.do"></jsp:forward>
</body>
</html>
▶< BoardController.java >
package com.smhrd.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.smhrd.domain.Board;
import com.smhrd.mapper.BoardMapper;
// 어노테이션
// POJO임을 명시
@Controller
public class BoardController {
// IOC : Inversion of Controll (제어 역전 )
// 우리가 xml에 적어두면, Spring이 알아서 객체 생성, 사용을 한다.
// DI : Dependency Injection(의존성 주입)
@Autowired // self service
BoardMapper mapper;
// 메서드 <--> 주소 연결(Mapping)
// /boardList요청이 들어오면 이 메서드 실행
@RequestMapping("/boardList.do")
public String boardList(HttpServletRequest request) {
// Request나, Session같이 필요한 게 있으면, 매개변수
// 게시물 가져오기
List<Board> list = mapper.boardList();
// 객체바인딩
request.setAttribute("list", list);
// jsp(view) 파일의 이름
// forward방식 이동
// /WEB-INF/views/boardList.jsp
return "boardList";
}
// boardForm으로 이동할 메서드
@RequestMapping("/boardForm.do")
public void boardForm() {}
// 리턴X --> 페이지 이동
// 만약 리턴이 없다면, 메서드명과 같은 이름을 가진 view(jsp) 이동
// 게시글 작성 메서드
@RequestMapping("/boardInsert.do")
public String boardInsert(Board vo) {
// 1. input태그의 name == VO의 필드명 == Table의 컬럼명
// 2. 기본생성자
// 매개변수를 통해서 파라미터 수집 가능
// 만약 한개만 보내주는 경우라면?
// input태그의 name == 매개변수 변수명
// 자동으로 파라미터 수집하는 경우 --> 만약 null값을 받으면 기본값으로 대체 ex) content : null --> vo.setContent("");
// 파라미터 수집
// form태그로 보낸 데이터 받기(변수에 담기)
/*
* String title = request.getParameter("title"); String writer =
* request.getParameter("writer"); String content =
* request.getParameter("content");
*
* Board vo = new Board();
* vo.setTitle(title);
* vo.setWriter(writer);
* vo.setContent(content);
*/
// 게시글 저장
mapper.boardInsert(vo);
// WEB-INF/views/boardList.do.jsp
// Redirect
// 컨트롤러(POJO 메서드)로 다시 요청하는 경우 사용
// urlMapping앞에 redirect:/를 붙이면 동작한다.
return "redirect:/boardList.do";
}
}
'자바스프링' 카테고리의 다른 글
게시판 수정 (0) | 2022.06.28 |
---|---|
게시판 글 삭제 (0) | 2022.06.27 |
게시판 글 출력 (0) | 2022.06.24 |
스프링 서버과정 (0) | 2022.06.24 |
자바스프링 기본 (0) | 2022.06.23 |