Spring 2022/03/28 새 프로젝트 시작/수정됨/(Mybatis,Member(Seller))

무간·2022년 3월 28일
0

프로젝트 생성 : boot_20220328


파일명 pom.xml

라이브러리 다운로드

		<!-- h2 db -->
		<dependency>
    		<groupId>com.h2database</groupId>
    		<artifactId>h2</artifactId>
    		<scope>runtime</scope> <!-- *** 배포시에는 삭제 -->
    	</dependency>

		<!-- oracle session -->
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-jdbc</artifactId>
		</dependency>
        
		<!-- oracle -->
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>

		<!-- thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- tomcat -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- devtools -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>

        <!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>


		<!-- 아래는 자동생성 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

파일명 boot_20220328/ Boot20220328Application.java

package com.example.boot_20220328;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {
	"com.example.controller",
	"com.example.service",
	"com.example.config"
})
public class Boot20220328Application {

	public static void main(String[] args) {
		SpringApplication.run(Boot20220328Application.class, args);
	}
}

파일명 config/ MybatisConfig.java

package com.example.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

// 환경설정 파일
// 실제적으로 필요없는 파일이나 mapper를 xml로 사용하기 위해 설정
// mapper를 현재는 interface방식으로 많이 사용

@Configuration
public class MybatisConfig {
    
    // 서버가 구동되기전에 만들어지는 객체    
    @Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
		System.out.println("datasource configuration");
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		
		//mappers 위치 설정
		Resource[] arrResource = new PathMatchingResourcePatternResolver().getResources("classpath:/mappers/*Mapper.xml");
		sqlSessionFactoryBean.setMapperLocations(arrResource);
		return sqlSessionFactoryBean.getObject();
    }    
}

파일명 controller/ HomeController.java

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    
    // 127.0.0.1:9090/ROOT/
    // 127.0.0.1:9090/ROOT/home
    @GetMapping(value = {"/","/home"})
    public String hameGET(){
        return "home";
    }
}

파일명 controller/ SellerController.java

package com.example.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.example.dto.MemberDTO;
import com.example.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value="/seller")
public class SellerController {
    @Autowired
    MemberService mService;


    // 127.0.0.1:9090/ROOT/seller/select / 로그인
    @GetMapping(value = "/select")
    public String selectGET(){
        return "/seller/select";
    }

    @PostMapping(value = "/select")
    public String selectPOST(
            HttpSession httpSession,
            @ModelAttribute MemberDTO member){
        // view에서 전달되는 값 확인용
        // System.out.println("==================");;
        // System.out.println(member.toString());
        // System.out.println("==================");;
        MemberDTO retMember = mService.selectMemberLogin(member);
        // 반환되는 경과(성공, 실패)
        if (retMember != null){ // 성공
            // System.out.println("==================");;
            // System.out.println(retMember.toString());;
            // System.out.println("==================");;
            // 세션에 정보를 기록 /자료가 유지되는 시간은 기본값 60*30 =1800초
            httpSession.setAttribute("SESSION_EMAIL", retMember.getUemail());
            httpSession.setAttribute("SESSION_NAME", retMember.getUname());
            httpSession.setAttribute("SESSION_ROLE", retMember.getUrole());
            return "redirect:/";
        }
        // 실패
        return "redirect:/seller/select"; 
    }

    @RequestMapping(value = "/logout", method = {RequestMethod.GET,RequestMethod.POST})
    public String logoutGETPOST(HttpSession httpSession){
        // 세션 데이터 지우기
        httpSession.invalidate();
        return "redirect:/";
    }


    // 127.0.0.1:9090/ROOT/seller/insert
    @GetMapping(value="/insert")
    public String insertGET(){
        // templates폴더 seller폴더 insert.html 표시(렌더링)
        return "/seller/insert";
    }

    @PostMapping(value = "/insert")
    public String insertPOST(@ModelAttribute MemberDTO member){
        System.out.println(member.toString());
        mService.insertMember(member);
        return "redirect:/home"; // 주소를 바꾼다음 엔터키
    }

    // 127.0.0.1:9090/ROOT/seller/selectlist
    @GetMapping(value = "/selectlist")
    public String selectlistGET(Model model){
        List<MemberDTO> list = mService.selectMemberList();
        model.addAttribute("list", list);
        return "/seller/selectlist";
    }

    // 127.0.0.1:9090/ROOT/seller/delete?email=aaa@gmail.com
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteGET(@RequestParam(name = "email") String em){
        int ret = mService.deleteMemberOne(em);
        if(ret == 1){
            // 성공
        }
        else{
            // 실패
        }
        return "redirect:/seller/selectlist";
    }

    // 127.0.0.1:9090/ROOT/seller/update?email=aaa@gmail.com
    @GetMapping(value="/update")
    public String updateGET( Model model, @RequestParam(name="email") String em){
        MemberDTO member = mService.selectMemberOne(em);
        model.addAttribute("obj", member);
        return "/seller/update";
    }

