gpt4 book ai didi

why return http 200 ok in place a 201 created in Response Entity?(为什么返回Http 200 OK,在响应实体中创建一个201?)

转载 作者:bug小助手 更新时间:2023-10-24 21:20:50 27 4
gpt4 key购买 nike



When testing the project with Postman, any post method, I receive 200 ok instead of 201 created, and Subreddit is not created in the database, and received this in the console
Hibernate:
select
t1_0.id,
t1_0.expired,
t1_0.revoked,
t1_0.token,
t1_0.token_type,
t1_0.user_id
from
token t1_0
where
t1_0.token=?
Hibernate:
select
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=?

当使用Postman测试项目时,任何POST方法,我收到的是200 OK而不是201 Created,并且subreddit不是在数据库中创建的,并且在控制台休眠中接收到以下内容:SELECT T1_0.id、T1_0.EXPIRED、T1_0.REVOKED、T1_0.TOKEN、T1_0.TOKEN_TYPE、T1_0.USER_ID FROM T1_0 WHERE T1_0.Token=?休眠:选择U1_0.userid、U1_0.Created、U1_0.mail、U1_0.Enable、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();
}
}

and this my authentification

这就是我的身份证明


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();
}
}


更多回答

Try adding a Location header to your response entity.

尝试向您的响应实体添加Location标头。

you do know that your logout wont work, so you know

您知道您的注销不会起作用,所以您知道

优秀答案推荐

Try this way:

尝试这样做:


 @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);
}

更多回答

no it doesn't work same problem

不,它不起作用,同样的问题

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com