我正在尝试按照网络上的指南使用 Spring 安全保护我的网站。我不希望我的用户通过网络浏览器使用我的应用程序,所以我禁用了 csrf 保护。服务器端的源代码:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
implements ApplicationContextAware {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().authenticated().and()
.httpBasic().and()
.csrf().disable();
}
@Override
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
authManagerBuilder.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMI N");
}
}
@Controller
//@RequestMapping("/course")
public class CourseController implements ApplicationContextAware{
@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json")
public @ResponseBody List<Course> get(// The critirion used to find.
@RequestParam(value="what", required=true) String what,
@RequestParam(value="value", required=true) String value) {
//.....
}
@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public List<Course> upload(@RequestBody Course[] cs) {
}
}
我在客户端使用 RestTemplate。问题是当我使用 POST 方法时,我在服务器端收到警告:
o.s.web.servlet.PageNotFound:不支持请求方法“POST”
在客户端,我得到了:
线程“main” org.springframework.web.client.HttpClientErrorException 中的异常:405 Method Not Allowed
我收到这个异常很奇怪,因为我已经在 Controller 中处理了 POST 方法。目前,该系统仍然有效,但这个问题困扰着我。
任何的想法?
谢谢。
最佳答案
终于,我发现了哪里不对劲。希望这对其他人有帮助。
这个错误非常愚蠢。 upload() 的返回值应该使用@ResponseBody,因为我想直接返回类(class)。
@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public @ResponseBody List<Course> upload(@RequestBody Course[] cs) {
}
关于POST 方法的 Spring 405 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19512564/