inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

Ajax 인증시 인가코드가 발급 되지 않는 원인 문의

해결됨

스프링 시큐리티 OAuth2

Spring Authorization 1.0,1 기반으로 개발을 하고 있습니다. 인가코드를 발급 할떄 FormLogin 기본 설정을 사용하면 인가코드가 발급이 되는데 Ajax 로 로그인을 하면 인가코드가 발급되지 않고 있습니다. 디버깅을 해보면 로그인인 후 OAuth2AuthorizationEndpointFilter 는 실행되는데 @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.authorizationEndpointMatcher.matches(request)) { filterChain.doFilter(request, response); return; } try { Authentication authentication = this.authenticationConverter.convert(request); if (authentication instanceof AbstractAuthenticationToken) { ((AbstractAuthenticationToken) authentication) .setDetails(this.authenticationDetailsSource.buildDetails(request)); } Authentication authenticationResult = this.authenticationManager.authenticate(authentication); if (!authenticationResult.isAuthenticated()) { // If the Principal (Resource Owner) is not authenticated then // pass through the chain with the expectation that the authentication process // will commence via AuthenticationEntryPoint filterChain.doFilter(request, response); return; } if (authenticationResult instanceof OAuth2AuthorizationConsentAuthenticationToken) { if (this.logger.isTraceEnabled()) { this.logger.trace("Authorization consent is required"); } sendAuthorizationConsent(request, response, (OAuth2AuthorizationCodeRequestAuthenticationToken) authentication, (OAuth2AuthorizationConsentAuthenticationToken) authenticationResult); return; } this.authenticationSuccessHandler.onAuthenticationSuccess( request, response, authenticationResult); } catch (OAuth2AuthenticationException ex) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Authorization request failed: %s", ex.getError()), ex); } this.authenticationFailureHandler.onAuthenticationFailure(request, response, ex); } } FormLogin 적용시에는 authenticationResult의 principal 에 UsernamePasswordAuthenticationToken이 설정되어 인가 코드가 정상적으로 발급되는데 AjaxLogin 적용시에는 authenticationResult의 principal 에 AnonymousAuthenticationToken이 설정되어 인가 코드가 정상적으로 발급되지 않고 403 예외가 발생합니다. AuthenticationProvider 구현체에서는 정상적으로 토큰을 저장하고 있습니다. AuthenticationProvider 구현체 소스 @Component @RequiredArgsConstructor public class CustomAuthenticationProvider implements AuthenticationProvider { private final CustomUserDetailsService customUserDetailsService; private final PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if(authentication == null){ throw new InternalAuthenticationServiceException("Authentication is null"); } LoginRequestDto loginRequestDto = (LoginRequestDto)authentication.getPrincipal(); String password = loginRequestDto.getLoginPassword(); UserAdapter userAdapter = (UserAdapter) customUserDetailsService.loadUserByLoinRequestDto(loginRequestDto); if (!passwordEncoder.matches(password, userAdapter.getCurrentUser().getLoginPwd())) { throw new BadCredentialsException("BadCredentialsException"); } CustomAuthenticationToken result = CustomAuthenticationToken.authenticated(userAdapter.getCurrentUser(), authentication.getCredentials(), userAdapter.getAuthorities()); result.setDetails(authentication.getDetails()); return result; } @Override public boolean supports(Class<?> authentication) { return CustomAuthenticationToken.class.isAssignableFrom(authentication); } } 이외 Custom 소스 Spring Security 설정 @EnableWebSecurity @RequiredArgsConstructor @Configuration public class DefaultSecurityConfig { private final CustomAuthenticationProvider customAuthenticationProvider; // private final CustomUserDetailsService customUserDetailsService; @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public CustomAuthenticationProcessingFilter customAuthenticationProcessingFilter() throws Exception { CustomAuthenticationProcessingFilter filter = new CustomAuthenticationProcessingFilter(); // filter.setAuthenticationManager(authenticationManager(null)); filter.setAuthenticationManager(new ProviderManager(customAuthenticationProvider)); // filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler()); // filter.setAuthenticationFailureHandler(customAuthenticationFailureHandler()); return filter; } // @formatter:off @Bean SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorizeRequests ->authorizeRequests .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .requestMatchers(new AntPathRequestMatcher("/")).permitAll() .requestMatchers(new AntPathRequestMatcher("/login/**")).permitAll() .requestMatchers("/api/login/**").permitAll() .requestMatchers("/api/registered-client/**").permitAll() .anyRequest().authenticated() ); http.addFilterBefore(customAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class); http.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer .authenticationEntryPoint(new CustomLoginAuthenticationEntryPoint()) .accessDeniedHandler(customAccessDeniedHandler()) ); // http.userDetailsService(customUserDetailsService); // http.formLogin(); http.csrf().disable(); return http.build(); } // @formatter:on @Bean public AccessDeniedHandler customAccessDeniedHandler() { return new CustomAccessDeniedHandler(); } @Bean public AuthenticationSuccessHandler customAuthenticationSuccessHandler() { return new CustomAuthenticationSuccessHandler(); } @Bean public AuthenticationFailureHandler customAuthenticationFailureHandler() { return new CustomAuthenticationFailureHandler(); } } Ajax 로그인 처리 필터 소스 public class CustomAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { private final ObjectMapper objectMapper = new ObjectMapper(); private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/api/login", HttpMethod.POST.name()); public CustomAuthenticationProcessingFilter() { super(DEFAULT_ANT_PATH_REQUEST_MATCHER); } public CustomAuthenticationProcessingFilter(AuthenticationManager authenticationManager) { super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } LoginRequestDto loginRequestDto = objectMapper.readValue(request.getReader(), LoginRequestDto.class); if(StringUtils.isEmpty(loginRequestDto.getLoginId())||StringUtils.isEmpty(loginRequestDto.getLoginPassword())) { throw new IllegalStateException("Username or Password is empty"); } CustomAuthenticationToken authRequest = CustomAuthenticationToken.unauthenticated(loginRequestDto, loginRequestDto.getLoginPassword()); authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); return getAuthenticationManager().authenticate(authRequest); } } CustomAuthenticationToken 소스 public class CustomAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Object principal; private Object credentials; public CustomAuthenticationToken(Object principal, Object credentials) { super(null); this.principal = principal; this.credentials = credentials; setAuthenticated(false); } public CustomAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; this.credentials = credentials; super.setAuthenticated(true); // must use super, as we override } public static CustomAuthenticationToken unauthenticated(Object principal, Object credentials) { return new CustomAuthenticationToken(principal, credentials); } public static CustomAuthenticationToken authenticated(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) { return new CustomAuthenticationToken(principal, credentials, authorities); } @Override public Object getCredentials() { return this.credentials; } @Override public Object getPrincipal() { return this.principal; } }

  • java
  • oauth
  • spring-boot
  • spring
신석균 댓글 2 좋아요 1 조회수 1390

시간 오류 - getTime()

해결됨

한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

안녕하세요. 한국에선 문제 없던 앱이. 미국에서 동작할경우 등록한 날짜보다 하루 전의 날짜로 저장되는문제를 겪었습니다. 찾아보니 getTime()도 toISOString 와 마찬가지로 UTC 0+ 시간으로 작동되는 부분이 문제였습니다. 스토리지에 저장되는 타임스탬프가 UTC 기반이였던거죠. 달력에서 날짜를 설정할때 시간은 반영되지않고 12am 즉 00시로 설정되는데, 한국은 UTC +9 이라 날짜에 영향을 주지 않았지만, 제가 있는 지역의 타임존은 UTC -5이기에 하루전날의 타임스탬프가 저장되고 다시 그 타임스탬을 이용해 new Date(date)을 해줄때 전날의 날짜가 불러진다고 결론내렸습니다. 이문제를 해결하기위해, 스트로지에 타임스탬프가아닌 getStringDate 으로 뽑아낸 스트링 날짜를 넣어주었고. 다이어리 리스트에서 sort 를 위한 비교를할때만 getTime()을 써주었습니다. 전문가의 의견을 듣고싶습니다.

  • javascript
  • nodejs
  • react
Junhaeng Lee 댓글 2 좋아요 0 조회수 1535

JdbcTemplate 테스트에서의 중복 회원 예외 오류가 뜨는 이유를 모르겠습니다.

미해결

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (비슷한 내용은 있었지만 원하는 해답을 찾지 못했습니다) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예) [질문 내용] 여기에 질문 내용을 남겨주세요. 차근차근 강의 예제를 따라가면서 잘 오고 있었는데 테스트 하는 부분에서 갑작스런 오류로 인해 해답을 찾던 도중 어려움을 겪어서 프로젝트 링크와 오류 사진을 남기겠습니다 https://drive.google.com/file/d/1DIAzsFD6RnTCv73h-kNpeDWUE5CsF8oC/view?usp=share_link

  • spring-boot
  • mvc
  • MVC
  • spring
  • java
김동우 댓글 2 좋아요 1 조회수 738

화살표 함수 질문드립니다.

해결됨

한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

화살표 함수 질문드립니다. const a = (a ) => {a *b } 보통 이렇게 가는데 어떤건 const a = (a ) => { ( a* b ) } 으로 괄호가 들어가더라구요 어떤 경우에 괄호가 들어가고 어떤 경우에는 빠지는지가 궁금합니다 .

  • react
  • node.js
  • nodejs
  • javascript
blossom_mind 댓글 1 좋아요 0 조회수 595

Click Redo 에서 set State 실행 부분 (비동기 관련)

해결됨

웹 게임을 만들며 배우는 React

안녕하세요. 강사님. 강사님의 높은 퀄리티의 강의를 듣고 열심히 공부중입니다. 감사합니다. 질문 사항은 다음과 같습니다. 아래는 로또번호를 다시 추첨하는 '한번 더' 버튼을 누를 때의 함수인데요. 보시면 winNumbers와 winBalls 의 setState가 같이 변경이 되고 있습니다. 제가 생각할 때에는, winNumbers의 당첨 번호가 모두 다 만들어 진 후에 winBalls의 배열이 [] 으로 되어, runTimeouts() 가 실행되어야 할 것 같은데요. 실제로 set State 가 비동기로 실헹되기 때문에, 만약 로직상 번호를 다 만들고 timeouts를 실행해야 한다면, 동기적으로 처리를 하는 것이 맞지 않을까 라는 생각이 들어서 입니다. 혹시 강사님의 생각은 어떠신가요..? 질문 읽어주셔서 감사합니다!

  • react
김민정 댓글 1 좋아요 0 조회수 448

업로드 후 홈화면에서 이미지가 보이지 않습니다

미해결

비전공자를 위한 진짜 입문 올인원 개발 부트캠프

데이터 베이스에도 기록이 잘 들어가고 사이트 홈화면에도 잘 뜨는데 화면의 이미지가 안뜹니다. uploads파일에도 이미지 다 잘 들어갑니다. 인강과 데이터베이스를 비교해봤을 때 경로문제인것같긴한데 어떻게 수정을 해야할까요? 근데 DB경로의 역슬래시를 슬래시로 바꾸어도 안뜨고 uploads에는 사진도 잘 들어가고 사진의 경로를 봤을때도 동일해서... 왜 안뜨는걸까요? 단순히 한사진의 오류라고생각했었는데 등록한 것 모두 이렇게 되어서... 어딜 어떻게 수정해야할지모르겠어서... 일단은 깃허브링크 함께올려봅니다... 홈사이트 화면 개발자 툴 상품넣고 난뒤 DB데이터 베이스 물건 등록 후 vscode에 뜨는것 깃허브 링크: https://github.com/Dalrae03/webstudy/commit/7a5981dafabdbf009b40c0c5814e7e7c6f3ea9de https://github.com/Dalrae03/webstudy/commit/c9106654b1d6badba9ae64ce744a11da46b719a5

  • html/css
  • 머신러닝 배워볼래요?
  • express
  • node.js
  • react-native
  • react-native
  • tensorflow
  • react
  • 머신러닝
  • HTML/CSS
  • nodejs
  • javascript
Yoo Seung Hwan 댓글 1 좋아요 0 조회수 602

static 메소드와 instance 메소드의 접근?

해결됨

나도코딩의 자바 기본편 - 풀코스 (20시간)

안녕하세요 ㅎㅎ 다름이 아니라 나도코딩 자바편에서 메소드를 공부하면서 궁금증이 생겨, 이렇게 또 다시 질문을 남깁니다...ㅎ 나도코딩 자바편을 보는 것과 동시에, 제 스스로 나름 예제들도 풀면서 개념을 익히고 있는데요...ㅎ 방금 전에 제가 문자열(String)배열과 charAt()을 이용하여, 전치행렬을 만드는데 성공했습니다...ㅎ 결과도 잘 출력했구요 ㅎㅎ 이 예제를 푸는 데는 String, String[], length(), charAt()에 대한 선생님의 도움과 답변이 없었으면 풀지 못했을 건데, 선생님의 자세한 답변 덕분에 문제를 빠르게 잘 풀 수 있었습니다. 감사합니다 ㅎㅎ 아래가 제가 쓴 코드고, 출력한 결과입니다: 여기서부터가 제 질문인데요...ㅎ static 메소드(public static void main(String[] args) {...})에서 일반 메소드를 접근하려면, 에러 메시지로 'non-static variable/method cannot be referenced fromstatic context.'라고 나오는데, 이럴 경우에 에러를 없애고, 결과를 잘 출력하려면: pubilc static void main 메소드 앞에 첫 번째 방법으로 void transpose 메소드를 static void tranpose라고 바꾸거나, 아니면 2번째 방법으로 static 메소드 안에서 이렇게 Question_03 making = new Question_03(); 즉, (클래스 이름) (객체 이름) = new (클래스 이름)(); 이런 식으로 객체화를 해서 메소드를 접근해야 하나요?

  • java
  • 객체지향
  • 메소드
  • oop
  • static
댓글 1 좋아요 0 조회수 751

next.js 버전이 12인건가요?

해결됨

따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)

