스프링

리펙토링

 

class UserController

if(!user.matchPassword(password)){
			log.info("login -  !password");
			return "redirect:/users/loginForm";
		}

 


		if(HttpSessionUtils.isLoginUser(session)){
			return "redirect:/";
		}
		User sessiondUser=HttpSessionUtils.getUserFromSession(session);
		if(!sessiondUser.matchId(id)){
			new IllegalStateException("You can't  update the anther user");
			return "redirect:/";
		}

 

 

package net.slipp.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.ThrowsAdvice;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import net.slipp.domain.User;
import net.slipp.domain.UserRepository;

@Controller
@RequestMapping("/users")
public class UserController {
	
	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/loginForm")
	public String loginForm(){
		return "/user/login";
	}
	
	@PostMapping("/login")
	public String login(String userId, String password, HttpSession session){
		User user =userRepository.findByUserId(userId);
		if(user==null){
			log.info("login -  user.null");
			return "redirect:/users/loginForm";
		}
		if(!user.matchPassword(password)){
			log.info("login -  !password");
			return "redirect:/users/loginForm";
		}
		
		log.info("login -  success");
		session.setAttribute(HttpSessionUtils.USER_SESSION_KEY, user);
		return "redirect:/";
	}
	
	@GetMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute(HttpSessionUtils.USER_SESSION_KEY);
		return "redirect:/";
	}
	
	
	
	@GetMapping("/form")
	public String form(){	
		return "/user/form";
	}
		
	
	@PostMapping("")
	public String create(User user){
		log.info("create   : {}", user.toString()); 
		// jpa h2 로 자동으로 인클로드 된다.
		userRepository.save(user);
		return "redirect:/users";
	}
	
	@GetMapping("")
	public String list(Model model){
		// userRepository.findAll() 목록 가져오기
		model.addAttribute("users", userRepository.findAll());
		return "/user/list";
	}
	
	
	@GetMapping("/{id}/form")
	public String updateForm(@PathVariable Long id, Model model, HttpSession session){

		if(HttpSessionUtils.isLoginUser(session)){
			return "redirect:/";
		}
		User sessiondUser=HttpSessionUtils.getUserFromSession(session);
		if(!sessiondUser.matchId(id)){
			new IllegalStateException("You can't  update the anther user");
			return "redirect:/";
		}
		
		log.info("update form {} ", id);
		User user =userRepository.findOne(id);
		model.addAttribute("user",user);
		return "/user/updateform";
	}
	
	
	@PutMapping("/update")
	public String update(User updateUser, HttpSession session){
		
		if(HttpSessionUtils.isLoginUser(session)){
			return "redirect:/";
		}
		User sessiondUser=HttpSessionUtils.getUserFromSession(session);
		if(!sessiondUser.getId().equals(updateUser.getId())){
			new IllegalStateException("You can't  update the anther user");
			return "redirect:/";
		}
				
		//save() 는 기존의 아이디값이 있으면 업데이트 없으면 인서트 한다.
		userRepository.save(updateUser);
		return "redirect:/users";
	}
	
	
	
}





 

 class HttpSessionUtils

 

package net.slipp.web;

import javax.servlet.http.HttpSession;

import net.slipp.domain.User;

public class HttpSessionUtils {
	public static final String USER_SESSION_KEY="sessionedUser";
	
	public static boolean isLoginUser(HttpSession session){
		Object sessionedUser =session.getAttribute(USER_SESSION_KEY);
		if(sessionedUser==null){
			return false;
		}
		return true;
	}
	
	public static User getUserFromSession(HttpSession session){
		if(!isLoginUser(session)){
			return null;
		}
		return (User)session.getAttribute(USER_SESSION_KEY);
	}
}

 

class User

	
	public boolean matchPassword(String newPassword){
		if(newPassword==null){
			return false;
		}
		return this.password.equals(newPassword);
	}
	
	public boolean matchId(Long newId){
		if(newId==null){
			return false;
		}
		return this.id.equals(newId);
	}

 

콘솔에 쿼리문 출력해서 보기

application.properties

spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true

 

spring.datasource.url=jdbc:h2:~/demo2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

server.port=1111
spring.mustache.expose-session-attributes=true

spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true

 

 

콘솔창 출력 결과

[2m2017-07-26 17:07:42.565[0;39m [32m INFO[0;39m [35m19568[0;39m [2m---[0;39m [2m[nio-1111-exec-3][0;39m [36mo.h.h.i.QueryTranslatorFactoryInitiator [0;39m [2m:[0;39m HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.email as email2_0_,
        user0_.name as name3_0_,
        user0_.password as password4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_
Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.email as email2_0_,
        user0_.name as name3_0_,
        user0_.password as password4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_ 
    where
        user0_.user_id=?
[2m2017-07-26 17:08:06.432[0;39m [32m INFO[0;39m [35m19568[0;39m [2m---[0;39m [2m[nio-1111-exec-8][0;39m [36mnet.slipp.web.UserController            [0;39m [2m:[0;39m login -  success
Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.email as email2_0_,
        user0_.name as name3_0_,
        user0_.password as password4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_

 

 

 

 

 

 

spring

 

about author

PHRASE

Level 60  머나먼나라

자기 부모를 섬길 줄 모르는 사람과는 벗하지 말라. 왜냐하면 그는 인간의 첫 걸음을 벗어났기 때문이다. -소크라테스

댓글 ( 5)

댓글 남기기

작성