Java 在';删除'';把';和|';获取';按id列出的项目|
我正在测试一个简单的后端,在SpringBoot架构的帮助下使用RESTfulWeb服务。现在我已经完成了后端,但是我无法使用Java 在';删除'';把';和|';获取';按id列出的项目|,java,spring,spring-boot,rest,spring-data-jpa,Java,Spring,Spring Boot,Rest,Spring Data Jpa,我正在测试一个简单的后端,在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.palindr
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);
}
}
SecurityConfig
@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();
}
}
MyUserDetailsService
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return new User("admin","admin",new ArrayList<>());
}
}
CORS过滤器
@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);
}
}
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”}-用户更新
。这些方法不起作用:(
在这里,当我生成请求时,甚至任何方法(PUT、DELETE、GET item by id)都不起作用。因此问题不是例外:(您需要为它们设置允许的方法。您可以为此添加一个bean
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
注意:这是所有源代码都允许的代码。您需要根据需要进行配置。如下更改控制器方法
@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);
}
}
}
@GetMapping(value=“/{userId}”,
products=MediaType.APPLICATION\u JSON\u值)
@ResponseStatus(HttpStatus.OK)
@应答器
公共响应getUserById(@PathVariable(“userId”)Integer userId)引发异常{
系统输出打印项次(“一”);
试一试{
返回新的响应属性(bo.getUser(userId),HttpStatus.OK);
}捕获(无接触元素例外e){
返回新的响应属性(“未找到用户!!”,HttpStatus.NOT\u found);
}捕获(例外e){
返回新的ResponseEntity(“出错了!!”,HttpStatus.INTERNAL\u SERVER\u ERROR);
}
}
@ResponseStatus(HttpStatus.CREATED)
@应答器
@DeleteMapping(“/{userId}”)
public ResponseEntity deleteUser(@PathVariable(“userId”)Integer userId)引发异常{
试一试{
getUser(userId);
删除用户(userId);
返回新的响应属性(“已成功删除用户!!”,HttpStatus.CREATED);
}捕获(无接触元素例外e){
返回新的响应属性(“未找到用户!!”,HttpStatus.NOT\u found);
}捕获(例外e){
返回新的ResponseEntity(“出错了!!”,HttpStatus.INTERNAL\u SERVER\u ERROR);
}
}
@PutMapping(
value=“/{userId}”,
products=MediaType.APPLICATION\u JSON\u值,
消费=MediaType.APPLICATION\u JSON\u值
)
@ResponseStatus(HttpStatus.OK)
@应答器
public ResponseEntity updateUser(@Valid@RequestBody UserDTO dto,@PathVariable(“userId”)Integer userId)
抛出异常{
if(dto.getId()!=userId){
返回新的响应属性(“不匹配的用户ID!!”,HttpStatus.BAD\u请求);
}
试一试{
getUser(userId);
更新用户(dto);
返回新的响应属性(dto、HttpStatus.CREATED);
}捕获(无接触元素例外e){
返回新的响应属性(“未找到用户!!”,HttpStatus.NOT\u found);
}捕获(例外e){
返回新的ResponseEntity(“出错了!!”,HttpStatus.INTERNAL\u SERVER\u ERROR);
}
}
}
如果仍然无法调用GET、PUT、DELETE方法,请检查您的业务逻辑是的,感谢所有回答我问题的人,我找到了问题的根源:/
- 在SecurityConfig中,我只允许以/api/v1/authenticate和/api/v1/users结尾的请求
- 因此,我无法传递类似于localhost:8080/api/v1/users/3的删除请求,因为它包含的“/3”多于“/api/v1/users”;SecurityConfig会阻止它。
- 我的prob就是这样(不允许访问安全过滤器来传递这些请求)
- 如果我们想获得访问权来传递这些请求,我们应该在securityConfig中提到相关路径
@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);
}
}
}
@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);
}