강의에서 사용하고 있는 next 버전이 궁금합니다. 12버전인가요?

  • nodejs
  • node.js
  • docker
  • postgresql
  • typescript
  • react
  • 클론코딩
  • next.js
  • Next.js
  • 클론코딩
김현성 댓글 1 좋아요 0 조회수 385

image 파일에서 vscode로 드래그 앤 드롭을 처리할 수 없다고 합니다

미해결

비전공자를 위한 진짜 입문 올인원 개발 부트캠프

압축을 푼뒤 진행해도 에러가 납니다 The file is not displayed in the text editor because it is either binary or uses an unsupported text encoding.라고 나오고요 hexeditor를 깔아도 해결이 안됩니다 찾아보니 50mb를 넘는 자료를 vs코드에서 지원을 못한다고 하는데요 참고로 집에 컴퓨터가 없어 pc방 컴퓨터로 배우는 중입니다

  • html/css
  • javascript
  • tensorflow
  • node.js
  • HTML/CSS
  • nodejs
  • react-native
  • 머신러닝
  • react
  • 머신러닝 배워볼래요?
  • express
tostarmk 댓글 1 좋아요 0 조회수 1035

31강 대출기능에서 테이블 생성에 대한 질문입니다.

해결됨

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

대출기능을 개발하려고 하니, 저희가 가진 두 테이블, User와 Book은 서로를 가리킬 필드가 없어서 '대출했다.'라는 정보를 표시할 수 없었습니다. 그래서 user_loan_history 테이블을 새로 만드는 내용이 강의의 주된 내용이 되는데요, 제가 궁금한건 여기서 User와 Book 테이블을 수정하여, 예를들면 User테이블에는 OneToMany로 Book의 id를 가리킬 수 있는 필드를, Book테이블에는 ManyToOne으로 User의 id를 가리킬 수 있는 필드를 추가하여 개발할 수도 있지 않나 싶어서요! 객체지향적으로 생각했을 때 User와 Book은 객체지만, '대출기록'은 객체가 아니라 객체간의 관계 같아서 테이블로 만드는 것에 거부감이 생기는 것 같습니다. 어떤 이유에서 기존의 테이블을 수정하지 않고, 새로운 테이블을 만들었는지 궁금합니다!

  • spring
  • spring-boot
  • JPA
  • java
  • aws
  • jpa
  • mysql
