자주 쓰는 Spring 정리 / Java 문법
자주 쓰는 Spring
Spring DB 연결 방법
https://0songha0.github.io/web-dev/2022-06-10-1
Spring annotation 정리
https://0songha0.github.io/web-dev/2023-02-08-1
요청 도메인 주소 반환 함수
public String getDomain(HttpServletRequest req) {
req.getSession().setAttribute("_paramReturnUrl", req.getParameter("_paramReturnUrl"));
// 현재 요청의 URL 가져오기
StringBuffer url = req.getRequestURL();
// 요청 도메인 추출
String domain = url.substring(0, url.indexOf("/", 8));
// 현재 접속한 URL이 IP면 IP, 도메인이면 도메인이 나옵니다.
// 예시 : http://211.188.35.25:8080 또는 http://www.naver.com
return domain;
}
사용 예시
@RequestMapping ("/cmmn/loginIntro.do")
public ModelAndView loginIntro(HttpServletRequest req, HttpServletResponse res) throws Exception {
ModelAndView mav = new ModelAndView();
CommonUtil commonUtil = new CommonUtil();
mav.addObject("domain", commonUtil.getDomain(req));
mav.setViewName("폴더경로/jap명");
return mav;
}
ModelAndView 사용법
// jsp View로 이동
ModelAndView mav = new ModelAndView();
mav.setViewName("layout명/경로/jsp명");
return mav;
// 다른 컨트롤러로 리다이렉트
return new ModelAndView("redirect:/컨트롤러명.do");
Java 문법
문자열로 변환
String.valueOf(변수);
int, float, double, char[] 등 다른 데이터 타입 및 객체를 문자열로 변환합니다.
toString 사용 시 단점
변수.toString();
toString 시 변수가 null이면 NullPointException이 발생하여 종료될 수 있습니다.
valueOf는 변수가 null이어도 Exception이 발생하지 않아 안전합니다.
추상메서드 및 디폴트메서드 차이
추상 메서드는 구현부가 없고, 반드시 하위 클래스에서 구현해야 하는 메서드입니다.
추상 메서드는 abstract 키워드로 직접 명시할 수 있습니다.
인터페이스에서 구현부가 없는 메서드는 자동으로 추상 메서드로 취급됩니다.
인터페이스에서 구현부를 가지는 디폴트 메서드는 default 키워드로 정의합니다.
스트림 (stream)
// 기본형 배열 최대값 구하기
Arrays.stream(배열명).max().getAsInt();
// 스트림에서 제공하는 리덕션 함수들은 OptionalInt 타입으로 리턴하므로, int로 변환하는 함수 사용 필요
// 기본형 배열 최소값 구하기
Arrays.stream(배열명).min().getAsInt();
// 기본형 배열 합계 구하기
Arrays.stream(배열명).sum();
// sum 합수는 기본형 int 리턴
// 조건에 따라 걸러내고, 각 요소를 다른 값으로 변환
List<Integer> result = 리스트명.stream() // 리스트를 스트림으로 변환
.filter(n -> n % 2 == 0) // 짝수 요소만 남긴 신규 스트림 생성
.map(n -> n * n) // 스트림 내 요소 값을 제곱
.toList(); // 스트림을 리스트로 변환
스트림은 오토박싱 및 내부처리 오버헤드로 인해 for문보다 약간 느릴 수 있습니다.