회원가입을 하기 위해 dao,service,serviceImpl,controller에 필요한 메소드를 추가하고 view를 생성한다.
package securityexam.dao;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import securityexam.dto.Member;
@Repository
public class MemberDao {
private NamedParameterJdbcTemplate jdbc;
private RowMapper<Member> rowMapper = BeanPropertyRowMapper.newInstance(Member.class);
private SimpleJdbcInsert insertAction;
public MemberDao(DataSource dataSource) {
this.jdbc = new NamedParameterJdbcTemplate(dataSource);
this.insertAction = new SimpleJdbcInsert(dataSource)
.withTableName("member")
.usingGeneratedKeyColumns("id");
}
public Member getMemberByEmail(String email) {
Map<String,Object> map = new HashMap<>();
map.put("email", email);
return jdbc.queryForObject(MemberDaoSqls.SELECT_ALL_BY_EMAIL, map, rowMapper);
}
public long insertUser(Member member) {
SqlParameterSource params = new BeanPropertySqlParameterSource(member);
return insertAction.executeAndReturnKey(params).longValue();
}
public long insertAdmin(Member member) {
SqlParameterSource params = new BeanPropertySqlParameterSource(member);
return insertAction.executeAndReturnKey(params).longValue();
}
}
MemberDao.java
회원가입폼에서 받아온 데이터를 추가시키기위해서 insertAction을 사용하는데
위 코드처럼 테이블명과 기본키만 지정해주면 sql문을 직접 작성하지않아도 스프링프레임워크가 데이터를 insert해준다.
package securityexam.service;
import securityexam.dto.Member;
import securityexam.service.security.UserDbService;
//회원관련 정보처리하는 서비스
public interface MemberService extends UserDbService {
void addMember(Member member, boolean b);
}
MemberService.java
package securityexam.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import securityexam.dao.MemberDao;
import securityexam.dao.MemberRoleDao;
import securityexam.dto.Member;
import securityexam.dto.MemberRole;
import securityexam.service.security.UserEntity;
import securityexam.service.security.UserRoleEntity;
@Service
public class MemberServiceImpl implements MemberService {
// 생성자에 의해 주입되는 객체이고, 해당 객체를 초기화할 필요가 이후에 없기 때문에 final로 선언하였다.
// final로 선언하고 초기화를 안한 필드는 생성자에서 초기화를 해준다.
private final MemberDao memberDao;
private final MemberRoleDao memberRoleDao;
// @Service가 붙은 객체는 스프링이 자동으로 Bean으로 생성하는데
// 기본생성자가 없고 아래와 같이 인자를 받는 생성자만 있을 경우 자동으로 관련된 타입이 Bean으로 있을 경우 주입해서 사용하게 된다.
public MemberServiceImpl(MemberDao memberDao, MemberRoleDao memberRoleDao) {
this.memberDao = memberDao;
this.memberRoleDao = memberRoleDao;
}
@Override
@Transactional
public UserEntity getUser(String loginUserId) {
Member member = memberDao.getMemberByEmail(loginUserId);
return new UserEntity(member.getEmail(),member.getPassword());
}
@Override
@Transactional
public List<UserRoleEntity> getUserRoles(String loginUserId) {
List<MemberRole> memberRoles = memberRoleDao.getRolesByEmail(loginUserId);
List<UserRoleEntity> list = new ArrayList<UserRoleEntity>();
for(MemberRole memberRole : memberRoles) {
list.add(new UserRoleEntity(loginUserId, memberRole.getRoleName()));
}
return list;
}
@Override
@Transactional
public void addMember(Member member, boolean b) {
if(b) {
memberDao.insertUser(member);
}else {
memberDao.insertAdmin(member);
}
}
}
MemberServiceImpl.java
boolean 타입의 매개변수가 true이면 관리자, false이면 일반 회원 계정으로 추가해주었다.
package securityexam.controller;
import java.security.Principal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 securityexam.dto.Member;
import securityexam.service.MemberService;
@Controller
@RequestMapping(path="/members")
public class MemberController {
//스프링컨테이너가 생성자를 통해 자동으로 주입한다.
private final MemberService memberService;
private final PasswordEncoder passwordEncoder;
public MemberController(MemberService memberService, PasswordEncoder passwordEncoder) {
this.memberService = memberService;
this.passwordEncoder = passwordEncoder;
}
@GetMapping("/loginform")
public String loginform() {
return "members/loginform";
}
@RequestMapping("/loginerror")
public String loginerror(@RequestParam("login_error")String loginError) {
return "members/loginerror";
}
@GetMapping("/joinform")
public String joinform() {
return "members/joinform";
}
//사용자가 입력한 name, email, password가 member에 저장된다.
@PostMapping("/join")
public String join(@ModelAttribute Member member) {
member.setPassword(passwordEncoder.encode(member.getPassword()));
memberService.addMember(member,false);
return "redirect:/members/welcome";
}
@GetMapping("/welcome")
public String welcome() {
return "members/welcome";
}
}
MemberController.java
회원가입에 필요한 메소드(joinform, join)와 회원가입 성공시 보여줄 메소드(welcome)를 추가해준다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 가입</title>
</head>
<body>
<div>
<h1>회원 가입 폼</h1>
<div>
<form method="post" action="join">
<div>
<label>name</label>
<input type="text" name="name">
</div>
<div>
<label>E-mail</label>
<input type="text" name="email">
</div>
<div>
<label>password</label>
<input type="password" name="password">
</div>
<div>
<label></label>
<input type="submit" value="회원가입">
</div>
</form>
</div>
</div>
</body>
</html>
joinform.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<h1>회원가입 성공</h1>
</body>
</html>
welcome.jsp
웹 어플리케이션을 실행한 후 http://localhost:8080/securityexam/members/joinform 를 입력한다.
회원가입 폼에 데이터를 기입하고 회원가입을 클릭하면 /members/welcome으로 넘어간다.
데이터베이스를 확인하면 데이터도 잘 추가된 것을 확인할 수 있다!
출처: https://ivory-room.tistory.com/32?category=875739 [개발로 자기개발]
'study > java' 카테고리의 다른 글
전자정부프레임워크기반 게시판 만들기 (2) (0) | 2021.12.30 |
---|---|
전자정부프레임워크기반 게시판 만들기 (1) 시작 (0) | 2021.12.30 |
[Spring Security] DB정보로 로그인/로그아웃하기 (2) (0) | 2021.12.30 |
[Spring Security] DB정보로 로그인/로그아웃하기 (1) (0) | 2021.12.30 |
[Spring Security] 스프링 시큐리티 설정 (0) | 2021.12.30 |