Dompoo 댓글 1 좋아요 2 조회수 474

SpringConfig에 JdbcMemberRepsoitory반환 오류

미해결

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

[질문 내용] SpringConfig클래스에 MemoryMemberRepsoitory 메소드에 retrun new JdbcMemberRepository();를 하고 dataSource 객체 생성 후 생성자까지 만들어주었습니다. 여기까지는 ()에 오류가 생기는데 여기에 dataSource를 넣어주면 전체오류가 생기여 옵션엔터를 눌러 해결하면 메소드 이름을 MemoryMemberRepository가 아닌 JdbcMemeberRepository로 바꿔라 합니다. 이를 변경하면 위에 MemberService도 바꿔야하며 전체코드에 이상이 생깁니다. package hello.hellospring; import hello.hellospring.repository.JdbcMemberRepository; import hello.hellospring.repository.MemoryMemberRepository; import hello.hellospring.service.MemberService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class SpringConfig { DataSource dataSource; public SpringConfig(DataSource dataSource) { this.dataSource = dataSource; } @Bean public MemberService memberService(){ return new MemberService(memberRepository()); } @Bean public MemoryMemberRepository memberRepository(){ //return new MemoryMemberRepository(); return new JdbcMemberRepository(dataSource); //오류발생 } } java: incompatible types: hello.hellospring.repository.JdbcMemberRepository cannot be converted to hello.hellospring.repository.MemoryMemberRepository 이러한 오류내용이 뜹니다. 수업 소스코드와 동일하게 해봤는데 이럽니다!

  • MVC
  • java
  • mvc
  • spring
  • spring-boot
  • spring-boot
nskynet5374 댓글 1 좋아요 0 조회수 667

Spring Boot 3.0.2~ nativeQuery 작성시 에러

해결됨

재고시스템으로 알아보는 동시성이슈 해결방법

안녕하세요 강의듣다가 막혔다 해결한 부분이 있어서 혹여나 동일한 문제를 겪고 있으신 분이 계실까봐 공유드립니다. named lock파트의 native query를 작성하는 부분에서 강의 코드와 동일하게 작성하였음에도 불구하고 스프링 빈을 초기화 하는 과정에서 다음과 같은 에러를 만나게 되었습니다. 작성한 코드 @Query("select get_lock(:key, 3000)", nativeQuery = true) fun getLock(key: String) @Query("select release_lock(:key)", nativeQuery = true) fun releaseLock(key: String) 발생한 에러 Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract void com.waterfogsw.cucurrentsolutions.domain.LockRepository.getLock(java.lang.String); Reason: Cannot invoke "String.contains(java.lang.CharSequence)" because "variable" is null at app//org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) at app//org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:115) at app//org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:99) at app//org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:88) at java.base@17.0.6/java.util.Optional.map(Optional.java:260) at app//org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:88) at app//org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:357) at app//org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279) at app//org.springframework.data.util.Lazy.getNullable(Lazy.java:245) at app//org.springframework.data.util.Lazy.get(Lazy.java:114) at app//org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285) at app//org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132) at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1798) at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1748) ... 122 more Caused by: java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "variable" is null at org.springframework.data.jpa.repository.query.QueryUtils.createCountQueryFor(QueryUtils.java:620) at org.springframework.data.jpa.repository.query.DefaultQueryEnhancer.createCountQueryFor(DefaultQueryEnhancer.java:49) at org.springframework.data.jpa.repository.query.StringQuery.deriveCountQuery(StringQuery.java:111) at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.<init>(AbstractStringBasedJpaQuery.java:82) at org.springframework.data.jpa.repository.query.NativeJpaQuery.<init>(NativeJpaQuery.java:58) at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:53) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:170) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:252) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95) at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:111) ... 134 more 동일한 강의를 수강중이던 지인분과 함께 비교해본 결과 스프링 부트 버전 문제임을 확인하였습니다. 지인분은 data jpa 3.0.1 버전을 사용중이셨고, 저는 data jpa 3.0.3버전을 사용하였는데 3.0.2 이상 버전에서 nativeQuery=true 사용시 NullPointerException이 발생하는 이슈가 있음을 알려드립니다. 저는 부트버전을 3.0.1로 다운그레이드하여 정상적으로 실습 진행할 수 있었습니다 :) https://github.com/spring-projects/spring-data-jpa/issues/2812

  • spring
  • java
  • 동시성
ddd 댓글 2 좋아요 3 조회수 2172

CalculatorAddRequest 질문

미해결

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

안녕하세요 선생님. CalculatorAddRequest 클래스에서 number1과 number2를 private final로 설정하는 이유가 무엇인가요? 감사합니다.

  • java
  • mysql
  • spring
  • JPA
  • jpa
  • spring-boot
  • aws
댓글 1 좋아요 1 조회수 440

loanBook 메소드 만들 때 유저정보 가져오는 코드에서 오류가 납니다

해결됨

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

예외 처리 부분이니까 주석 처리하면 실행될까 했는데 아래와 같은 에러메시지가 나옵니다. 혹시 몰라 전체 코드를 깃헙에 업로드해놓겠습니다! https://github.com/you-eun-hye/library-app-Inflearn

  • java
  • mysql
  • aws
  • spring-boot
  • jpa
  • JPA
  • spring
유은혜 댓글 1 좋아요 1 조회수 398

로그인 폼을 만들고 로컬 스토리지에 jwt저장하기 강의에서 질문입니다!

해결됨

파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트

import React, { useState } from "react"; import { Card, Button, Form, Input, notification } from "antd"; import { useHistory } from "react-router-dom"; import Axios from "axios"; import { SmileOutlined, FrownOutlined } from "@ant-design/icons"; import useLocalStorage from "utils/useLocalStorage"; export default function Login() { const history = useHistory(); const [jwtAccessToken, setJwtAccessToken] = useLocalStorage( "jwtAccessToken", "" ); console.log("loaded Token: ", jwtAccessToken); // 왜 이게 두번이나 출력되는 것이지? const onFinish = (values) => { async function fn() { const { username, password } = values; const data = { username, password }; try { //응답을 꼭 받아야 한다. 토큰을 받아야 하니까 const response = await Axios.post( "http://127.0.0.1:8000/accounts/token/", data, { headers: { "Content-Type": "application/json" } } ); // const { data: token } = response; 이런 방식은 아래랑 다르다 response에서 data을 꺼내서 이름을 token이라 짓는 것 // const token = response.data 와 일치하며 밑에 녀석은 // const jwtAccessToken = response.data.access 과 일치한다 const { data: { access: jwtAccessToken }, } = response; setJwtAccessToken(jwtAccessToken); notification.open({ message: "로그인 성공!", icon: <SmileOutlined style={{ color: "#108ee9" }} />, }); // history.push("/accounts/login"); //TODO: 이동주소 } catch (error) { console.log(error); if (error.response) { notification.open({ message: "로그인 실패!", icon: <FrownOutlined style={{ color: "#ff3333" }} />, description: "아이디/암호를 확인해 주세요.", onClick: () => { console.log("Notification Clicked!"); }, }); } } } fn(); }; return ( <Card title="login"> <Form labelCol={{ span: 8 }} //부트스트랩은 한 행이 12 컬럼인데 antd는 24컬럼임 wrapperCol={{ span: 16 }} style={{ maxWidth: 600 }} onFinish={onFinish} autoComplete="off" > <Form.Item label="Username" name="username" rules={[{ required: true, message: "Please input your username!" }]} //rules을 통해 유효성검사로직이 들어가 잇다 > <Input /> </Form.Item> <Form.Item label="Password" name="password" rules={[ { required: true, message: "Please input your password!" }, { min: 5, message: "5자리 이상 해주세요" }, // 한글자 한글자 들어갈때마다 검사해준다. ]} > <Input.Password /> </Form.Item> {/* //8칸 이동하고 16칸을 쓰겠다 */} <Form.Item wrapperCol={{ offset: 8, span: 16 }}> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> </Card> ); } 안녕하세요 강사님!! 위에서 15번째 줄에 있는 console.log("loaded Token: ", jwtAccessToken); 이 부분이 페이지의 콘솔창에서 두번이나 나타납니다... 왜 그런지 알 수 있을까요?? 새로고침을 했을때도 두번 나타나고 submit을 했을 때도 2번 출력됩니다. 아 ! 그리고 simplejwt토큰을 사용중 입니다!

  • docker
  • django
  • python
  • react
꺼넝 댓글 1 좋아요 0 조회수 714

getVideoFileCount 변수 선언하는 이유

미해결

나도코딩의 자바 기본편 - 풀코스 (20시간)

안녕하세요 선생님🙇‍♀️ 클래스_메소드 강의를 보다 궁금한 점이 생겨 질문 남깁니다. BlockBox 클래스에 두 메소드를 넣었고, 04_Method클래스에 두 메소드를 활용한 문장이 있었는데요. insertMemoryCard()는 그대로 사용했지만, getVideoFileCount()는 다시 변수로 선언한 이유가 무엇인가요? 감사합니다. void inserMemoryCard(int capacity) { System.out.println("메모리 카드가 삽입되었습니다."); System.out.println("용량은 " + capacity + "GB 입니다."); } void getVideoFileCount(int type) { if ( type == 1) { return 9; } else if ( type == 2) { return 1; } return 10; } b1.insertMemoryCard(256); int fileCount = b1.getVideoFileCount(1);

  • oop
  • 객체지향
  • java
고 예진 댓글 3 좋아요 0 조회수 677

csrf 토큰 시큐리티 6버전 변경사항

해결됨

스프링 시큐리티

안녕하세요 강의 잘 보고있습니다. csrf 토큰 값을 헤더에 넣어서 실습하는 부분 따라해봤는데 잘 안되서 코드를 뜯어봤습니다. 이번에 시큐리티 버전이 6으로 올라가면서 csrf 토큰을 인코딩해서 전달하고 이걸 디코딩하는 부분이 영상과 다른것같았습니다. 그래서 기본으로 제공하는 로그인 페이지에서 디버깅을 해보았는데 클라이언트에 전달한 csrf 토큰값이랑 실제 서버가 가지는 csrf 토큰값이 서로 달랐습니다. 이렇게되면 영상에서 보여주신 실습은 제대로 동작하지 않는게 맞나요? 해당 사진은 CsrfFilter에서 actualToken을 받아오기 위한XorCsrfTokenRequestAttributeHandler 클래스 내부에 존재하는 resolveCsrfTokenValue 함수의 소스코드입니다. 예제 따라하면 항상 마지막에 사이즈 비교하는 부분에서 걸렸습니다.

  • java
  • spring-boot
  • spring-security
  • Spring Security
  • spring-boot
김민종 댓글 2 좋아요 0 조회수 1320

@types/cors설치

미해결

따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 22:03 초 부분 에 cors 설치하시는데 요거는 안하셨는데 해야되는거 맞나요?? 저는 안하니까 오류나서 설치하라고 뜨더라구요.. 영상에서는 설치안했는데도 오류 안뜨는 거같아서.. 아님 제가 잘 못본걸 수도 있어서 알려주시면 감사드립니다!

  • node.js
  • typescript
  • docker
  • react
  • nodejs
  • postgresql
  • 클론코딩
  • next.js
  • Next.js
  • 클론코딩
oridori2705 댓글 2 좋아요 1 조회수 506

모임 만들기 페이지에서 시간을 설정할 때, 연월일 제외하고 시간만 입력하려면 어떻게 하면 되는지요?

미해결

스프링과 JPA 기반 웹 애플리케이션 개발

안녕하세요. 모임 만들기 페이지에서 시간을 설정할 때, 연월일 제외하고 시간만 입력하려면 어떻게 하면 되는지요? fragments.html 의 <div th:fragment="event-form (mode, action)"> 에서 <input id="endEnrollmentDateTime" type="datetime-local" 의 type 부분을 type="time" 으로 하고 Event 클래스에서 private LocalDateTime endEnrollmentDateTime; 을 private DateTime endEnrollmentDateTime; 로 변경하고 실행하면 html 상에서는 시간이 입력되나, DB 에는 insert 되어 있지 않습니다. 어떻게 하면 가능한지요? 자세한 설명 부탁드립니다. 그리고, 제공해 주신 소스를 다운로드해서 프로젝트를 실행한 후, 오른쪽 드롭다운 메뉴 중 스터디를 클릭해도 아무 동작이 일어나지 않습니다. 소스를 보면 <a class="dropdown-item" >스터디</a> 이렇게만 나와있고 th:href="@{}" 로 연결된 페이지가 없습니다. 이 부분 기능 구현은 안 해 놓으신 건지요? 프로필 페이지에서도 왼쪽 프로필 사진 밑에 있는 스터디 버튼을 누르면 Study 라고만 나오고 별다른 페이지가 나오지 않습니다. 이 부분도 기능 구현은 안 해 놓으신 건지요?

  • java
  • spring
  • spring-boot
  • jpa
  • JPA
  • spring-boot
  • thymeleaf
박종성 댓글 1 좋아요 0 조회수 480

Postman 406, 404 에러

미해결

실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화

첫번째 PostMapping 으로 했을때 값 등록은 잘되는데 406 에러가 나옵니다. 두번째 update 할때는 값도 변경안되고 404 에러가 납니다..

  • spring
  • spring-boot
  • jpa
  • JPA
  • java
114tla 댓글 4 좋아요 0 조회수 1716

인기 태그

인프런 TOP Writers

주간 인기글