    @PostMapping(value = "/update")
    public String updatePOST(@ModelAttribute MemberDTO member){    
        System.out.println(member.toString());
        int ret = mService.updateMemberOne(member);
        if(ret == 1 ){
            return "redirect:/seller/selectlist";
        }
        else{
            return "redirect:/seller/update?email=" + member.getUemail();
        }        
    }
}

파일명 dto/ MemberDTO.java

package com.example.dto;

import java.util.Date;
import lombok.Data;

@Data
public class MemberDTO {
    // 이메일
    private String uemail;
    // 암호
    private String upw;
    // 이름
    private String uname;
    // 연락처
    private String uphone;
    // 권한
    private String urole;
    // 등록일
    private Date uregdate;

   	// 날짜 포멧을 바꿔서 보관하기 위한 변수
    private String uregdate1;
}

파일명 service/ MemberService.java

package com.example.service;

import java.util.List;

import com.example.dto.MemberDTO;

import org.springframework.stereotype.Service;

@Service
public interface MemberService {

    // 판매자 등록    
    public int insertMember(MemberDTO member);   

    // 판매자 목록(parameter은 없고 return 만 있음)
    public List<MemberDTO> selectMemberList();

    // 판매자 삭제 (이메일 전송 후 int값 리턴)
    public int deleteMemberOne (String uemail);

    // 판매자 1명 조회
    public MemberDTO selectMemberOne(String uemail);

    // 판매자 1명 수정
    public int updateMemberOne (MemberDTO member);
    
    // 로그인
    public MemberDTO selectMemberLogin(MemberDTO member);
}

파일명 service/ MemberServiceImpl.java

package com.example.service;

import java.util.List;

import com.example.dto.MemberDTO;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberServiceImpl  implements MemberService{

    // xml로 되어있는 mapper을 호출함
    @Autowired
    SqlSessionFactory sqlFactory;

    @Override
    public int insertMember(MemberDTO member) {
        // namespace가 Member이고 id가 insertMemberOne인 항목을 호출함.
        return sqlFactory.openSession().insert("Member.insertMemberOne",member);
    }

    @Override
    public List<MemberDTO> selectMemberList() {       
        // 네입스페이스명 .id명으로 호출함 
        return sqlFactory.openSession().selectList("Member.selectMemberList");
    }

    @Override
    public int deleteMemberOne(String uemail) {        
        return sqlFactory.openSession().delete("Member.deleteMemberOne",uemail);
    }

    @Override
    public MemberDTO selectMemberOne(String uemail) {        
        return sqlFactory.openSession().selectOne("Member.selectMemberOne", uemail);
    }

    @Override
    public int updateMemberOne(MemberDTO member) {        
        return sqlFactory.openSession().update("Member.updateMemberOne", member);
    }

    @Override
    public MemberDTO selectMemberLogin(MemberDTO member) {        
        // xml mapper호출 Member id가 selectMemberLogin인것
        return sqlFactory.openSession().selectOne("Member.selectMemberLogin", member);
    }
}

