00. Spring Legacy Project 생성
Spring Legacy Project를 만들어주세요!
01. pom.xml : ojdbc6, mybatis, mabatis-spring, commons-dbcp, spring-orm
<!-- 추가 -->
<!-- https://mvnrepository.com/artifact/oracle/ojdbc6 -->
<dependency>
<groupId>oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<!-- Object - Relational - Mapping -->
<!-- version에 위에있는 properties태그 안에 version 복사해서 붙여넣기 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
02. web.xml : applicationContext.xml, mapping(*.do), encodingFilter
root-context.xml파일은 원래 src/main/webapp/WEB-INF/spring의 경로에 위치해있습니다.
하지만 xml파일은 한곳으로 몰아서 좀더 보기 편하게 하기위해 경로를 바꿔주었으며 이름을 applicationContext.xml로 수정하였습니다.
이부분은 개인의 취향차이이니 경로나 이름은 템플릿 설정 그대로 놔두셔도 괜찮습니다.
저는 변경할 예정인데요.
따라서 web.xml안에서도 경로르 바꿔야합니다.
<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>
web.xml
또한 아래쪽으로 가서 url-pattern을 /가 아닌 *.do로 바꾸겠습니다
*.do의 형태가 편해서 저는 이렇게 사용하겠습니다!
그리고 한글이 깨지지 않게 하기 위해 filter를 만들어주세요!
<!-- Processes application requests -->
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 서버 밖에서 존재. 요청되는거, 응답되는거 받는 역할 -->
<filter>
<filter-name>encodingFilter</filter-name>
<!-- 패키지 : org.spirngframework.web.filter -->
<!-- 클래스 : CharacterEncoding -->
<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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
web.xml
03. /WEB-INF/spring/sqls/test.sql
spring폴더 아래에 sqls라는 폴더를 만들어주시고 해당 폴더에서 test.sql 파일을 만들겠습니다.
test.sql에서는 사용할 sql문을 작성해주세요!
DROP SEQUENCE MYNOSEQ;
DROP TABLE MYNOBOARD;
CREATE SEQUENCE MYNOSEQ;
CREATE TABLE MYNOBOARD(
MYNO NUMBER PRIMARY KEY,
MYNAME VARCHAR2(1000) NOT NULL,
MYTITLE VARCHAR2(2000) NOT NULL,
MYCONTENT VARCHAR2(4000) NOT NULL,
MYDATE DATE NOT NULL
);
INSERT INTO MYNOBOARD
VALUES(MYNOSEQ.NEXTVAL, '관리자', '스프링 재밌다.', '정말 재밌다.', SYSDATE);
SELECT MYNO, MYNAME, MYTITLE, MYCONTENT, MYDATE
FROM MYNOBOARD
ORDER BY MYNO DESC;
04. dto, dao, biz, controller
MYBoardDto.java
package com.mvc.upgrade.model.dto;
import java.util.Date;
public class MYBoardDto {
private int myno;
private String myname;
private String mytitle;
private String mycontent;
private Date mydate;
public MYBoardDto() {
}
public MYBoardDto(int myno, String myname, String mytitle, String mycontent, Date mydate) {
this.myno = myno;
this.myname = myname;
this.mytitle = mytitle;
this.mycontent = mycontent;
this.mydate = mydate;
}
public int getMyno() {
return myno;
}
public void setMyno(int myno) {
this.myno = myno;
}
public String getMyname() {
return myname;
}
public void setMyname(String myname) {
this.myname = myname;
}
public String getMytitle() {
return mytitle;
}
public void setMytitle(String mytitle) {
this.mytitle = mytitle;
}
public String getMycontent() {
return mycontent;
}
public void setMycontent(String mycontent) {
this.mycontent = mycontent;
}
public Date getMydate() {
return mydate;
}
public void setMydate(Date mydate) {
this.mydate = mydate;
}
}
MYBoardController.java(@Controller)
package com.mvc.upgrade.model.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.mvc.upgrade.model.biz.MYBoardBiz;
import com.mvc.upgrade.model.dto.MYBoardDto;
@Controller
public class MYBoardController {
@Autowired
private MYBoardBiz biz;
@RequestMapping("/list.do")
public String selectList(Model model) {
model.addAttribute("list", biz.selectList());
return "myboardlist";
}
@RequestMapping("/detail.do")
public String selectOne(Model model, int myno) {
model.addAttribute("dto", biz.selectOne(myno));
return "myboarddetail";
}
@RequestMapping("/writeform.do")
public String insertForm() {
return "myboardinsert";
}
@RequestMapping(value="/writeres.do", method=RequestMethod.POST)
public String insertRes(MYBoardDto dto) {
if(biz.insert(dto) > 0) {
return "redirect:list.do";
}
return "redirect:writeform.do";
}
@RequestMapping("/updateform.do")
public String updateForm(Model model, int myno) {
model.addAttribute("dto", biz.selectOne(myno));
return "myboardupdate";
}
@RequestMapping("/updateres.do")
public String updateRes(MYBoardDto dto) {
if(biz.update(dto) > 0) {
return "redirect:detail.do?myno="+dto.getMyno();
}
return "redirect:updateform.do?myno="+dto.getMyno();
}
@RequestMapping("/delete.do")
public String delete(int myno) {
if(biz.delete(myno) > 0){
return "redirect:list.do";
}
return "redirect:detail.do?myno="+myno;
}
}
MYBoardBiz.java(interface)
package com.mvc.upgrade.model.biz;
import java.util.List;
import com.mvc.upgrade.model.dto.MYBoardDto;
public interface MYBoardBiz {
public List<MYBoardDto> selectList();
public MYBoardDto selectOne(int myno);
public int insert(MYBoardDto dto);
public int update(MYBoardDto dto);
public int delete(int myno);
}
MYBoardBizImpl.java(implements MYBoardBiz, @Service)
package com.mvc.upgrade.model.biz;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mvc.upgrade.model.dao.MYBoardDao;
import com.mvc.upgrade.model.dto.MYBoardDto;
@Service
public class MYBoardBizImpl implements MYBoardBiz {
@Autowired
private MYBoardDao dao;
@Override
public List<MYBoardDto> selectList() {
return dao.selectList();
}
@Override
public MYBoardDto selectOne(int myno) {
return dao.selectOne(myno);
}
@Override
public int insert(MYBoardDto dto) {
return dao.insert(dto);
}
@Override
public int update(MYBoardDto dto) {
return dao.update(dto);
}
@Override
public int delete(int myno) {
return dao.delete(myno);
}
}
MYBoardDao.java(interface)
package com.mvc.upgrade.model.dao;
import java.util.List;
import com.mvc.upgrade.model.dto.MYBoardDto;
public interface MYBoardDao {
String NAMESPACE = "myboard.";
public List<MYBoardDto> selectList();
public MYBoardDto selectOne(int myno);
public int insert(MYBoardDto dto);
public int update(MYBoardDto dto);
public int delete(int myno);
}
MYBoardDaoImpl.java(implements MYBoardDao, @Repository)
package com.mvc.upgrade.model.dao;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mvc.upgrade.model.dto.MYBoardDto;
@Repository
public class MYBoardDaoImpl implements MYBoardDao {
@Autowired
private SqlSessionTemplate sqlSession;
@Override
public List<MYBoardDto> selectList() {
List<MYBoardDto> list = new ArrayList<MYBoardDto>();
try {
list = sqlSession.selectList(NAMESPACE+"selectList");
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@Override
public MYBoardDto selectOne(int myno) {
MYBoardDto dto = null;
try {
dto = sqlSession.selectOne(NAMESPACE+"selectOne", myno);
} catch (Exception e) {
e.printStackTrace();
}
return dto;
}
@Override
public int insert(MYBoardDto dto) {
int res = 0;
try {
res = sqlSession.insert(NAMESPACE + "insert", dto);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
@Override
public int update(MYBoardDto dto) {
int res = 0;
try {
res = sqlSession.update(NAMESPACE + "update", dto);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
@Override
public int delete(int myno) {
int res = 0;
try {
res = sqlSession.delete(NAMESPACE + "delete", myno);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
05. src/main/resources/mybatis/myboard-mapper.xml
src/test/resources에 mybatis폴더를 만들어주시고 myboard-mapper.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="myboard">
<resultMap type="myBoardDto" id="myBoardMap">
<result property="myno" column="MYNO" />
<result property="myname" column="MYNAME" />
<result property="mytitle" column="MYTITLE" />
<result property="mycontent" column="MYCONTENT" />
<result property="mydate" column="MYDATE" />
</resultMap>
<select id="selectList" resultType="myBoardDto">
SELECT MYNO, MYNAME, MYTITLE, MYCONTENT, MYDATE
FROM MYNOBOARD
ORDER BY MYNO DESC
</select>
<select id="selectOne" resultMap="myBoardMap">
SELECT MYNO, MYNAME, MYTITLE, MYCONTENT, MYDATE
FROM MYNOBOARD
WHERE MYNO = #{myno}
</select>
<insert id="insert" parameterType="myBoardDto">
INSERT INTO MYNOBOARD
VALUES(MYNOSEQ.NEXTVAL, #{myname}, #{mytitle}, #{mycontent}, SYSDATE)
</insert>
<update id="update" parameterType="myBoardDto">
UPDATE MYNOBOARD
SET MYTITLE = #{mytitle}, MYCONTENT = #{mycontent}
WHERE MYNO = #{myno}
</update>
<delete id="delete" parameterType="int">
DELETE FROM MYNOBOARD
WHERE MYNO = #{myno}
</delete>
</mapper>
06. src/main/resources/mybatis/db.properties
다음으로는 db.properties를 만들어주세요.
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=kh
password=kh
07. /WEB-INF/spring/sqls/config.xml
아까 만들었던 sqls폴더에 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>
<typeAlias type="com.mvc.upgrade.model.dto.MYBoardDto" alias="myBoardDto"/>
</typeAliases>
<!-- resource : src/main/resources 와 같음 -->
<mappers>
<mapper resource="/mybatis/myboard-mapper.xml"/>
</mappers>
</configuration>
08. applicationContext.xml, servlet-context.xml
applicationContext파일에 설정을 마무리 해줍니다!
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- db.properties -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mybatis/db.properties</value>
</list>
</property>
</bean>
<!-- dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- mybatis -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="WEB-INF/spring/sqls/config.xml" />
<!-- 만약 config를 mybatis 폴더안에 넣어놓았다면? classpath:mybatis/config.xml 이라고 경로 쓰면된다. -->
</bean>
<!-- mybatis-template -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSession" />
</bean>
</beans>
<!--
원래는 spring폴더 아래 root-context라는 이름으로 있었지만 xml폴더를 한곳으로 몰기 위해 appServlet으로 이동시킴
이름을 root-context에서 application-context로 이름 바꿈 -> web.xml에서도 이름 바꿔야함
-->
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.mvc.upgrade" />
</beans:beans>
이제 views에 jsp파일을 모두 작성해주시면 잘 작동이 될겁니다!
제 깃허브를 참고해주세요
실행시켜보면 CRUD기능 모두 작동합니다!
(저는 뒤에 작업도 해놓아서...)
'Java 관련 > Spring Legecy' 카테고리의 다른 글
[Spring] 스프링MVC - AOP (0) | 2022.04.04 |
---|---|
[Spring] filter(javax.servlet.Filter) (0) | 2022.04.03 |
[Spring] request, response (0) | 2022.04.01 |
[Spring] encodingFilter로 한글 설정하기 (0) | 2022.03.31 |
[Spring] Spring Legacy Project (0) | 2022.03.30 |