[Spring] CH14 스프링부트 컨트롤러 고급 - 필터와 예외처리 (책)

jaegeunsong97·2023년 3월 21일
0

[Fast Campus] Spring

목록 보기
22/44
post-thumbnail

https://github.com/codingspecialist/Springboot-Controller-High.git

📕 자바스크립트 응답


package shop.mtcoding.filterandhandler.util;

public class Script {

    public static String href(String uri){
        String sc = "";
        sc += "<script>";
        sc += "location.href='"+uri+"';";
        sc += "</script>";
        return sc;
    }

    public static String href(String uri, String msg){
        String sc = "";
        sc += "<script>";
        sc += "alert('"+msg+"');";
        sc += "location.href='"+uri+"';";
        sc += "</script>";
        return sc;
    }

    public static String back(String msg){
        String sc = "";
        sc += "<script>";
        sc += "alert('"+msg+"');";
        sc += "history.back();";
        sc += "</script>";
        return sc;
    }
}

📕 Fetch 요청


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>회원가입 페이지</h1>
<hr/>
<form>
    <input type="text" id="username"/> <br/>
    <input type="password" id="password"/><br/>
    <input type="tel" id="tel"/> <br/>
    <button type="button" onclick="join()">회원가입</button>
</form>

<script>
    async function join() {
        // this란 : https://www.youtube.com/watch?v=tDZROpAdJ9w
        // this.event.preventDefault(); // form 태그 액션을 실행하지마!!
        let requestBody = {
            username: document.querySelector("#username").value,
            password: document.querySelector("#password").value,
            tel: document.querySelector("#tel").value,
        };
        //console.log(requestBody);
        //console.log(JSON.stringify(requestBody));
        try {
            let response = await fetch("/join/v2", {
                method: "post",
                body: JSON.stringify(requestBody),
                headers: {
                    "Content-Type": "application/json; charset=utf-8"
                }
            });
            let responseBody = await response.json();
            if (!response.ok) {
                throw new Error(responseBody.msg);
            }
            console.log(responseBody.data);
            alert(responseBody.msg);
            location.href = "/home";
        } catch (err) {
            alert(err);
            //console.error(err);
        }
    }
</script>
</body>
</html>

📕 예외처리


package shop.mtcoding.filterandhandler.handler.ex;

import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

@Getter @Setter
public class ControllerException extends RuntimeException{

    private HttpStatus httpStatus;

    public ControllerException(String msg) {
        this(msg, HttpStatus.BAD_REQUEST);
    }

    public ControllerException(String msg, HttpStatus httpStatus) {
        super(msg);
        this.httpStatus = httpStatus;
    }
}
package shop.mtcoding.filterandhandler.handler.ex;

import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

@Getter @Setter
public class RestControllerException extends RuntimeException{
    private HttpStatus httpStatus;

    public RestControllerException(String msg) {
        this(msg, HttpStatus.BAD_REQUEST);
    }

    public RestControllerException(String msg, HttpStatus httpStatus) {
        super(msg);
        this.httpStatus = httpStatus;
    }
}
package shop.mtcoding.filterandhandler.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import shop.mtcoding.filterandhandler.dto.ResponseDto;
import shop.mtcoding.filterandhandler.handler.ex.RestControllerException;
import shop.mtcoding.filterandhandler.handler.ex.ControllerException;
import shop.mtcoding.filterandhandler.util.Script;

// RestController -> Data 줘
// Controller -> View줘 text/html 줘

@RestControllerAdvice
public class ExHandler {

    @ExceptionHandler(ControllerException.class)
    public String controllerException(ControllerException e){
        return Script.back(e.getMessage());
    }

    @ExceptionHandler(RestControllerException.class)
    public ResponseEntity<?> restControllerException(RestControllerException e){
        ResponseDto<?> responseDto = new ResponseDto<>(e.getMessage());
        return new ResponseEntity<>(responseDto, HttpStatus.BAD_REQUEST);
    }
}
throw new ControllerException("username을 입력해주세요");
throw new RestControllerException("username을 입력해주세요");

📕 필터


필터 생성

package shop.mtcoding.filterandhandler.filter;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import java.io.BufferedReader;
import java.io.IOException;

public class BlackListFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // x-www-form-urlencoded -> username=ssar
        String username = request.getParameter("username");
        if(username.equals("ssar")){
            // DS보다 먼저 작동한다.
            response.setContentType("text/plain; charset=utf-8");
            response.getWriter().println("당신은 블랙리스트입니다.");
            return;
        }
        chain.doFilter(request, response);
    }
}

필터등록

package shop.mtcoding.filterandhandler.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import shop.mtcoding.filterandhandler.filter.BlackListFilter;

@Configuration
public class FilterRegister {

    @Bean
    public FilterRegistrationBean<?> myFilterRegistration() {
        FilterRegistrationBean<BlackListFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new BlackListFilter());
        registration.addUrlPatterns("/login/*");
        registration.setOrder(1); // 필터 순서 설정
        return registration;
    }
}

📕 인터셉터


인터셉터 생성

package shop.mtcoding.filterandhandler.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 실행됨");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 실행됨");
    }

}

인터셉터 등록

package shop.mtcoding.filterandhandler.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import shop.mtcoding.filterandhandler.interceptor.LoginInterceptor;

@Configuration // new 가 됨
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/login/*");
    }
}
profile
블로그 이전 : https://medium.com/@jaegeunsong97

0개의 댓글