결과샷
1. 오른쪽에는 등록되어있는 유저들 리스트
2. 왼쪽에는 정보를 보거나, 수정 및 등록 할 수 있는 창을 준비
1. pom.xml (jdbc 인식 못해서 계속 404 에러뜨는데 뒤질뻔했다.. 정말 xml 너란자식... ㅠ)
<!-- jdbc -->
<repositories>
<repository>
<id>oracle</id>
<name>Oracle JDBC Repository</name>
<url>http://maven.jahia.org/maven2</url>
</repository>
</repositories>
<!-- Oracle JDBC: ojdbc6.jar -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.0</version>
</dependency>
<!-- mybatis -->
<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>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.2.0</version>
</dependency>
2. root-context.xml
<bean id= "dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@자신의 오라클주소" />
<property name="username" value="오라클계정" />
<property name="password" value="오라클비밀번호" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mapper의 위치/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
</bean>
3. web.xml
<!-- 프로젝트마다 추가하는 인코딩 -->
<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>
4. sql
CREATE TABLE USERS (
USERID VARCHAR2(20) PRIMARY KEY,
NAME VARCHAR2(20),
GENDER VARCHAR2(20),
CITY VARCHAR2(20)
);
5. UserDto
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {
private String userId, name, gender, city;
}
6. mapper.xml
<mapper namespace="mapper랑 연결되어있는 Dao의 위치">
// 1. list
<select id="selectUserList" resultType="com.koreait.mybatis04.dto.UserDto">
SELECT *
FROM USERS
</select>
// 2. View
<select id="selectUserByUserId" resultType="com.koreait.mybatis04.dto.UserDto">
SELECT *
FROM USERS
WHERE USERID = #{param1}
</select>
// 3. Insert (register)
<insert id="insertUser" parameterType="com.koreait.mybatis04.dto.UserDto">
INSERT
INTO USERS
VALUES (#{userId}, #{name}, #{gender}, #{city})
</insert>
// 4. Update (edit)
<update id="updateUser" parameterType="com.koreait.mybatis04.dto.UserDto">
UPDATE USERS
SET NAME = #{name}
, CITY = #{city}
WHERE USERID = #{userId}
</update>
// 5. Delete
<delete id="deleteUser">
DELETE
FROM USERS
WHERE USERID = #{param1}
</delete>
</mapper>
7. UserDao (interface)
public interface UserDao {
// List
public List<UserDto> selectUserList();
// View
public UserDto selectUserByUserId(String userId);
// Insert(Write)
public int insertUser(UserDto uDto);
// Edit
public int updateUser(UserDto uDto);
// Delete
public int deleteUser(String userId);
}
8. command
*기본 UserCommand interface
public interface UserCommand {
public Map<String, Object> execute(SqlSession sqlSession, Model model);
}
1) userList
public class UserListCommand implements UserCommand {
@Override
public Map<String, Object> execute(SqlSession sqlSession, Model model) {
UserDao uDao = sqlSession.getMapper(UserDao.class);
List<UserDto> list = uDao.selectUserList();
//뷰로 옮길 때 : model.addAttribute("list", list);
: model.addAttribute("list", list);
Map<String, Object> map = new HashMap<>();
map.put("list", list);
map.put("result", true);
return map;
}
}
2) userView
public class UserViewCommand implements UserCommand {
@Override
public Map<String, Object> execute(SqlSession sqlSession, Model model) {
Map<String, Object> map = model.asMap();
String userId = (String) map.get("userId");
UserDao uDao = sqlSession.getMapper(UserDao.class);
UserDto uDto = uDao.selectUserByUserId(userId);
Map<String, Object> map2 = new HashMap<>();
map2.put("uDto", uDto);
map2.put("result", true);
return map2;
}
}
3) userInsert
public class UserInsertCommand implements UserCommand {
@Override
public Map<String, Object> execute(SqlSession sqlSession, Model model) {
Map<String, Object> map = model.asMap();
UserDto uDto = (UserDto) map.get("uDto");
UserDao uDao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map2 = new HashMap<>();
map2.put("result", uDao.insertUser(uDto));
return map2;
}
}
4) userUpdate
public class UserUpdateCommand implements UserCommand {
@Override
public Map<String, Object> execute(SqlSession sqlSession, Model model) {
Map<String, Object> map = model.asMap();
UserDto uDto = (UserDto) map.get("uDto");
UserDao uDao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map2 = new HashMap<>();
map2.put("result", uDao.updateUser(uDto));
return map2;
}
}
5) userDelete
public class UserDeleteCommand implements UserCommand {
@Override
public Map<String, Object> execute(SqlSession sqlSession, Model model) {
Map<String, Object> map = model.asMap();
String userId = (String) map.get("userId");
UserDao uDao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map2 = new HashMap<>();
map2.put("result", uDao.deleteUser(userId));
return map2;
}
}
9. controller
모니터 피벗기능으로 찍으니까 ㄹㅇ 짱이다 !!!!!!!!!
xml 순서와 동일하게 위에서부터 index(홈), list, userView, insert, update, delete
10. Index.jsp (view)
항상 그랬듯... css와 html은 창피할정도로 기본만 했으므로.. script만 ㅋㄷㅋㄷ..
<!-- jQuery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
fn_userList();
fn_userView();
fn_userInsert();
fn_userUpdate();
fn_userDelete();
fn_init();
});
// 1. 목록
function fn_userList() {
$.ajax({
url: 'users',
type: 'get',
dataType: 'json',
success: function(response) {
/*
response = {
"list":[
{"userId":"user1", "name":"에밀리", "gender":"여", "address":"서울"},
{ ... },
{ ... },
{ ... },
{ ... }
],
"result":true
}
*/
if (response.result == true) {
userList(response.list); // 별도 함수로 구현
}
},
error: function(){
alert('error');
}
});
} // 1. 목록 fn_userList() 종료
// 2. 목록 출력
function userList(list) {
$('tbody').empty();
$.each(list, function(i, user){
$('<tr>')
.append($('<td>').append(user.userId))
.append($('<td>').append(user.name))
.append($('<td>').append(user.gender))
.append($('<td>').append(user.city))
.append($('<td>').append('<button id="btnSelect">조회</button>'))
.append($('<td>').append('<button id="btnDelete">삭제</button>'))
.append($('<input type="hidden" id="userId" />').val(user.userId))
.appendTo('tbody');
});
}
// 3. 보기
function fn_userView() {
// 아래 클릭 이벤트는 btnSelect 를 클릭할 수 없다.
// ajax를 통해서 나중에 추가된 (동적 바인딩) 버튼은 onclick 이 동작하지 않는다.
// $('#btnSelect').click(function(){});
// 동적으로 추가된 요소에 이벤트를 연결하려면 on 함수를 사용한다.
$('body').on('click', '#btnSelect', function() {
var userId = $(this).closest('tr').find('#userId').val(); // $(this) : #btnSelect
$.ajax({
url: 'users/' + userId,
type: 'get',
dataType: 'json',
success: function(obj) {
if (obj.result == true) {
userView(obj.uDto);
}
},
error: function() {
alert('error');
}
});
});
} // 3. 보기 fn_userView() 종료
// 4. 보기 userView
function userView(obj) {
$('input:text[name="userId"]').val(obj.userId);
$('input:text[name="name"]').val(obj.name);
$('input:radio[name="gender"][value="'+ obj.gender +'"]').prop('checked', true);
$('select[name="city"]').val(obj.city).prop('selected', true);
}
// 5. 등록 (register)
function fn_userInsert() {
$('#btnInsert').click(function(){
var userId = $('input:text[name="userId"]').val();
var name = $('input:text[name="name"]').val();
var gender = $('input:radio[name="gender"]:checked').val();
var city = $('select[name="city"]').val();
var obj = {
"userId":userId,
"name":name,
"gender":gender,
"city":city
};
$.ajax({
url: 'users',
type: 'post',
data: JSON.stringify(obj), // @RequestBody UserDto uDto
contentType: 'application/json', // @RequestBody 사용할 때 필수
dataType: 'json',
success: function(obj) {
if (obj.result == 1) {
alert('User registration has been completed.');
fn_userList();
}
},
error: function() {
alert('error');
}
});
});
} // 5.등록 fn_userInsert() 종료
// 6. 수정 (update)
function fn_userUpdate() {
$('#btnUpdate').click(function (){
var userId = $('input:text[name="userId"]').val();
var name = $('input:text[name="name"]').val();
var city = $('select[name="city"]').val();
var obj = {
"userId": userId,
"name": name,
"city": city
};
$.ajax({
url: 'users',
type: 'put',
data: JSON.stringify(obj),
contentType: 'application/json',
dataType: 'json',
success: function(obj) {
if (obj.result == 1) {
alert('User information has been updated.');
fn_userList();
}
},
error: function() {
alert('error');
}
});
});
} // 6. 수정 fn_userUpdate() 종료
// 7. 삭제
function fn_userDelete(){
$('body').on('click', '#btnDelete', function(){
var userId = $(this).closest('tr').find('#userId').val();
var deleteCheck = confirm('Are you sure you want to delete ' +userId + ' ?' );
if (deleteCheck) {
$.ajax({
url: 'users/' + userId,
type: 'delete',
dataType: 'json',
success: function(obj){
if (obj.result == 1) {
alert(userId + ' has been deleted.');
fn_userList();
}
},
error: function() {
alert('error');
}
});
}
});
} // 7. 삭제 fn_userDelete() 종료
// 8. 초기화
function fn_init(){
$('#btnInit').click(function(){
$('input:text[name="userId"]').val('');
$('input:text[name="name"]').val('');
$('input:radio[name="gender"]').prop('checked', false);
$('select[name="address"]').val('');
fn_userList();
});
}
'Backend > Spring' 카테고리의 다른 글
7. STS / MVC 처리 순서 (0) | 2020.10.04 |
---|---|
7. STS / @PathVariable @RequestParam (0) | 2020.09.13 |
5. STS / REST API (0) | 2020.09.07 |
4. STS / Mybatis 게시판에 이미지 업로드하고 다운로드 받기 (0) | 2020.09.04 |
3. STS 로 랜덤한 숫자의 인증코드 이메일로 보내고 인증절차 거치기 (0) | 2020.09.02 |