예외처리 클래스
- 메세지의 값을 부모에게 전달 처리
암호화 처리
- 사용자로부터 입력받아 전달된 비밀번호를 암호화 변환하여 필드값 변경
- ⇒요청 처리 메소드에서 암호화 변환하여 필드값 변경 기능
- 암화화 처리 기능을 제공하는 jbcrypt 라이브러리를 프로젝트에 빌드 처리 -pom.xml
- 암호화처리하는 라이브러리
<!-- https://mvnrepository.com/artifact/org.mindrot/jbcrypt -->
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
UserinfoServiceImpl
- Service 클래스의 메소드는 명령 실행시 발생되는 문제에 대한 예외 발생
- ⇒ 발생된 예외는 Controller 클래스에서 예외처리 되도록 전달
- BCrypt.hashpw(String password, String salt) : 전달받은 비밀번호에 첨가물을 삽입한 후 암호화 처리 하여 반환하는 메소드
- BCrypt.gensalt(int log_bounds) : 첨가물의 길이를 전달받아 첨가물을 생성하여 반환하는 메소드
- ⇒ 매개변수가 없느 메소드를 호출한 경우 첨가물의 길이는 기본값(10)으로 자동 설정
public void addUserinfo(Userinfo userinfo) throws UserinfoExistsException {
if(userinfoDAO.selectUserinfo(userinfo.getUserid())!=null) {
throw new UserinfoExistsException("이미 사용중인 아이디를 입력 하였입니다.", userinfo);
}
**userinfo.setPassword(BCrypt.hashpw(userinfo.getPassword(), BCrypt.gensalt()));**
userinfoDAO.insertUserinfo(userinfo);
}
- BCrypt.checkpw(String plainText, String hashed) : 일반 문자열과 암호화 처리된 문자열을 비교하여 다른 경우 false 반환하고 같은 경우 true를 반환하는 메소드
@Override
public void loginAuth(Userinfo userinfo) throws LoginAuthFailException {
Userinfo authUserinfo=userinfoDAO.selectUserinfo(userinfo.getUserid());
if(authUserinfo==null) {//아이디 인증 실패
throw new LoginAuthFailException("아이디의 회원정보가 존재하지 않습니다.", userinfo.getUserid());
}
if(!**BCrypt.checkpw(userinfo.getPassword(), authUserinfo.getPassword()))** {//비밀번호 인증 실패
throw new LoginAuthFailException("아이디가 없거나 비밀번호가 맞지 않습니다.", userinfo.getUserid());
}
}
- @ExceptionHandler : Controller 클래스의 요청 처리 메소드에서 발생된 예외를 처리하기 위해 예외처리 메소드를 설정하는 어노테이션
- value 속성 : 예외 처리할 예외클래스(Clazz)를 속성값으로 설정
- ⇒ 다른 속성이 없는 경우 속성값만 설정 가능
- 예외처리 메소드의 매개변수에는 예외처리 관련 값(객체)를 제공받아 사용 가능하며 ViewName를 반환하여 JSP 문서로 응답 처리
@ExceptionHandler(value = UserinfoExistsException.class)
public String exceptionHandler(UserinfoExistsException exception, Model model) {
model.addAttribute("message", exception.getMessage());
model.addAttribute("userinfo", exception.getUserinfo());
return "userinfo/user_write";
}
ExceptionController
@ControllerAdvice : Controller 클래스를 Spring Bean으로 등록하기 위한 어노테이션
⇒ 예외처리메소드만 선언된 Controller 클래스를 Spring Bean으로 등록할 때 사용
⇒ 모든 Controller 클래스의 요청 처리 메소드에서 발생되는 예외에 대한 처리 가능
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = Exception.class)
public String exceptionHandler(Exception exception) {
exception.printStackTrace();
return "userinfo/user_error";
}
}
AdminAuthInterceptor
- 관리자 권한 관려 처리를 위한 Interceptor 클래스
- ⇒ 요청 처리 메소드의 명령이 실행되기 전에 비로그인 사용자이거나 관리자가 아닌 사용자인 경우 웹프로그램을 요청한 경우 에러페이지로 응답 처리
- Interceptor 클래스 : Front Controller에 의해 요청 처리 메소드의 명령 실행 전후에 삽입되어 동작될 기능을 제공⇒ Bean Configuration File(servlet-context.xml)에서 Spring Bean으로 등록
- public class AdminAuthInterceptor implements HandlerInterceptor
- ⇒ Interceptor 클래스 HandlerInterceptor 인터페이스를 상속받아 작성
- preHandle : 요청 처리 메소드의 명령이 실행되게 전에 실행될 명령을 작성하는 메소드⇒ false 반환 : 요청처리 메소드의 명령 미실행 , true 반환 : 요청 처리 메소드의 명령 실행
- ⇒ 권한 관련 명령을 실행하기 위해 사용하는 메소드
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session=request.getSession();
Userinfo loginUserinfo=(Userinfo)session.getAttribute("loginUserinfo");
if(loginUserinfo==null || loginUserinfo.getStatus()!=9) {
//request.getRequestDispatcher("userinfo/user_error.jsp").forward(request, response);
//return false;
throw new Exception();
}
return true;
}
- postHandle : 요청 처리 메소드의 명령이 정상적으로 실행된 후에 실행될 명령을 작성하는 메소드⇒ 요청 처리 메소드의 반환값(ModelAndView)을 조작할 경우 사용하는 메소드
- ⇒ 요청 처리 메소드의 명령 실행시 예외가 발생된 경우 postHandle 메소드의 명령 미실행
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
- afterCompletion : 요청 처리 메소드의 명령 실행되기 전에 비로그인 사용자가 웹프로그램을 요청할 경우 에러페이지 생성
- @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub HandlerInterceptor.super.afterCompletion(request, response, handler, ex); }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
LoginAuthIntercetor
로그인 관련 권한 처리를 위한 Interceptor 클래스
⇒ 요청 처리 메소드의 명령이 실행되기 전에 비로그인 사용자이거나 관리자가 아닌 사용자인 경우 웹프로그램을 요청한 경우 에러페이지로 응답 처리
public class LoginAuthIntercetor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session=request.getSession();
if(session.getAttribute("loginUserinfo")==null) {
throw new Exception();
}
return true;
}
}
Sevlet-context
- Interceptor 클래스를 Spring Bean으로 등록
<beans:bean class="xyz.itwill10.util.AdminAuthInterceptor" id="adminAuthInterceptor"/>
<beans:bean class="xyz.itwill10.util.LoginAuthIntercetor" id="loginAuthIntercetor"/>
- interceptors : 인터셉터를 설정하기 위한 상위 엘리먼트
- interceptor : 인터셉터를 등록하기 위한 엘리먼트
- mapping : 인터셉터가 동작될 요청 URL 주소에 패턴을 등록하는 엘리먼트
- ⇒ path : 클라이언트의 요청 URL 주소의 패턴을 속성값으로 설정
- ref : 클라이언트 요청에 의해 동작될 Interceptor SpringBean을 등록하는 bean
- ⇒ bean 속성 : Interceptor 클래스의 Spring BeanName을 속성값으로 설정
<interceptors>
<interceptor>
<mapping path="/userinfo/join"/>
<mapping path="/userinfo/modify"/>
<mapping path="/userinfo/remove"/>
<beans:ref bean="adminAuthInterceptor"/>
</interceptor>
</interceptors>
- * : 현재 폴더의 모든 페이지, ** : 현재 폴더와 하위 폴더의 모든 페이지
- exclude-mapping : 인터셉터가 동작되지 않는 요청 URL 주소의 패턴을 설정하는 엘리먼트
<interceptors>
<interceptor>
<mapping path="/userinfo/*"/>
<mapping path="/userinfo/li*"/>
<mapping path="/userinfo/**"/>
<exclude-mapping path="/userinfo/login"/>
<beans:ref bean="loginAuthIntercetor"/>
</interceptor>
</interceptors>
댓글