상세 컨텐츠

본문 제목

Spring - 웹에서 db 수정 및 삭제하기

Archive

by 에스프리터 2018. 4. 5. 17:00

본문




늘은 지난 편에 이어서 db를 수정하는 것을 배워볼 예정입니다. 지난편이 궁금하신 분은 바로가기로 들어가주세요. 이번편에는 전체가 아닌 수정과 삭제와 관련된 파일만을 올리려고 합니다. 전체 맥락은 내일 다시 올리도록 하겠습니다.

파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.




pack.controller 패키지

** DeleteController.java **
package pack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pack.model.MemberDao;

@Controller
public class DeleteController {
    @Autowired
    private MemberDao memberDao;
    
    @RequestMapping("delete")
    public ModelAndView delProcess(@RequestParam("id")String id) {
        memberDao.delData(id);
        
        return new ModelAndView("redirect:/list");
    }
}

** DeleteContents.java **
package pack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pack.model.MemberDao;
import pack.model.MemberDto;

@Controller
public class DetailContents {
    @Autowired
    private MemberDao memberDao;
    
    @RequestMapping("detail")
    public ModelAndView detailProcess(@RequestParam("id")String id) {
        MemberDto dto = memberDao.getMember(id);
        return new ModelAndView("detail", "mem", dto);
    }
}


** UpdateController.java **
package pack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pack.model.MemberDao;
import pack.model.MemberDto;

@Controller
public class UpdateController {
    @Autowired
    private MemberDao memberdao;
    
    private String formName = "upform";
    
    @RequestMapping(value="update", method=RequestMethod.GET)
    public ModelAndView form(@RequestParam("id")String id) {
        MemberDto dto = memberdao.getMember(id);
        //System.out.println(dto.getId() + " " + dto.getName());
        return new ModelAndView(formName, "updata", dto);
    }
    
    @RequestMapping(value="update", method=RequestMethod.POST)
    public ModelAndView submit(MemberBean bean) {
        memberdao.upData(bean);
        
        return new ModelAndView("redirect:/list"); // 수정 후 목록 보기
    }
}




pack.model 패키지

** MemberDao.java **
package pack.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Repository;

import pack.controller.MemberBean;

@Repository
public class MemberDao extends JdbcDaoSupport{
    
    public MemberDao(DriverManagerDataSource dataSource) {
        setDataSource(dataSource);
    }
    
    //전체 자료 읽기
    /*
    public List<MemberDto> getMemberAll() {
        String sql = "select * from member";
        
        List<MemberDto> list = getJdbcTemplate().query(sql, new RowMapper() {
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
            MemberDto dto = new MemberDto();
            dto.setId(rs.getString("id"));
            dto.setPasswd(rs.getString("passwd"));
            dto.setName(rs.getString("name"));
            dto.setRegdate(rs.getString("regdate"));
            return dto;
            }
        });
        return list;
    }
    */
    //전체 자료 읽기 / 페이지 나누기
    public List<MemberDto> getMemberAll(int startR, int endR) {
        String sql = "select * from member order by id asc limit ?,?";
        
        List<MemberDto> list = getJdbcTemplate()
                .query(sql, new Object[] {startR, endR}, new RowMapper() {
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
            MemberDto dto = new MemberDto();
            dto.setId(rs.getString("id"));
            dto.setPasswd(rs.getString("passwd"));
            dto.setName(rs.getString("name"));
            dto.setRegdate(rs.getString("regdate"));
            return dto;
            }
        });
        return list;
    }
    
    public int getMemberCount() {//전체 레코드 건수(페이지 나누기용)
        String sql = "select count(*) from member";
        return getJdbcTemplate().queryForObject(sql, Integer.class);
    }
    
    // 추가 : jdbcDaoSupport
    public void insData(MemberBean bean) {
        String sql = "insert into member values(?,?,?,now())";
        Object[] args = {bean.getId(), bean.getPasswd(), bean.getName()};
        getJdbcTemplate().update(sql, args);
    }
    
    //부분 자료 읽기
    public MemberDto getMember(String id) {
        String sql = "select * from member where id=?";
        
        MemberDto dto = (MemberDto)getJdbcTemplate()
                        .queryForObject(sql, new Object[]{id}, new RowMapper() {                        
        public Object mapRow(ResultSet rs, int arg1) throws SQLException {
            MemberDto dto = new MemberDto();
            dto.setId(rs.getString("id"));
            dto.setPasswd(rs.getString("passwd"));
            dto.setName(rs.getString("name"));
            dto.setRegdate(rs.getString("regdate"));
            return dto;
            }
        });
        return dto;
    }
    
    // 수정 : jdbcDaoSupport
    public void upData(MemberBean bean) {
        String sql = "update member set passwd=?, name=? where id=?";
        getJdbcTemplate().update(sql, new Object[] {bean.getPasswd(), bean.getName(),bean.getId()});
    }
    
    // 삭제 : jdbcDaoSupport
    public void delData(String id) {
        String sql = "delete from member where id=?";
        getJdbcTemplate().update(sql, new Object[] {id});
    }
    
}


view 폴더

** upform.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
* 자료 수정 * <p/>
<form action ="update" method="post">
<input type="hidden" name="id" value="${updata.id}">
아이디 : ${updata.id} <br>
회원명 : <input type="text" name="name" value="${updata.name}"><br>
비밀번호 : <input type="text" name="passwd" value="${updata.passwd}"><br>
<br>
<input type="submit" value="수정확인">
</form>
</body>
</html>





결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.









태그

관련글 더보기

댓글 영역