首页 > 解决方案 > 'DELETE'、'PUT' 和 |'GET' item by id| 中不支持 Spring-boot

问题描述

我正在 Spring-boot 架构的帮助下使用 RESTful Web 服务测试一个简单的后端。现在我已经完成了后端,但我无法访问DELETE,PUTGET方法get item by id(The other http methods work - GET alland POST)

用户控制器类

package com.pali.palindromebackend.api;

import com.pali.palindromebackend.business.custom.UserBO;
import com.pali.palindromebackend.business.util.EntityDTOMapper;
import com.pali.palindromebackend.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.sql.SQLException;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    @Autowired
    private UserBO bo;

    @Autowired
    private EntityDTOMapper mapper;

    public UserController() throws SQLException{

    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseEntity<List<UserDTO>> getAllUsers() throws Exception {
        System.out.println("get");
        return new ResponseEntity<List<UserDTO>>(bo.getAllUsers(), HttpStatus.OK);
    }

    @GetMapping(value = "/{userId}", produces = MediaType.APPLICATION_JSON_VALUE )
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseEntity<Object> getUserById(@PathVariable Integer userId) throws Exception {
        System.out.println("One");
        try {
            return new ResponseEntity<>(bo.getUser(userId), HttpStatus.OK);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>("No user found !!", HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            return new ResponseEntity<>("Something went wrong !!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping(
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE
    )
    @ResponseBody
    public ResponseEntity<Object> saveUser(@Valid @RequestBody UserDTO dto) throws Exception {
        System.out.println(mapper.getUser(dto));
        try {
            bo.saveUser(dto);
            return new ResponseEntity<>(dto, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    @DeleteMapping("/{userId}")
    public ResponseEntity<Object> deleteUser(@PathVariable Integer userId) throws Exception {
        try {
            bo.getUser(userId);
            bo.deleteUser(userId);
            return new ResponseEntity<>("Successfully deleted the user !!", HttpStatus.CREATED);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>("No user is found !!", HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            return new ResponseEntity<>("Something went wrong!!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping(
            value = "/{userId}",
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE
    )
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseEntity<Object> updateUser(@Valid @RequestBody UserDTO dto, @PathVariable Integer userId)
            throws Exception {
        if (dto.getId() != userId) {
            return new ResponseEntity<>("Mismatch userId !!", HttpStatus.BAD_REQUEST);
        }
        try {
            bo.getUser(userId);
            bo.updateUser(dto);
            return new ResponseEntity<>(dto, HttpStatus.CREATED);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>("No user is found !!", HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            return new ResponseEntity<>("Something went wrong !!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

AppInitializer 类

import com.pali.palindromebackend.util.LogConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PalindromeBackendApplication {

    public static void main(String[] args) {
        LogConfig.initLogging();
        SpringApplication.run(PalindromeBackendApplication.class, args);
    }

}

安全配置

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Autowired
    private JWTRequestFilter jwtRequestFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/api/v1/authenticate").permitAll()
                .antMatchers("/api/v1/users").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

MyUserDetailsS​​ervice

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return new User("admin","admin",new ArrayList<>());
    }
}

JWTRequestFilter

@Component
public class JWTRequestFilter extends OncePerRequestFilter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private JWTUtil jwtUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        final String authorizationHeader = req.getHeader("Authorization");

        String userName = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer")){
            jwt = authorizationHeader.substring(7);
            userName = jwtUtil.extractUsername(jwt);
        }
        if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null){
            UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(userName);
            if(jwtUtil.validateToken(jwt,userDetails)){
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()
                );
                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(req,res);
    }
}

CORS 过滤器

import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTION");
        response.setHeader("Access-Control-Allow-Headers", "Content-type,Authorization");
        super.doFilter(request, response, chain);
    }
}

我发送了GET http://localhost:8080/api/v1/users and POST http://localhost:8080/api/v1/users headers with{'name':'Charls','password':'asd123'}`(JSON 类型)并且这些都有效。

但是GET http://localhost:8080/api/v1/courses/3- 通过 id 获取 Item ,DELETE localhost:8080/api/v1/users/3并且PUT localhost:8080/api/v1/users/3使用JSON head {"name": "Samwise Gamgee", "duration": "ring bearer"} -user update.Those 方法不起作用:(

2021-05-20 12:55:01.798  WARN 15187 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound             : Request method 'PUT' not supported
2021-05-20 12:55:32.746  WARN 15187 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound             : Request method 'DELETE' not supported

在这里,当我生成请求时,甚至任何方法(PUT、DELETE、GET item by id)都不起作用。所以问题也不例外:(

标签: javaspringspring-bootrestspring-data-jpa

解决方案


您需要为它们设置允许的方法。您可以为此添加一个 bean。

    @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
        }
    };
}

注意:这是允许所有来源的代码。您需要根据需要进行配置。


推荐阅读