postman 为什么返回http 200 ok代替响应实体中创建的201?

9vw9lbht  于 2023-10-18  发布在  Postman
关注(0)|答案(1)|浏览(192)

当用Postman测试项目时,任何post方法,我收到的是200 ok而不是201 created,Subreddit不是在数据库中创建的,而是在控制台Hibernate中收到的:从t1_0中选择t1_0.id、t1_0.expired、t1_0.revocated、t1_0.token、t1_0.token_type、t1_0.user_id,其中t1_0.token=?休眠:选择u1_0.userid,u1_0.created,u1_0.email,u1_0.enabled,u1_0.password,u1_0.user_name from _user u1_0 where u1_0.userid=?
this is my code

package com.example.redditback.Controller;

import com.example.redditback.Dto.SubRedditDto;
import com.example.redditback.Service.SubRedditService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/subreddit")
@AllArgsConstructor
public class SubRedditController {
    private final SubRedditService subredditService;
    @GetMapping("/all")
    public ResponseEntity<List<SubRedditDto>> getAllSubreddits() {
        List<SubRedditDto> subRedditDtos=subredditService.getAll();
        return new ResponseEntity<>(subRedditDtos,HttpStatus.OK);
    }
    @GetMapping("/findbyid/{id}")
    public ResponseEntity<SubRedditDto> getSubreddit(@PathVariable("id") Long id) {
        SubRedditDto subRedditDto=subredditService.getSubreddit(id);
        return new ResponseEntity<>(subRedditDto,HttpStatus.OK);
    }
    @PostMapping("/add")
    public ResponseEntity<SubRedditDto> create(@RequestBody SubRedditDto subRedditDto){
        SubRedditDto subRedditDto1=subredditService.save(subRedditDto);
        return new ResponseEntity<>(subRedditDto1,HttpStatus.CREATED);
    }
}
package com.example.redditback.Dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SubRedditDto {
    private Long id;
    private String name;
    private String description;
    private Integer postCount;
}
package com.example.redditback.Repository;

import com.example.redditback.Entity.SubReddit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface SubRedditRepository extends JpaRepository<SubReddit,Long> {

    Optional<SubReddit> findByName(String subRedditName);
    Optional<SubReddit> findById(Long id);
}
package com.example.redditback.Service;

import com.example.redditback.Authentification.AuthenticationService;
import com.example.redditback.Dto.SubRedditDto;
import com.example.redditback.Entity.SubReddit;
import com.example.redditback.Exeption.SubRedditNotFoundExeption;
import com.example.redditback.Repository.SubRedditRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.time.Instant.now;
import static java.util.stream.Collectors.toList;

@Service
@AllArgsConstructor
@Component
public class SubRedditService {
    private final SubRedditRepository subredditRepository;
    private final AuthenticationService authenticationService;

    @Transactional(readOnly = true)
    public List<SubRed`
ditDto> getAll() {
        return subredditRepository.findAll()
                .stream()
                .map(this::mapToDto)
                .collect(toList());
    }

    @Transactional
    public SubRedditDto save(SubRedditDto subRedditDto) {
        SubReddit subreddit = subredditRepository.save(mapToSubreddit(subRedditDto));
        subRedditDto.setId(subreddit.getId());
        return subRedditDto;
    }

    @Transactional(readOnly = true)
    public SubRedditDto getSubreddit(Long id) {
        SubReddit subreddit = subredditRepository.findById(id)
                .orElseThrow(() -> new SubRedditNotFoundExeption("Subreddit not found with id -" + id));
        return mapToDto(subreddit);
    }

    private SubRedditDto mapToDto(SubReddit subreddit) {
        return SubRedditDto.builder()
                .name(subreddit.getName())
                .description(subreddit.getDescription())
                .id(subreddit.getId())
                .postCount(subreddit.getPosts().size())
                .build();
    }

    private SubReddit mapToSubreddit(SubRedditDto subredditDto) {
        return SubReddit.builder().name("/r/" + subredditDto.getName())
                .description(subredditDto.getDescription())
                .user(authenticationService.getCurrentUser())
                .createdDate(now()).build();
    }
}

这是我的身份证明

package com.example.redditback.Configuration;

import com.example.redditback.Token.TokenRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtService jwtService;
    private final TokenRepository tokenRepository;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String userEmail;
        if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        jwt = authHeader.substring(7);
        userEmail = jwtService.extractUsername(jwt);
        if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
            var isTokenValid=tokenRepository.findByToken(jwt)
                    .map(t -> !t.getExpired() && !t.getRevoked())
                    .orElse(false);
            if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        null,
                        userDetails.getAuthorities()
                );
                authToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request)
                );
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
    }
}
package com.example.redditback.Configuration;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration{
        private final JwtAuthenticationFilter jwtAuthFilter;
        private final AuthenticationProvider authenticationProvider;
        private final LogoutHandler logoutHandler;

        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                    .csrf()
                    .disable()
                    .authorizeHttpRequests()
                    .requestMatchers("/Auth/**")
                    .permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authenticationProvider(authenticationProvider)
                    .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                    .cors()
                    .and()
                    .logout()
                    .logoutUrl("/lougout")
                    .addLogoutHandler(logoutHandler)
                    .logoutSuccessHandler((request, response, authentication) ->
                                    SecurityContextHolder.clearContext()
                            );

            return http.build();
        }
}
vd8tlhqk

vd8tlhqk1#

试试这个方法:

@PostMapping("/add")
public ResponseEntity<SubRedditDto> create(@RequestBody SubRedditDto subRedditDto){
    SubRedditDto subRedditDto1=subredditService.save(subRedditDto);
    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(subRedditDto1.getId())
            .toUri();
    return ResponseEntity.created(uri).body(subRedditDto1);
}

相关问题