inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

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

출력(전반전-정수)

미해결

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

정수 3자리마다 콤마가 찍히는 원리를 답변 받고 싶습니다 ㅠㅠ

  • oop
  • java
문수 댓글 2 좋아요 -1 조회수 414

임베티드 타입에 대해 질문있습니다.

미해결

자바 ORM 표준 JPA 프로그래밍 - 기본편

7분44초에 임베디드 타입에서 같은 객체를 사용하여 저장하고 setter를 통해서 값을 수정하게 되면 같은 객체의 인스턴스를 사용하기 때문에 값이 member1과 member2가 둘 다 바뀐다고 하셔서 제가 테스트를 해봤습니다. 같은 메서드에서 member1과 member2를 같은 address 객체를 사용해서 저장한 건 똑같은데 다른 메서드에서 아래에 코드 처럼 member1을 찾아와서 city를 수정하니 member2는 수정이 안된 것을 확인하였습니다. 이것은 다른 트랜잭션을 사용하기 때문에 같은 인스턴스를 공유하고 있지 않은 건가요? Member member = em.find(Member.class, 1L); member.getHomeAddress().setCity("city");

  • java
  • JPA
댓글 1 좋아요 0 조회수 401

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

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

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

섹션 4 -> 그리디 , 결정문제 질문

미해결

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

안녕하세요! 강의 정말 잘 듣고 있습니다. 섹션 4를 풀다가, 어떤 문제를 그리디를 쓰고, 어떤문제를 결정알고리즘을 써야하는지 감이 잡히지 않아서 질문 드립니다. 답변해주시면 정말 감사하겠습니다!

  • 코딩-테스트
  • 코테 준비 같이 해요!
  • python
깨위 댓글 1 좋아요 0 조회수 268

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

해결됨

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

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

  • spring
  • spring-boot
  • JPA
  • java
  • jpa
  • aws
  • 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

이 문제에서 궁금한게있습니다.

미해결

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

ch[i] != 0라서 if문을 탐색하지않는다면 L에 해당하는 dfs함수는 뭘 반환하는건가요?? 반환하는게 안보일때는 return이 생략됐다고 생각하는건가요?

  • 코딩-테스트
  • python
  • 코테 준비 같이 해요!
코딩코딩코딩코 댓글 1 좋아요 0 조회수 355

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
  • spring-boot
  • jpa
  • 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

안녕하세요. 다른 풀이도 풀었는데 괜찮을까요?

미해결

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

정답은 제대로 나오긴 했는데 시간 초과라던가 하는 문제가 없을까요? 4중 for문은 생각지도 못했네요..ㅠㅠ sudoku = [list(map(int, input().split())) for _ in range(9)] def solution(sudoku): length = len(sudoku) a, b, c, = list(), list(), list() # 행열 검사 for i in range(length): row, col = list(), list() for j in range(length): row.append(sudoku[i][j]) col.append(sudoku[j][i]) if len(set(row)) != 9 or len(set(col)) != 9: return "NO" # 3x3 격자판 검사 a.extend(row[0:3]) b.extend(row[3:6]) c.extend(row[6:]) if i == 2 or i == 5 or i == 8: if len(set(a)) != 9 or len(set(b)) != 9 or len(set(c)) != 9: return "NO" a, b, c, = list(), list(), list() return "YES" print(solution(sudoku))

  • python
  • 코딩-테스트
  • 코테 준비 같이 해요!
HTCho1 댓글 1 좋아요 0 조회수 461

1068번: 트리

미해결

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

제가 다음과 같이 코드를 작성했는데, 100%까지 가다가 틀립니다.. 어떤게 문제일까요? 반례를 제시해주실 수 있나요? 감사합니다. https://www.acmicpc.net/problem/1068 import sys input = sys.stdin.readline n = int(input()) g = list(map(int, input().split())) m = int(input()) cnt = 0 def DFS(x): g[x] = -1 for i in range(n): if g[i] == x: DFS(i) DFS(m) for i in range(n): if g[i] != -1 and i not in g: cnt += 1 print(cnt)

  • python
  • 코딩-테스트
  • 코테 준비 같이 해요!
이도열 댓글 1 좋아요 1 조회수 376

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

해결됨

스프링 시큐리티

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

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

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

미해결

스프링과 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

안녕하세요 리뷰복습하다가, 발견했습니다

미해결

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

최근에 다시 자바스크립트로 돌리면서, 기존에 파이썬으로 했던 것들 다시 모두 자바스크립트로 풀어보면서 문제 풀어보니, 발견했습니다. 이거 첫번째 가정을, 그리디로 접근하면 해결 안되는 문제인것같습니다. 이후 가정들은 당연히 그리디 관념으로 최적값 찾을 수 있는데, 첫번째 가정부터 그리디로 접근하면 해결되는 문제가 아니라서 어긋나기때문에, 그리디관념이 통하지 않는 문제인것같습니다. 완전탐색해버리거나, 시간 더 줄이려면 백트래킹 가지치기 해야하는 문제인것같습니다. 입력입니다! 7 172 67 183 65 179 61 178 62 177 63 170 72 181 60 기존 풀이(무조건 183선발) 가 내주는 답 : 3 감독 현수가 원할 것 같은 답 : 6 그리디로 가장 키 큰 사람 무조건 선발하는 과정이 풀이에서 오류인것같습니다. 183 선발 가정하고 cnt 값 구하고, 그다음 181 선발 가정하고 cnt값 구하고, 쭉 다음 순으로 선발 가정하고 cnt값 구하는데, 만약 어떤 사람 선발 가정하고 cnt값 구하는데 남은 사람 수 다 합해도 기존 Max cnt보다 적을 경우, 백트레킹 가지치기로 break 혹은 return 끊어버리는게 맞는것같습니다. 풀이1. 이중포문 const input = require("fs") .readFileSync("input.txt") .toString() .trim() .split("\n"); const n = parseInt(input[0]); const arr = Array.from(Array(5), () => []); for (let i = 0; i < n; i++) { arr[i] = Array.from(input[i + 1].trim().split(" ")).map((v) => parseInt(v)); } function solution(n, arr) { arr.sort((a, b) => b[0] - a[0]); let cnt = 0; let largest = 0; let res = 0; for (let i = 0; i < n; i++) { largest = arr[i][1]; cnt += 1; if (res >= n - i) { break; } for (let j = i + 1; j < n; j++) { if (arr[j][1] > largest) { largest = arr[j][1]; cnt += 1; } } res = Math.max(res, cnt); cnt = 0; } console.log(res); } solution(n, arr); 풀이2. DFS const input = require("fs") .readFileSync("input.txt") .toString() .trim() .split("\n"); const n = parseInt(input[0]); const arr = Array.from(Array(5), () => []); for (let i = 0; i < n; i++) { arr[i] = Array.from(input[i + 1].trim().split(" ")).map((v) => parseInt(v)); } let cnt = 0; let res = 0; //const list = []; function DFS(s, weight) { if (s < 0) return; if (cnt + n - s <= res) { cnt -= 1; s -= 1; return; } for (let i = s; i < n; i++) { if (arr[i][1] > weight) { cnt += 1; //list.push(arr[i][1]); DFS(i + 1, arr[i][1]); //list.pop(); } } res = Math.max(res, cnt); //console.log(list); cnt -= 1; } function solution(n, arr) { arr.sort((a, b) => b[0] - a[0]); DFS(0, 0); console.log(res); } solution(n, arr);

  • 코딩-테스트
  • python
  • 코테 준비 같이 해요!
ncprog1 댓글 2 좋아요 1 조회수 455

인기 태그

인프런 TOP Writers

주간 인기글