목차
Framework 만들기
jdk 버전 올리기
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
dependencies 올리기
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
log4j 파일 만들기
# log4j.properties
log4j.rootLogger=WARN, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%C $c %M - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.home.controller=WARN
log4j.logger.com.emp=DEBUG
Dto/Dao 만들기
package com.gimhae.framework.model;
import java.time.LocalDate;
public class EmpDto {
private int empno,pay;
private String ename;
private LocalDate hiredate;
public EmpDto() {
// TODO Auto-generated constructor stub
}
public EmpDto(int empno, int pay, String ename, LocalDate hiredate) {
super();
this.empno = empno;
this.pay = pay;
this.ename = ename;
this.hiredate = hiredate;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public int getPay() {
return pay;
}
public void setPay(int pay) {
this.pay = pay;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public LocalDate getHiredate() {
return hiredate;
}
public void setHiredate(LocalDate hiredate) {
this.hiredate = hiredate;
}
@Override
public String toString() {
return "EmpDto [empno=" + empno + ", pay=" + pay + ", ename=" + ename + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + empno;
result = prime * result + ((ename == null) ? 0 : ename.hashCode());
result = prime * result + pay;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmpDto other = (EmpDto) obj;
if (empno != other.empno)
return false;
if (ename == null) {
if (other.ename != null)
return false;
} else if (!ename.equals(other.ename))
return false;
if (pay != other.pay)
return false;
return true;
}
}
package com.gimhae.framework.model;
import javax.sql.DataSource;
import com.mysql.cj.jdbc.MysqlDataSource;
public class EmpDao {
Logger log=Logger.getLogger(this.getClass());
DataSource dataSource;
public EmpDao() {
MysqlDataSource dataSource=new MysqlDataSource();
dataSource.setURL("jdbc:mysql://localhost:3306/xe");
dataSource.setUser("scott");
dataSource.setPassword("tiger");
this.dataSource=dataSource;
}
}
JUnit 테스트 확인하기
[RMB]>[new]>[other]>[JUnit Test Case]
접속이 성공하는지 확인하기
@Test
public void test() throws SQLException {
EmpDao dao=new EmpDao();
dao.dataSource.getConnection().close();
}
PullList
Dao
public List<EmpDto> pullList() throws SQLException{
String sql="select * from emp38 order by empno";
List<EmpDto> list=new ArrayList();
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
){
while(rs.next()) {
list.add(new EmpDto(
rs.getInt("empno"),rs.getInt("pay"),rs.getString("ename"),
LocalDate.from(rs.getDate("hiredate").toLocalDate())
));
}
}
log.debug(list);
return list;
}
Test
@Test
public void test1PullList() throws SQLException {
EmpDao dao=new EmpDao();
Object obj=dao.pullList();
assertNotNull(obj);
assertTrue(((List)obj).size()>0);
}
GetList
Dao
public EmpDto getList(int pk) throws SQLException {
String sql="select * from emp38 where empno=?";
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
pstmt.setInt(1, pk);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
EmpDto bean= new EmpDto(
rs.getInt("empno"),rs.getInt("pay"),rs.getString("ename"),
LocalDate.from(rs.getDate("hiredate").toLocalDate())
);
log.debug(bean.toString());
return bean;
}
}
return null;
}
Test
@Test
public void test2GetlList() throws SQLException {
EmpDto target=new EmpDto(4, 4444, "tester4",null);
EmpDao dao=new EmpDao();
Object result=dao.getList(target.getEmpno());
assertEquals(target, result);
}
addList
Dao
public int addList(EmpDto bean) throws SQLException {
String sql="insert into emp38 (ename,hiredate,pay) values (?,now(),?)";
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
pstmt.setString(1, bean.getEname());
pstmt.setInt(2, bean.getPay());
return pstmt.executeUpdate();
}
}
Test
@Test
public void test3AddlList() throws SQLException {
EmpDto target=new EmpDto(0, 1717, "tester17",null);
EmpDao dao=new EmpDao();
assertSame(1, dao.addList(target));
}
-rollback 하기
Dao
boolean test;
public EmpDao(boolean test) {
this();
this.test=test;
}
public int addList(EmpDto bean) throws SQLException {
String sql="insert into emp38 (ename,hiredate,pay) values (?,now(),?)";
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
if(test)conn.setAutoCommit(false);
pstmt.setString(1, bean.getEname());
pstmt.setInt(2, bean.getPay());
int result=pstmt.executeUpdate();
if(test)conn.rollback();
if(test)conn.setAutoCommit(true);
return result;
}
}
Test
@Test
public void test3AddlList() throws SQLException {
EmpDto target=new EmpDto(18, 1818, "tester18",null);
EmpDao dao=new EmpDao(true);
assertSame(1, dao.addList(target));
}
removeList
Dao
public int rmList(int pk) throws SQLException {
String sql="delete from emp38 where empno=?";
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
if(test)conn.setAutoCommit(false);
pstmt.setInt(1, pk);
int result=pstmt.executeUpdate();
if(test)conn.rollback();
if(test)conn.setAutoCommit(true);
return result;
}
}
Test
@Test
public void test4RmlList() throws SQLException {
EmpDto target=new EmpDto(4, 4444, "tester4",null);
EmpDao dao=new EmpDao(true);
assertSame(1, dao.rmList(target.getEmpno()));
}
editList
Dao
public int editList(EmpDto bean) throws SQLException {
String sql="update emp38 set ename=?,pay=? where empno=?";
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
if(test)conn.setAutoCommit(false);
pstmt.setString(1, bean.getEname());
pstmt.setInt(2, bean.getPay());
pstmt.setInt(3, bean.getEmpno());
int result=pstmt.executeUpdate();
if(test)conn.rollback();
if(test)conn.setAutoCommit(true);
return result;
}
}
Test
@Test
public void test5EditlList() throws SQLException {
EmpDto target=new EmpDto(4, 4444, "tester4",null);
target.setEname("test");
target.setPay(4000);
EmpDao dao=new EmpDao(true);
assertSame(1, dao.editList(target));
}
Test 이름순으로 수행하기
@OrderWith(Alphanumeric.class)
public class EmpDaoTest {
...
}
Test Before/After 메소드 사용하기
@OrderWith(Alphanumeric.class)
public class EmpDaoTest {
EmpDto target;
static EmpDao dao;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dao=new EmpDao(true);
}
@Before
public void setUp() throws Exception {
EmpDto target=new EmpDto(4, 4444, "tester4",null);
}
@Test
public void test() throws SQLException {
dao.dataSource.getConnection().close();
}
@Test
public void test1PullList() throws SQLException {
Object obj=dao.pullList();
assertNotNull(obj);
assertTrue(((List)obj).size()>0);
}
@Test
public void test2GetlList() throws SQLException {
Object result=dao.getList(target.getEmpno());
assertEquals(target, result);
}
@Test
public void test3AddlList() throws SQLException {
EmpDto target=new EmpDto(18, 1818, "tester18",null);
assertSame(1, dao.addList(target));
}
@Test
public void test4RmlList() throws SQLException {
assertSame(1, dao.rmList(target.getEmpno()));
}
@Test
public void test5EditlList() throws SQLException {
target.setEname("test");
target.setPay(4000);
assertSame(1, dao.editList(target));
}
}
-> 전체 Test를 수행하기 전 한번만 SetUp을 시킨다.
-> 매 test를 수행하기 전 target을 세팅시킨다.
Template 만들기
jdbcTemplate
package com.gimhae.framework.jdbc;
public class JdbcTemplate<T> {
Logger log=Logger.getLogger(this.getClass());
DataSource dataSource;
boolean test;
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
super();
this.dataSource = dataSource;
}
public void setTest(boolean test) {
this.test = test;
}
public int update(String sql,Object ... args) throws SQLException {
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
if(test)conn.setAutoCommit(false);
for(int i=0;i<args.length;i++) {
pstmt.setObject(i+1, args[i]);
}
int result=pstmt.executeUpdate();
if(test)conn.rollback();
if(test)conn.setAutoCommit(true);
return result;
}
}
public T queryForObject(String sql,RowMapper<T> rowMapper,Object ... args) throws SQLException {
return query(sql,rowMapper,args).get(0);
}
public List<T> query(String sql,RowMapper<T> rowMapper,Object ... args) throws SQLException {
List<T> list=new ArrayList<>();
try(
Connection conn=dataSource.getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
){
for(int i=0;i<args.length;i++) {
pstmt.setObject(i+1, args[i]);
}
ResultSet rs=pstmt.executeQuery();
while(rs.next()) {
list.add(rowMapper.mapper(rs));
}
log.debug(list.toString());
return list;
}
}
}
Dao
package com.gimhae.framework.model;
@OrderWith(Alphanumeric.class)
public class EmpDaoTest {
EmpDto target;
static EmpDao dao;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dao=new EmpDao(true);
}
@Before
public void setUp() throws Exception {
target=new EmpDto(4, 4444, "tester4",null);
}
@Test
public void test1PullList() throws SQLException {
Object obj=dao.pullList();
assertNotNull(obj);
assertTrue(((List)obj).size()>0);
}
@Test
public void test2GetlList() throws SQLException {
Object result=dao.getList(target.getEmpno());
assertEquals(target, result);
}
@Test
public void test3AddlList() throws SQLException {
EmpDto target=new EmpDto(18, 1818, "tester18",null);
assertSame(1, dao.addList(target));
}
@Test
public void test4RmlList() throws SQLException {
assertSame(1, dao.rmList(target.getEmpno()));
}
@Test
public void test5EditlList() throws SQLException {
target.setEname("test");
target.setPay(4000);
assertSame(1, dao.editList(target));
}
}
Interface
package com.gimhae.framework.jdbc;
public interface RowMapper {
T mapper(ResultSet rs) throws SQLException;
}
Jetty WAS 컨테이너를 이용해 서버 배포하기
https://jetty.org/download.html
Jetty Downloads :: Eclipse Jetty
Jetty 12 is currently the community-supported version of Jetty. This means that Jetty 12 is the actively developed and supported version of Jetty for the open-source community. Issues filed for Jetty 12 at the GitHub repository are actively triaged and we
jetty.org
jetty 버전별 특징
- JDK 버전에 따라 사용할 수 있는 버전이 있다.
Embeded Jetty
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-server -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.56.v20240826</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-webapp -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>9.4.56.v20240826</version>
</dependency>
<!-- jetty jsp -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>apache-jsp</artifactId>
<version>9.4.56.v20240826</version>
</dependency>
서버 start
https://jetty.org/docs/jetty/12/programming-guide/maven-jetty/jetty-maven-helloworld.html
Using Maven :: Eclipse Jetty
Maven uses convention over configuration, so it is best to use the project structure Maven recommends. You can use archetypes to quickly setup Maven projects, but we will set up the structure manually for this simple tutorial example: > mkdir JettyMavenHel
jetty.org
html
public class App {
public static void main(String[] args) throws Exception {
Server serve=new Server(8080);
WebAppContext ctxt=new WebAppContext();
ctxt.setContextPath("/");
ctxt.setResourceBase("./src/main/WebApp");
serve.setHandler(ctxt);
serve.start();
}
}
Plugin으로 올리기
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.56.v20240826</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugins>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.56.v20240826</version>
</plugin>
</plugins>
</build>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>framework</servlet-name>
<servlet-class>com.gimhae.framework.mvc.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>framework</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.location.href='index.do';
</script>
</head>
<body>
</body>
</html>
DispatcherServlet
package com.gimhae.framework.mvc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DispatcherServlet extends HttpServlet{
Map<String,String> map;
@Override
public void init() throws ServletException {
map=new HashMap<String,String>();
Properties props=new Properties();
File f=new File("C:\\workspace\\Day42\\src\\main\\resources\\framework.properties");
Reader reader;
try {
reader=new FileReader(f);
props.load(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Set<Entry<Object,Object>> entrys=props.entrySet();
for(Entry<Object,Object> entry:entrys) {
map.put(entry.getKey().toString(),entry.getValue().toString());
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doDo(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doDo(req,resp);
}
protected void doDo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(req.getContextPath().length());
String info=map.get(url);
MyController controller=null;
try {
Class clz=Class.forName(info);
controller=(MyController) clz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
String viewName=controller.execute(req);
if(viewName.startsWith("redirect:")) {
resp.sendRedirect(viewName.substring("redirect:".length()));
return;
}
String prefix="/WEB-INF/views/";
String suffix=".jsp";
viewName=prefix+viewName+suffix;
RequestDispatcher rd=req.getRequestDispatcher(viewName);
rd.forward(req, resp);
}
}
framework.properties
/index.do=com.gimhae.framework.controller.IndexController
/emp/index.do=com.gimhae.framework.controller.ListController
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<nav>
<a href="/index.do">home</a>
<a href="/emp/index.do">emp</a>
</nav>
<div class="container">
<div>
<h2>인덱스페이지</h2>
</div>
</div>
</body>
</html>
/emp/list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<nav>
<a href="/index.do">home</a>
<a href="/emp/index.do">emp</a>
</nav>
<div class="container">
<div>
<h2>리스트페이지</h2>
<table class="table">
<thead>
<tr>
<th>사번</th>
<th>이름</th>
<th>금액</th>
<th>날짜</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="bean">
<tr>
<td><a href="detail.do?idx=${bean.empno }">${bean.empno }</a></td>
<td><a href="detail.do?idx=${bean.empno }">${bean.ename }</a></td>
<td><a href="detail.do?idx=${bean.empno }">${bean.pay }</a></td>
<td><a href="detail.do?idx=${bean.empno }">${bean.hiredate }</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</body>
</html>
ListController
package com.gimhae.framework.controller;
public class ListController implements MyController{
@Override
public String execute(HttpServletRequest req) {
EmpDao dao=new EmpDao();
try {
req.setAttribute("list", dao.pullList());
} catch (SQLException e) {
e.printStackTrace();
}
return "emp/index";
}
}
Run As > Maven Build
'100일 챌린지 > 빅데이터기반 인공지능 융합 서비스 개발자' 카테고리의 다른 글
Day 42 - Spring 사용하기 (0) | 2024.09.24 |
---|---|
Day 42 - Dispatcher Servlet 성능 개선하기 (0) | 2024.09.24 |
Day 41 - Embeded (0) | 2024.09.23 |
Day 41 - Framework 만들기 (0) | 2024.09.23 |
Day 38 - Filter / Listener (1) | 2024.09.13 |