반응형
테이블 생성
MemberVO.java
package com.example.domain;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.Data;
@Data
public class MemberVO {
private String id;
private String passwd;
private String name;
private String email;
private Date regDate;
private String recvEmail; // "Y" or "N"
}
BoardVO.java
package com.example.domain;
import java.util.Date;
import lombok.Data;
@Data
public class BoardVO {
private int num;
private String mbrid;
private String title;
private String content;
private Date regDate;
private int readcount;
private String ip;
private int reRef; // 글 그룹 번호
private int reLev; // 글 들여쓰기 레벨
private int reSeq; // 글 그룹 내에서의 순번
}
인터페이스 MemberMapper 생성
package com.example.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.example.domain.MemberVO;
public interface MemberMapper {
@Insert("INSERT INTO member (id, passwd, name, email, reg_date, recv_email) "
+ "VALUES (#{id}, #{passwd}, #{name}, #{email}, #{regDate}, #{recvEmail})")
int insert(MemberVO memberVO);
@Select("SELECT COUNT(*) FROM member WHERE id = #{id}")
int getCountById(String id);
@Select("SELECT * FROM member WHERE id = #{id}")
MemberVO getMemberById(String id);
@Select("SELECT * FROM member")
List<MemberVO> getMembers();
@Delete("DELETE FROM member WHERE id = #{id}")
int deleteMemberById(String id);
@Update("UPDATE member "
+ "SET passwd = #{passwd}, name = #{name}, email = #{email}, recv_email = #{recvEmail} "
+ "WHERE id = #{id}")
void updateMemberById(MemberVO memberVO);
}
MemberService 클래스 생성
※ 마지막 MVC 구조 설명에 왜 Service 클래스가 필요한지 나와있습니다.
package com.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.domain.MemberVO;
import com.example.mapper.MemberMapper;
import lombok.Setter;
@Service
//@Transactional // 이 클래스에 있는 각 메소드 호출마다 트랜잭션 단위로 처리됨
public class MemberService {
@Setter(onMethod_ = @Autowired)
private MemberMapper memberMapper;
public int register(MemberVO memberVO) {
int rowCount = memberMapper.insert(memberVO);
return rowCount;
}
public int getCountById(String id) {
return memberMapper.getCountById(id);
}
public MemberVO getMemberById(String id) {
return memberMapper.getMemberById(id);
}
public List<MemberVO> getMembers() {
return memberMapper.getMembers();
}
public int removeMemberById(String id) {
return memberMapper.deleteMemberById(id);
}
public void modifyMemberById(MemberVO memberVO) {
memberMapper.updateMemberById(memberVO);
}
}
트렌잭션 사용을 위해 root-context에 코드 삽입 및 설정
※ 이후 트렌잭션을 사용하기 위해 root-context에 소스 삽입과
Spring이 해당 클래스를 찾을수있게끔 context:component-scan을 추가
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<context:component-scan base-package="com.example.service" />
MemberServiceTests.java
package com.example.service;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.example.domain.MemberVO;
import lombok.Setter;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class MemberServiceTests {
@Setter(onMethod_ = @Autowired)
private MemberService memberService;
@Test
public void testRegister() {
MemberVO memberVO = new MemberVO();
memberVO.setId("aaa");
memberVO.setPasswd("1234");
memberVO.setName("홍길동");
memberVO.setEmail("aaa@a.com");
memberVO.setRecvEmail("Y");
memberVO.setRegDate(new Date());
int rowCount = memberService.register(memberVO);
assertEquals(1, rowCount);
}
}
한글 깨짐현상 해결하기
<filter>
<filter-name>setCharacterEncodingFilter</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
DB회원목록에 암호노출위험이 있으므로 암호화하기
※ pom.xml에 jdbrypt 소스 추가하기
<!-- https://mvnrepository.com/artifact/org.mindrot/jbcrypt -->
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
MemberController.java
@PostMapping("/join")
public String join(MemberVO memberVO) {
// 회원가입 날짜 셋팅
memberVO.setRegDate(new Date());
String passwd = memberVO.getPasswd();
String hashPasswd = BCrypt.hashpw(passwd, BCrypt.gensalt());
memberVO.setPasswd(hashPasswd);
System.out.println(memberVO.toString());
// 회원가입 처리함
memberService.register(memberVO);
return "redirect:/member/login";
}
※ 한글깨짐이 사라지고 사용자 정보를 가지고 있는 데이터베이스가
만약 해킹당할 수 있기 때문에 패스워드 해싱을 해주어 사용자의 패스워드를 보호해준다.
Null값 에러방지
src/main/resources => mybatis-config.xml 생성 후 소스 삽입
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.example.domain"/>
</typeAliases>
</configuration>
Mybatis에서 해당 파일 읽게 만들기
root-context.xml에 소스를 삽입한다.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis-config.xml" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
반응형
'Back-End > Java' 카테고리의 다른 글
[Spring] Legacy Project Handler intercepor 사용법 (0) | 2021.06.10 |
---|---|
[Spring] Legacy Project 회원탈퇴 및 회원정보수정 구현하기 (0) | 2021.06.09 |
[Spring] Legacy Project Controller 설정 및 MVC 구조 (0) | 2021.06.09 |
[Spring] Legacy Project 오라클 연동하기 (0) | 2021.06.08 |
[Spring] Legacy Project mybatis 설정 및 실행 (0) | 2021.06.04 |