파일명 mapper/ memberMapper.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="Member">

    <select id="selectMemberOne" parameterType="String" resultType="com.example.dto.MemberDTO">
        SELECT M.* FROM MEMBER M WHERE M.UEMAIL=#{uemail}
    </select>

    <select id="selectMemberList" resultType="com.example.dto.MemberDTO">
        SELECT M.*,TO_CHAR(UREGDATE, 'YYYY-MM-DD') UREGDATE1 FROM MEMBER M
    </select>

    <insert id="insertMemberOne" parameterType="com.example.dto.MemberDTO">
        INSERT INTO MEMBER( UEMAIL, UPW, UNAME, UPHONE, UROLE )
        VALUES( #{ uemail}, #{upw}, #{uname}, #{uphone}, #{urole} )
    </insert>

    <delete id="deleteMemberOne" parameterType="String">
        DELETE FROM MEMBER WHERE UEMAIL=#{uemail}
    </delete>

    <update id="updateMemberOne" parameterType="com.example.dto.MemberDTO">
        UPDATE MEMBER SET UPHONE=#{uphone}, UNAME=#{uname} WHERE UEMAIL=#{uemail}
    </update>

    <select id="selectMemberLogin" parameterType="com.example.dto.MemberDTO" resultType="com.example.dto.MemberDTO">
        SELECT M.UEMAIL, M.UNAME, M.UPHONE, M.UROLE FROM MEMBER M 
        WHERE M.UEMAIL=#{uemail} AND M.UPW=#{upw}
    </select>

</mapper>

<!--  
위의 xml을 java로 변경했을 때 코드
public class Member {
    public int static insertMemberOne(MemberDTO member) {
        INSERT INTO ....
    }
}

Member obj = new Member();
obj.insertMemberOne();

Member.insertMemberOne(); 
 -->

파일명 home.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>home</title>
</head>

<body style="padding: 10px;">
    <div>
        <h3>home화면</h3>
        <p th:text="${session.SESSION_EMAIL}"></p>
        <hr />

        <div th:if="${session.SESSION_EMAIL == null}">
            <a th:href="@{/seller/select}">판매자 로그인</a>
            <a th:href="@{/seller/insert}">판매자 등록</a>
        </div>

        <div th:if="${session.SESSION_EMAIL != null}">
            <a th:href="@{/seller/logout}">판매자 로그아웃</a>
            <a th:href="@{/item/insert}">판매자 물품 등록</a>
        </div>
        <hr />
        <a th:href="@{/seller/selectlist}">판매자 목록(운영자용)</a>
    </div>    
</body>
</html>

파일명 seller/ insert.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>판매자등록</title>
</head>

<body style="padding: 10px;">
    <h3>판매자 등록 페이지 입니다.</h3>

    <hr />

    <div style="padding: 20px;">        
        <form th:action="@{/seller/insert}" method="post"> 
            <label style="width:75px; height: 30px; display:inline-block;">이메일 : </label>
            <input type="text" placeholder="이메일" name="uemail"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">암호 : </label>
            <input type="password" placeholder="암호" name="upw"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">암호확인 : </label>
            <input type="password" placeholder="암호확인" name="upw1"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">이름 : </label>
            <input type="text" placeholder="이름" name="uname"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">연락처 : </label>
            <input type="text" placeholder="연락처" name="uphone"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">권한 : </label>
            <select name="urole">
                <option value="SELLER">판매자</option>
            </select></br>

            <label style="width:75px; height: 30px; display:inline-block;"></label>                    
            <input type="submit"  value="판매자등록" />
        </form>        
    </div>    
</body>
</html>

파일명 seller/ selectlist.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>판매자목록</title>
</head>

<body style="padding: 10px;">
    <h3>판매자목록</h3>

    <hr />

    <div style="padding:20px">
        <table border="1">
        	<tr>
        		<th>번호</th>
        		<th>이메일</th>
        		<th>이름</th>
        		<th>연락처</th>
        		<th>권한</th>
        		<th>등록일</th>
        		<th>버튼</th>
        	</tr>		
        	<tr th:each="tmp, idx : ${list}">
        		<td th:text="${idx.count}"></td>
        		<td th:text="${tmp.uemail}"></td>
        		<td th:text="${tmp.uname}"></td>
        		<td th:text="${tmp.uphone}"></td>
        		<td th:text="${tmp.urole}"></td>
        		<td th:text="${tmp.uregdate1}"></td>
                <td>
                    <form th:action="@{/seller/delete}" method="post">
                        <input type="hidden" name="email" th:value="${tmp.uemail}" />
                        <input type="submit" value="post삭제" />
                    </form>

                    <a th:href="@{/seller/update(email=${tmp.uemail})}">수정</a>
                    <a th:href="@{/seller/delete(email=${tmp.uemail})}">삭제</a>
                </td>
        	</tr> 
        </table>

    </div>
</body>
</html>

파일명 seller/ update.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>판매자 수정</title>
</head>

<body style="padding: 10px;">
    <h3>판매자 수정 페이지 입니다.</h3>

    <hr />

    <div style="padding: 20px;">        
        <form th:action="@{/seller/update}" method="post"> 
            <label style="width:75px; height: 30px; display:inline-block;">이메일 : </label>
            <input type="text" placeholder="이메일" name="uemail" th:value="${obj.uemail}" /></br>            

            <label style="width:75px; height: 30px; display:inline-block;">이름 : </label>
            <input type="text" placeholder="이름" name="uname" th:value="${obj.uname}" /></br>

            <label style="width:75px; height: 30px; display:inline-block;">연락처 : </label>
            <input type="text" placeholder="연락처" name="uphone" th:value="${obj.uphone}" /></br>

            <label style="width:75px; height: 30px; display:inline-block;"></label>                    
            <input type="submit"  value="판매자수정" />
        </form>        
    </div>    
</body>
</html>

파일명 seller/ select.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인</title>
</head>

<body style="padding: 10px;">
    <h3>로그인 페이지 입니다.</h3>

    <hr />

    <div style="padding: 20px;">        
        <form th:action="@{/seller/select}" method="post"> 
            <label style="width:75px; height: 30px; display:inline-block;">이메일 : </label>
            <input type="text" placeholder="이메일" name="uemail"/></br>

            <label style="width:75px; height: 30px; display:inline-block;">암호 : </label>
            <input type="password" placeholder="암호" name="upw"/></br>            

            <label style="width:75px; height: 30px; display:inline-block;"></label>                    
            <input type="submit"  value="로그인" />
        </form>        
    </div>    
</body>
</html>
profile
당신을 한 줄로 소개해보세요

0개의 댓글