SPRING #2

aro9515·2022년 3월 30일
0

Spring #2

목록 보기
2/8

package com.example.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

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;

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

@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(member.toString());
    	MemberDTO retMember = mService.selectMemberLogin(member);
    	
    	// 성공
    	if(retMember != null) {
    		// 세션에 정보를 기록
    		// 자료가 유지되는 시간은 기본값 60*30 = 1800초
    		httpSession.setAttribute("SESSION_ROLE", retMember.getUrole());
    		httpSession.setAttribute("SESSION_EMAIL", retMember.getUemail());
    		httpSession.setAttribute("SESSION_NAME", retMember.getUname());
    		
    		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=a
    @RequestMapping(value="/delete", 
    		method = {RequestMethod.GET, RequestMethod.POST })
    public String deleteGETPOST(@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=a
    @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";
    	}
    	return "redirect:/seller/update?email=" + member.getUemail();
    }
}



--------------------------------------
package com.example.service;

import com.example.dto.MemberDTO;

import java.util.List;

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 MemberDTO selectMemberLogin(MemberDTO member) {
		//xml mapper호출 Member id가 selectMemberLogin인것
		return sqlFactory.openSession()
				.selectOne("Member.selectMemberLogin", member);
	}
	
	
    @Override
    public int insertMember(MemberDTO member) {
    	// 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);
	}


    
}


-----------------------------------------
<?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="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>

	<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 UNAME=#{uname}, UPHONE=#{uphone}
			WHERE UEMAIL=#{uemail}	
	</update>	

</mapper>



-----------------------------------

<!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>
    <div style="padding:20px">
        <h3>판매자로그인</h3>
        <hr />

        <form th:action="@{/seller/select}" method="post">
            이메일 : <input type="text" name="uemail" /><br />
            암호 : <input type="password" name="upw" /><br />
            <input type="submit" value="판매자로그인" />
        </form>
    </div>
</body>
</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>
	<div style="padding:5px">
		<h3>홈화면</h3>
		
		<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="@{/item/insert}">판매자물품등록</a>
			<a th:href="@{/seller/logout}">판매자로그아웃</a>
		</div>	
		
		<a th:href="@{/seller/selectlist}">판매자목록(운영자용)</a>
	</div>
    
</body>
</html>



=================================================

// h2DB사용하기

// 파일명 : pom.xml

	<!-- oracle session -->
	<dependency>
		<groupId>org.springframework.session</groupId>
		<artifactId>spring-session-jdbc</artifactId>
	</dependency>
	
	
	<dependency>
		<groupId>com.h2database</groupId>
		<artifactId>h2</artifactId>
		<scope>runtime</scope> <!-- *** 배포시에는 삭제 -->
	</dependency>


------------------------
// 파일명 : application/properties
# port number
server.port=9090

# context-path
server.servlet.context-path=/ROOT

# devtools
spring.devtools.livereload.enabled=true

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html


# oracle
# spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# spring.datasource.url=jdbc:oracle:thin:@1.234.5.158:11521/xe
# spring.datasource.username=ds200
# spring.datasource.password=pw200


# DB가 저장될 폴더 지정, db01은 파일명 ex) c:/tmp/db01
spring.datasource.url=jdbc:h2:file:C:/tmp/db01;Mode=Oracle     
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
spring.datasource.hikari.connection-timeout=600000
spring.datasource.hikari.maximum-pool-size=500
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.minimum-idle=20
spring.datasource.hikari.validation-timeout=3000
spring.datasource.hikari.idle-timeout=60000


# 시간, oracle, 테이블자동생성
server.servlet.session.timeout=1800
spring.session.store-type=jdbc    
spring.session.jdbc.initialize-schema=always


// 크롬에서 127.0.0.1:9090/ROOT/h2-console

----------------------------------

package com.example.dto;

import java.sql.Date;

import lombok.Data;

//물품테이블
@Data
public class ItemDTO {
	// 물품코드
	private Long icode;
	// 물품이름
	private String iname;
	// 물품내용
	private String icontent;
	// 물품가격
	private Long iprice;
	// 재고수량
	private Long iquantity;
	// 등록일
	private Date iregdate;
	// 이미지
	private byte[] iimage;
	// 이미지크기
	private Long iimagesize;
	// 이미지타입
	private String iimagetype;
	// 이미지명
	private String iimagename;
	// 이메일
	private String uemail;
}


<!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>
    <div style="padding:20px">
        <h3>물품등록</h3>
        <hr />

        <form th:action="@{/item/insert}" method="post" 
        	enctype="multipart/form-data">
           	물품명 : <input type="text" name="iname" /><br />
           	물품내용: <textarea rows="6" cols="" name="icontent"></textarea><br />
            가격 : <input type="text" name="iprice" /><br />
            수량 : <input type="text" name="iquantity" /><br />
            대표이미지 : <input type="file" name="timage" /><br />
            <hr />
            <input type="submit" value="물품등록" />
        </form>

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

-------------------------------

package com.example.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

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.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.example.dto.ItemDTO;
import com.example.service.ItemService;

@Controller
@RequestMapping(value="/item")
public class ItemController {
    
	@Autowired
	ItemService iService;
	
