我是一名有用的助手,可以为您翻译文本。
我有一个简单的REST API,与数据库配合使用。在添加了安全性部分之前,它能够正常工作。现在在POST和DELETE请求时会返回HTTP 405 Not Allowed错误。我不知道原因。GET请求可以正常工作。
以下是控制器类:
@Controller
public class MarkerController {
private Logger logger = Logger.getLogger(MarkerController.class.getName());
@Autowired
private MarkerServiceInterface markerService;
@RequestMapping(value="/markers", method=RequestMethod.GET)
public @ResponseBody List<Marker> getMarkers(@RequestParam(value="city", defaultValue="") String city) {
logger.info("HANDLE GET REQUEST");
return this.markerService.getAllMarkers();
}
@RequestMapping(value="/markers/new", method=RequestMethod.POST)
public @ResponseBody Marker addMarker(@RequestBody Marker marker) {
logger.info("HANDLE POST REQUEST");
this.markerService.addMarker(marker);
return marker;
}
@RequestMapping(value="/markers/delete", method=RequestMethod.DELETE)
public @ResponseBody String deleteMarker(@RequestParam(value="id", defaultValue="") String id) {
logger.info("HANDLE DELETE REQUEST");
if (!id.equals("")) {
logger.info(id);
this.markerService.deleteMarker(Long.parseLong(id));
}
return "";
}
@RequestMapping(value="/admin/map")
public String trafficSpy() {
logger.info("HANDLE MAP");
return "index";
}
@RequestMapping(value="/admin")
public String admin() {
return "admin";
}
@RequestMapping(value="/login")
public String login() {
return "login";
}
}
This is the SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(
passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**")
.access("hasRole('ROLE_ADMIN')")
.antMatchers("/markers/**")
.access("hasRole('ROLE_USER')")
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.and()
.csrf()
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
}
DELETE请求是通过以下ajax代码调用的:
$.ajax({
url: "localhost:8080/markers/delete?id=" + currentMarker.get("id"),
type: 'DELETE',
success: function(result) {
console.log(result);
}
});
这是控制台中显示的消息:
2015-05-11 15:48:13.671 WARN 8279 --- [nio-8181-exec-6] o.s.web.servlet.PageNotFound : Request method 'DELETE' not supported
这些是响应的头部信息。我可以看到在ALLOW中只有GET和HEAD。如果我没错的话,这意味着控制器中的方法仅接受GET和HEAD请求。
(Status-Line) HTTP/1.1 405 Method Not Allowed
Server Apache-Coyote/1.1
x-content-type-options nosniff
x-xss-protection 1; mode=block
Cache-Control no-cache, no-store, max-age=0, must-revalidate
Pragma no-cache
Expires 0
X-Frame-Options DENY
Allow GET, HEAD
Content-Type application/json;charset=UTF-8
Transfer-Encoding chunked
Date Mon, 11 May 2015 17:35:31 GMT
在响应中,我遇到了这个异常:
org.springframework.web.HttpRequestMethodNotSupportedException
有什么想法是什么原因导致这个问题?我该如何允许POST和DELETE方法?
POST
和DELETE
就会成功吗? - Dirk Lachowskicsrf
令牌。请您检查一下错误信息是否有相关提示。 - Manu Zi