我的Spring Boot应用程序中出现异常PageNotFound: Request method 'POST' not supported
。
这是我的控制者:
@RestController
public class LoginController {
UserWrapper userWrapper = new UserWrapper();
@RequestMapping(value = "/api/login", method = RequestMethod.POST, headers = "Content-type: application/*")
public @ResponseBody ResponseEntity getCredentials(@RequestBody UserDTO userDTO) {
User user = userWrapper.wrapUser(userDTO);
if (userDTO.getPassword().equals(user.getPassword())) {
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
我在localhost:8080/api/login
发送邮件请求,但它不起作用。你有什么想法吗?
修改
UserDTO:
public class UserDTO implements Serializable {
private String email;
private String password;
//getters and setters
我和json发送:
{
"email":"email@email.com",
"password":"password"
}
答案 0 :(得分:9)
我通过禁用CSRF解决了这个问题。
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
答案 1 :(得分:3)
我解决了我的问题。我从RequestMapping中删除了标题,并为@Autowired
添加了UserWrapper
注释,现在一切正常。
答案 2 :(得分:0)
如果您使用的是JPA,则会出现此问题。 Spring引导存储库内置了所有请求。因此您的请求必须匹配存储库请求这是我发现的唯一具有可用Spring Boot POST的示例 https://dzone.com/articles/crud-using-spring-data-rest 关键是您必须匹配存储库休息调用
您的存储库Iterface看起来像这样加上任何覆盖没有impl类
public interface UseerRepository extends CrudRepository<User, Integer>{
}
您的控制器将如下所示。请注意请求值 / users 它是末尾带有S的实体名称
@RestController
public class LoginController {
@RequestMapping("/api/login")//this will return the login page
public String home() {
return "login";
}
UserWrapper userWrapper = new UserWrapper();
//this will do the post
@RequestMapping(value = "/users", method = RequestMethod.POST, headers = "Content-type: application/*")
public @ResponseBody ResponseEntity getCredentials(@RequestBody UserDTO userDTO) {
User user = userWrapper.wrapUser(userDTO);
if (userDTO.getPassword().equals(user.getPassword())) {
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
您的应用程序配置文件应如下所示通知@ComponentScan no basepackage = {“com”}如果您这样做,那么您的JPA无法正常工作
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
@Configuration
@ComponentScan
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
@PropertySource("application.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如果要覆盖存储库POST请求在控制器或服务类中执行,我希望我解释得很好,但该示例确实有效,您不必再编写大量原始代码了