	// 127.0.0.1:9090/ROOT/item/selectlist?txt=검색어&page=1
	@GetMapping(value = "/selectlist")
	public String selectlistGET(Model model,
		@RequestParam(name = "txt", defaultValue = "") String txt,
		@RequestParam(name = "page", defaultValue = "1") int page) {

		Map<String, Object> map = new HashMap<>();
		map.put("txt", txt);
		map.put("start",page * 10-9 ); 
		map.put("end", page * 10);
		// page 1, start 1  end 10
		// page 2, start 11 end 20
		// page 3, start 21 end 30
		
		List<ItemDTO> list = iService.selectItemList(map);
		model.addAttribute("list", list);
		
		long cnt = iService.selectItemCount(txt);
		// 9  => 1
		// 11 => 2
		// 24 => 3
		model.addAttribute("pages", (cnt-1)/10+1);
		
		return "/item/selectlist";
	}
	
	
    @GetMapping(value="/insert")
    public String insertGET(){
        return "/item/insert";
    }
    
    @PostMapping(value="/insert")
    public String insertPOST(
    		HttpSession httpSession,
    		@ModelAttribute ItemDTO item,
    		@RequestParam(name="timage") MultipartFile file) 
    				throws IOException {
    	
    	//파일관련내용
    	item.setIimagetype(file.getContentType() );
    	item.setIimagename(file.getOriginalFilename());
    	item.setIimagesize(file.getSize());
    	item.setIimage(file.getBytes());
    	
    	//세션에서 이메일 꺼내기
    	String em = (String)httpSession.getAttribute("SESSION_EMAIL");
    	item.setUemail(em);
    	
    	System.out.println(item.toString());
    	
    	int ret = iService.insertItemOne(item);
    	if(ret == 1) {
    		return "redirect:/item/selectlist";
    	}
    	
    	return "redirect:/item/insert";
    }
}


----------------------------------

package com.example.service;

import java.util.List;
import java.util.Map;

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

import com.example.dto.ItemDTO;

@Service
public class ItemServiceImpl implements ItemService{

	@Autowired
	SqlSessionFactory sqlFactory;
	
	@Override
	public long selectItemCount(String txt) {
		return sqlFactory.openSession()
			.selectOne("Item.selectItemCount", txt);
	}

	
	@Override
	public int insertItemOne(ItemDTO item) {
		return sqlFactory.openSession()
			.insert("Item.insertItemOne", item);
	}

	@Override
	public List<ItemDTO> selectItemList(Map<String, Object> map) {
		return sqlFactory.openSession()
			.selectList("Item.selectItemList", map);
	}


}




----------------------------------

<?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="Item">

	<insert id="insertItemOne" 
		parameterType="com.example.dto.ItemDTO">
		INSERT INTO ITEM( ICODE, INAME, ICONTENT, IPRICE, 
			IQUANTITY, IIMAGE, IIMAGESIZE, IIMAGETYPE, 
			IIMAGENAME, UEMAIL ) 
		VALUES ( SEQ_ITEM_ICODE.NEXTVAL, #{iname},#{icontent},
			#{iprice}, #{iquantity},
			#{iimage, jdbcType=BLOB}, #{iimagesize},#{iimagetype},
			#{iimagename}, #{uemail} )
	</insert>
	
	<select id="selectItemList"	
		parameterType="map"
		resultType="com.example.dto.ItemDTO">
		SELECT * FROM (
			SELECT 
				I.ICODE, I.INAME, I.IPRICE, 
				I.IQUANTITY, I.IREGDATE,
				ROW_NUMBER() OVER (ORDER BY I.ICODE DESC) ROWN
			FROM 
				ITEM I	
			WHERE 
				I.INAME LIKE '%' || #{txt} || '%'
		)
		WHERE ROWN BETWEEN #{start} AND #{end} 	
	</select>

	<select id="selectItemCount"	
			parameterType="String" resultType="long">
		SELECT
			COUNT(*) CNT 
		FROM 
			ITEM I	
		WHERE 
			I.INAME LIKE '%' || #{txt} || '%'
	</select>
	
</mapper>



---------------------------------

<!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>
    <div style="padding:20px">
        <h3>물품목록</h3>
        <hr />
        <a th:href="@{/item/insert}">물품등록</a>
        
        <form th:action="@{/item/selectlist}" method="get">
        	<input type="text" name="txt" placeholder="검색어" />
        	<input type="submit" value="검색" />
        </form>
        <table border="1">
        	<tr>
        		<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>
        			<a th:href="@{/item/selectone(code=${tmp.icode})}"
        				th:text="${tmp.icode}"></a>
        		</td>
        		<td th:text="${tmp.iname}"></td>
        		<td th:text="${tmp.iprice}"></td>
        		<td th:text="${tmp.iquantity}"></td>
        		<td th:text="${tmp.iregdate}"></td>
        	</tr> 
        </table>
        
        <th:block th:each="i : ${#numbers.sequence(1, pages)}">
        	<a th:href="@{/item/selectlist(page=${i}, txt=${param.txt})}"
        		th:text="${i}"></a>
        </th:block>

    </div>
</body>
</html>
profile
The best

0개의 댓글