목차 | |
1. | 설정 |
2. | 기초 |
1. 설정
spring tool site =>
sts 3 (spring에 최적화)
sts 4 (spring tool에 최적화)
- sts 3 다운로드
** sts4는 springboot에 최적화 되어있음
우리는 spring을 다룰 것이므로 sts3를 다운받아줌
처음 spring 페이지 들어가면 sts4 다운이 안내되어있는데 아래로 쭉 내리면 sts3를 받는 링크가 있음
D드라이브에 spring_workspace 폴더 생성 및 sts 설치
- Spring Legacy Project 만들기
여기서 템플릿으로 MVC project를 생성해야하는데, 존재하지 않음
sts3에서 MVC project 생성을 막아둔 것인데,
수업을 위해서 없어진 파일을 다시 넣어 MVC project를 생성해볼 것임
1. D:\aws_chaminjoo\spring_workspace\.metadata
\.plugins\org.springsource.ide.eclipse.commons.content.core
폴더에 http-content.xml 파일 직접 넣어주기
파일 넣고 다시 열어보면 MVC project가 추가되어있음
다시 실행하면
2. D:\aws_chaminjoo\spring_workspace\.metadata
\.sts\content\org.springframework.templates.mvc-3.2.2
폴더에 빈 파일을 직접 추가해줌
1,2번 둘 다 넣어주면 이제 패키지 생성 가능함
- 초기 설정 해주기
이제 프로젝트를 만들어줬으니 세부 설정을 해줘야한다.
- 이클립스 설정
1. encoding 설정 : 평소 해줬던 것과 같이 utf-8로 설정해 한글 깨짐을 방지한다. 추가로 workspace랑 css html외에 전부 다 utf-8로 바꿔줘야한다! 옛날 버전이라 utf-8로 자동 설정 안되있음!
2. 자바 JDK 버전 확인 : JDK 1.6으로 되어있는걸 11 버전으로 바꿔주었다. 컴파일러 당연히 같이 바꿔주기!
3. Server 설정 : 기본으로 주는 서버 없애고, Tomcat으로 설정해준다!
4. web 설정 : 외부 파일로 연결되도록 extenal로 바꾸고 기본 브라우저를 chrome으로 설정한다.
5. 그 외 : console 버퍼 사이즈, 폰트 크기 설정 등등
- Properties 설정
mvnrepository에서 코드를 복사해서 pom.xml에 붙여놓으면 따로 파일을 다운로드 안 해도 됨
lombok은 파일 경로에 한글이 있으면 안 됨!
2. 기초
▣ sqlFile
create table board(
bno int auto_increment,
title varchar(200) not null,
writer varchar(200) not null,
content text,
isDel varchar(10) default 'N',
regdate datetime default now(),
modDate datetime default now(),
primary key(bno));
▣ 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">
<!-- 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>
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
▣ 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">
<!-- 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>
<context:component-scan base-package="com.ezen.spring.controller" />
<context:component-scan base-package="com.ezen.spring.service" />
<context:component-scan base-package="com.ezen.spring.handler" />
<context:component-scan base-package="com.ezen.spring.dao" />
</beans:beans>
▣ 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans https://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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- DB 설정 driverClassName, url, username, password -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://Localhost:3306/springdb"></property>
<property name="username" value="springUser"></property>
<property name="password" value="mysql"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
</bean>
<!-- dao interface 위치(패캐지) -->
<!-- daoImpl() mapper와 연결시 namespace.id -->
<!-- mapper namespace="dao interface명" id="메서드명" -->
<mybatis-spring:scan base-package="com.ezen.spring.dao"/>
</beans>
▣ index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" contentType="text/html; charset+UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
<a href="/board/register"><p> board register page... </p></a>
<a href="/board/list"><p> board List page... <p></a>
</body>
</html>
▣ BoardVO.java
package com.ezen.spring.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class BoardVO {
private int bno;
private String title;
private String writer;
private String content;
private String isDel;
private String regdate;
private String modDate;
}
▣ BoardController.java
package com.ezen.spring.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.service.BoardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RequestMapping("/board/*")
@Slf4j
@RequiredArgsConstructor
@Controller
public class BoardController {
private final BoardService bsv;
// return의 위치와 컨트롤러의 경로가 같으면 void 생략가능
@GetMapping("/register")
public String register() {
// return은 이동하는 jsp 위치 == destPage
// /WEB-INF/views/register.jsp
return "/board/register";
}
// 같은 의미
// @GetMapping("/register")
// public void register() {}
@PostMapping("/insert")
public String insert(BoardVO bvo) {
log.info(">>>> insert boardVO > {}", bvo);
int isOk = bsv.register(bvo);
log.info(">>> register >{} ", isOk > 0 ? "OK":"FAIL");
// 내부 컨트롤러를 다시 접근할 경우 redirect:/경로
return "redirect:/";
}
@GetMapping("/list")
public String list(Model m) {
// request.setAttribute 역할을 하는 객체 => Model 객체
List<BoardVO> list = bsv.getList();
m.addAttribute("list", list);
return "/board/list";
}
// 두개의 경로를 하나의 메서드에서 처리
// /board/detail, /board/modify
@GetMapping({"/detail", "/modify"})
public void detail(Model m, @RequestParam("bno") int bno) {
log.info(">>> param bno > {}", bno);
BoardVO bvo = bsv.getDetail(bno);
m.addAttribute("bvo", bvo);
// return "/board/detail";
}
}
▣ BoardService.java
package com.ezen.spring.service;
import java.util.List;
import com.ezen.spring.domain.BoardVO;
public interface BoardService {
int register(BoardVO bvo);
List<BoardVO> getList();
BoardVO getDetail(int bno);
}
▣ BoardServiceImpl.java
package com.ezen.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.domain.BoardVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@Slf4j
@Service
public class BoardServiceImpl implements BoardService{
private final BoardDAO bdao;
@Override
public int register(BoardVO bvo) {
// TODO Auto-generated method stub
return bdao.register(bvo);
}
@Override
public List<BoardVO> getList() {
// TODO Auto-generated method stub
return bdao.getList();
}
@Override
public BoardVO getDetail(int bno) {
// TODO Auto-generated method stub
return bdao.getDetail(bno);
}
}
▣ BoardDAO.java
package com.ezen.spring.dao;
import java.util.List;
import com.ezen.spring.domain.BoardVO;
public interface BoardDAO {
int register(BoardVO bvo);
List<BoardVO> getList();
BoardVO getDetail(int bno);
}
▣ boardMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ezen.spring.dao.BoardDAO">
<!-- id = BoardDAO 메서드명으로 설정 -->
<insert id="register" parameterType="com.ezen.spring.domain.BoardVO">
insert into board(title, writer, content)
values(#{title}, #{writer}, #{content})
</insert>
<select id="getList" resultType="com.ezen.spring.domain.BoardVO">
select * from board where isDel = 'N' order by bno desc
</select>
<select id="getDetail" resultType="com.ezen.spring.domain.BoardVO">
select * from board where bno = #{bno}
</select>
<update id="update">
update set title=#{title}, content=#{content}, modDate = now() where bno = #{bno}
</update>
<delete id="delete">
update set isDel = 'Y' where bno = #{bno}
</delete>
</mapper>
▣ register.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>
<h1>Board Register Page</h1>
<hr>
<form action="/board/insert" method="post">
title : <input type="text" name="title" placeholder="title..."> <br>
writer : <input type="text" name="writer" placeholder="wrtier..."> <br>
content : <br>
<textarea rows="10" cols="50" name="content" placeholder="content..."></textarea>
<button type="submit">register</button>
</form>
</body>
</html>
▣ list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Board List Page</h1>
<hr>
<table>
<tr>
<th>bno</th>
<th>title</th>
<th>writer</th>
<th>regdate</th>
<th>modDate</th>
</tr>
<c:forEach items="${list}" var="bvo">
<tr>
<td>${bvo.bno }</td>
<td><a href="/board/detail?bno=${bvo.bno }">${bvo.title }</a></td>
<td>${bvo.writer }</td>
<td>${bvo.regdate }</td>
<td>${bvo.modDate }</td>
</tr>
</c:forEach>
</table>
<a href="/"><button type="button">index</button></a>
</body>
</html>
▣ detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Board detail Page</h1>
<hr>
<table>
<tr>
<th>bno</th>
<td>${bvo.bno }</td>
</tr>
<tr>
<th>title</th>
<td>${bvo.title }</td>
</tr>
<tr>
<th>writer</th>
<td>${bvo.writer }</td>
</tr>
<tr>
<th>regdate</th>
<td>${bvo.regdate }</td>
</tr>
<tr>
<th>modDate</th>
<td>${bvo.modDate }</td>
</tr>
<tr>
<th>content</th>
<td>${bvo.content }</td>
</tr>
</table>
<a href="/board/modify?bno=${bvo.bno }"><button type="button">수정</button></a>
</body>
</html>
▷ 출력
'Java > Spring' 카테고리의 다른 글
Spring 기초(scheduler) - AWS 풀스택 과정 70일차 (0) | 2024.11.04 |
---|---|
Spring 기초(file) - AWS 풀스택 과정 69일차 (0) | 2024.11.01 |
Spring 기초(comment) - AWS 풀스택 과정 68일차 (0) | 2024.10.31 |
Spring 기초(paging, search) - AWS 풀스택 과정 67일차 (0) | 2024.10.30 |
Spring 설정 및 기초2 - AWS 풀스택 과정 66일차 (0) | 2024.10.29 |