我正在测试一个简单的后端,在SpringBoot架构的帮助下使用RESTfulWeb服务。现在我已经完成了后端,但是我无法使用GET item by id
访问DELETE
、PUT
和GET
方法(其他http方法工作-GET all
和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);
}
}
}
应用初始化器类
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();
}
}
MyUserDetails服务
@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);
}
}
我发送了GEThttp://localhost:8080/api/v1/users和
POSThttp://localhost:8080/api/v1/users带有
{'name':'Charls','password':'asd123'}`(JSON类型)的标题以及那些有效的标题。
但是GEThttp://localhost:8080/api/v1/courses/3
-按id获取项目,删除localhost:8080/api/v1/users/3
并将localhost:8080/api/v1/users/3
与JSON头{“name”:“Samwise Gamgee”,“duration”:“ring bearer”}-用户更新
。这些方法不起作用:(
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)都不起作用。因此,问题并非例外:(
是的,感谢所有回答我问题的人,我找到了问题的根源:/
@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);
}
按如下所示更改控制器方法
@GetMapping(value = "/{userId}",
produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<Object> getUserById(@PathVariable("userId") 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)
@ResponseBody
@DeleteMapping("/{userId}")
public ResponseEntity<Object> deleteUser(@PathVariable("userId") 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("userId") 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);
}
}
}
如果仍然不能调用GET, PUT, DELETE方法,请检查您的业务逻辑
您需要为它们设置允许的方法。您可以为此添加一个bean。
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
注意:这是允许所有起源的代码。您需要根据需要进行配置。
问题内容: 我正在工作一个内部Web应用程序。在IE10中,请求工作正常,但在Chrome中,所有AJAX请求(很多)都是使用OPTIONS发送的,而不是我提供的任何已定义方法。从技术上讲,我的要求是“跨域”。该站点位于localhost:6120上,我向AJAX发出请求的服务位于57124上。此关闭的jquery错误定义了该问题,但不是真正的解决方法。 如何在ajax请求中使用正确的http
我对Java服务器端编程还不熟悉,我的问题基本上是使用Servlets(低级别,不使用spring mvc等)开始一个起点,然后从node开始构建。js后台,其中路由定义将以函数(,等),函数将在http方法之一(GET、post、PUT、DELETE)的参数中接收和。 如果有人可以帮助我,从一个servlet类中的路由(比如说)开始定义方法,这个servlet类映射到http方法,同时在其参数中
好吧,这是我在Stackoverflow上的第一个问题,所以我希望,我正在解释我的问题足够好:-) 我正在使用Spring Data Rest MongoDB。我使用了一些“神奇”的方法,这些方法可以通过实现MongoRepository来获得,但是我也使用了自定义实现和RestController。让我给你看一些代码: 我的仓库看起来像这样: 现在,我的前端是由好的老AngularJS制作的,它
问题内容: 因此,我一直在浏览有关创建REST API的文章。其中一些建议使用所有类型的HTTP请求:like 。我们将创建例如 index.php 并以这种方式编写API: 好的,理所当然-我对Web服务还不太了解。但是,通过常规或(包含方法名称和所有参数)接受 JSON 对象,然后也以JSON进行响应,会不会更容易。我们可以轻松地通过PHP进行序列化/反序列化,并且无需处理不同的HTTP请求方
问题内容: 如何检测PHP中使用了哪种请求类型(GET,POST,PUT或DELETE)? 问题答案: 通过使用 例
问题内容: 我正在尝试在Spring MVC控制器(版本3.0.2)中使用和。在Spring控制器类中,有三种与URL映射的方法,如下所示(分别是PUT,GET和POST,仅用于演示目的)。 加载页面时,该方法将很明显地被调用,但是在所有其他情况下(提交页面时),唯一要调用POST的方法是,永远不会调用用指定的方法。 Spring表单仅包含一个提交按钮和一个图像浏览器, 生成的HTML如下, 在我