本文将分享SpringBoot405POST方法不受支持?的详细内容,并且还将对springboot报错不支持post进行详尽解释,此外,我们还将为大家带来关于AjaxPOST导致405(方法不允许)
本文将分享Spring Boot 405 POST方法不受支持?的详细内容,并且还将对springboot报错不支持post进行详尽解释,此外,我们还将为大家带来关于Ajax POST导致405(方法不允许) – Spring MVC、android-Spring Boot 415上的控制器不受支持的媒体类型、HTTP状态405-不支持请求方法“ POST”(Spring MVC)、HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'的相关知识,希望对你有所帮助。
本文目录一览:- Spring Boot 405 POST方法不受支持?(springboot报错不支持post)
- Ajax POST导致405(方法不允许) – Spring MVC
- android-Spring Boot 415上的控制器不受支持的媒体类型
- HTTP状态405-不支持请求方法“ POST”(Spring MVC)
- HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'
Spring Boot 405 POST方法不受支持?(springboot报错不支持post)
Spring Boot MVC如何不支持POST方法?我正在尝试实现一个简单的post方法,该方法接受实体列表:这是我的代码
@RestController(value="/backoffice/tags")public class TagsController { @RequestMapping(value = "/add", method = RequestMethod.POST) public void add(@RequestBody List<Tag> keywords) { tagsService.add(keywords); }}
像这样点击此网址:
http://localhost:8090/backoffice/tags/add
请求正文:
[{"tagName":"qweqwe"},{"tagName":"zxczxczx"}]
我收到:
{ "timestamp": 1441800482010, "status": 405, "error": "Method Not Allowed", "exception": "org.springframework.web.HttpRequestMethodNotSupportedException", "message": "Request method ''POST'' not supported", "path": "/backoffice/tags/add"}
编辑 :
调试Spring Web请求处理程序
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.checkRequest(request); protected final void checkRequest(HttpServletRequest request) throws ServletException { String method = request.getMethod(); if(this.supportedMethods != null && !this.supportedMethods.contains(method)) { throw new HttpRequestMethodNotSupportedException(method, StringUtils.toStringArray(this.supportedMethods)); } else if(this.requireSession && request.getSession(false) == null) { throw new HttpSessionRequiredException("Pre-existing session required but none found"); } }
仅有的两种方法supportedMethods
是{GET,HEAD}
答案1
小编典典RestController注释定义中存在错误。根据文档,它是:
公共@interface RestController {
/ 该值可能表明建议使用逻辑组件名称,如果自动检测到组件,则将其转换为Spring bean。 @返回建议的组件名称(如果有的话)
@自4.0.1开始* /字符串value()默认为“”;}
这意味着您输入的值(“ / backoffice / tags”)是控制器的名称,而不是其可用路径。
添加@RequestMapping("/backoffice/tags")
控制器的类,并从@RestController
注释中删除值。
编辑: 完全正常工作的示例,根据注释它不起作用-请尝试使用此代码-并从IDE本地运行。
build.gradle
buildscript { ext { springBootVersion = ''1.2.5.RELEASE'' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE") }}apply plugin: ''java''apply plugin: ''eclipse''apply plugin: ''idea''apply plugin: ''spring-boot'' apply plugin: ''io.spring.dependency-management''jar { baseName = ''demo'' version = ''0.0.1-SNAPSHOT''}sourceCompatibility = 1.8targetCompatibility = 1.8repositories { mavenCentral()}dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") }eclipse { classpath { containers.remove(''org.eclipse.jdt.launching.JRE_CONTAINER'') containers ''org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'' }}task wrapper(type: Wrapper) { gradleVersion = ''2.3''}
Tag.java
package demo;import com.fasterxml.jackson.annotation.JsonCreator;import com.fasterxml.jackson.annotation.JsonProperty;public class Tag { private final String tagName; @JsonCreator public Tag(@JsonProperty("tagName") String tagName) { this.tagName = tagName; } public String getTagName() { return tagName; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Tag{"); sb.append("tagName=''").append(tagName).append(''\''''); sb.append(''}''); return sb.toString(); }}
SampleController.java
package demo;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController@RequestMapping("/backoffice/tags")public class SampleController { @RequestMapping(value = "/add", method = RequestMethod.POST) public void add(@RequestBody List<Tag> tags) { System.out.println(tags); }}
DemoApplication.java
package demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
Ajax POST导致405(方法不允许) – Spring MVC
1.
经过一些研究后,我发现了一些答案,说明问题可能与csrf机制有关,所以我禁用它并仍然存在问题. (spring-security.xml bellow)
2.
我做了一个wireshark捕获来检查请求/响应.我的ajax请求没问题,我的控制器声明没问题,但我不明白为什么,405响应表明>允许:GET(捕获波纹管)
3.
我试图通过浏览器访问我的控制器操作(即发出GET请求),我收到错误HTTP状态405 – 不支持请求方法’GET’!
4.
我试图将RequestMapping(方法…)更改为RequestMethod.GET,并且请求到达控制器并且工作正常,但我不希望它在GET方法上工作,我想要一个POST请求.
5.
更改了RequestMapping(使用,生成,标题)以接受所有类型的数据,但仍然是405 …
这真让我抓狂!我发布我的文件,所以你可以检查它们,任何提示将不胜感激.谢谢! (重要说明:这是我的绝望配置)
弹簧security.xml文件
<beans:beans xmlns...(all needed declarations)> <http pattern="/js/**" security="none" /> <http pattern="/css/**" security="none" /> <!-- enable use-expressions --> <http auto-config="true" > <access-denied-handler error-page="/403" /> <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" /> <intercept-url pattern="/login" access="isAnonymous()" /> <intercept-url pattern="/403" access="permitAll" /> <intercept-url pattern="/**" access="hasRole('ROLE_USER')" /> <form-login login-page="/login" username-parameter="email" password-parameter="password" authentication-failure-url="/login?Failed" /> <!-- <csrf/> --> </http> ..... (authentication)
AdminController.java
@Controller @RequestMapping("/admin**") public class AdminController { ... (all my autowired beans) @RequestMapping( value = "/events/loadEvents",method = RequestMethod.POST,consumes = MediaType.ALL_VALUE,produces = MediaType.ALL_VALUE,headers = "Accept=*/*") @ResponseBody public Event loadEvents(@RequestParam("parentId") long parentId) { ... (my logic) return event; } }
请求(wireshark捕获)
响应(wireshark捕获)
编辑
jquery ajax调用代码
$.ajax({ type: 'POST',cache: false,url: /admin/events/loadEvents,data: { parentId: 1 },dataType = 'json',contentType = 'application/json',... });
解决方法
so I disabled it (csrf on spring-security.xml) and still have the issue.
不,我没有禁用它.我试图禁用它
<!-- <csrf/> -->
但我应该这样做:
<csrf disabled="true"/>
注释csrf标签不会禁用csrf,这是因为默认情况下启用了csrf!找到问题后很容易说这是一个愚蠢的错误,但是当我添加csrf标签来启用它时,我认为评论它会禁用它.在Spring Documentation找到答案
现在,回到我的问题.要使用CSRF ENABLED在POST AJAX调用中修复405错误消息,这非常简单.我将csrf参数保存在JS变量中,如下所示:
<script type="text/javascript"> var csrfParameter = '${_csrf.parameterName}'; var csrftoken = '${_csrf.token}'; </script>
然后我的ajax调用看起来像这样:
var jsonParams = {}; jsonParams['parentId'] = 1; jsonParams[csrfParameter] = csrftoken; $.ajax({ type: 'POST',data: jsonParams,... });
像魅力一样工作.希望将来帮助某人.
android-Spring Boot 415上的控制器不受支持的媒体类型
您好,我在Controller的Spring Boot上具有以下配置:
@RequestMapping(value = "/test/setgamesets", method = RequestMethod.POST,consumes="application/json")
public @ResponseBody Collection<GameSet> setGameSets(@RequestBody ArrayList<GameSet> gmsets) {
for(GameSet gs : gmsets){
System.out.println(""+gs.getId());
gamesets.save(gs);
}
return Lists.newArrayList(gamesets.findAll());
}
在我的Android应用程序中:
@POST("/test/setgamesets")
public Collection<GameSet> setGameSets(@Body ArrayList<GameSet> gmsets);
当我在Android应用程序中调用它时,出现此错误:
retrofit.RetrofitError: 415 Unsupported Media Type
您能给我提示在哪里找我的错吗?
感谢您的关注和时间;
Logcat:
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ ---> HTTP POST https://192.168.1.65:8443/test/setgamesets
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ Authorization: Bearer 1d5deb22-a470-4443-984f-3f877b05e372
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ Content-Type: application/json
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ Content-Length: 848
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ [{"explanation":"I dont kNow why this is wrong.","title4":"MovieD","question":"Choose one of the following, which is wrong.","title3":"MovieC","title2":"MovieB","title1":"MovieA","id":1,"rate":1.0,"rates":4,"wrong":1},{"explanation":"I dont kNow why this is wrong.","title4":"MovieD","question":"What is wrong with the follow movies.","title3":"MovieC","title2":"MovieB","title1":"MovieA","id":2,"rate":1.0,"rates":5,"wrong":2},{"explanation":"I dont kNow why this is wrong.","title4":"MovieD","question":"What is wrong with the follow movies.","title3":"MovieC","title2":"MovieB","title1":"MovieA","id":3,"rate":1.0,"rates":5,"wrong":3},{"explanation":"I dont kNow why this is wrong.","title4":"MovieD","question":"What is wrong with the follow movies.","title3":"MovieC","title2":"MovieB","title1":"MovieA","id":4,"rate":0.0,"rates":0,"wrong":4}]
11-17 08:43:12.283 8287-8734/com.testing.test D/Retrofit﹕ ---> END HTTP (848-byte body)
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ <--- HTTP 415 https://192.168.1.65:8443/test/setgamesets (177ms)
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Server: Apache-Coyote/1.1
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ X-Content-Type-Options: nosniff
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ X-XSS-Protection: 1; mode=block
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Cache-Control: no-cache, no-store, max-age=0, must-revalidate
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Pragma: no-cache
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Expires: 0
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Strict-Transport-Security: max-age=31536000 ; includeSubDomains
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ x-frame-options: DENY
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Set-Cookie: JSESSIONID=C97BD6EB007A558F69B0DA7A19615917; Path=/; Secure; HttpOnly
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ X-Application-Context: application
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Content-Type: application/schema+json
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ transfer-encoding: chunked
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ Date: Mon, 17 Nov 2014 06:43:12 GMT
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ {
"timestamp" : 1416206592255,
"error" : "Unsupported Media Type",
"status" : 415,
"message" : ""
}
11-17 08:43:12.463 8287-8734/com.testing.test D/Retrofit﹕ <--- END HTTP (112-byte body)
11-17 08:43:12.463 8287-8734/com.testing.test E/com.testing.test.CallableTask﹕ Error invoking callable in AsyncTask callable: com.testing.test.Game_Panel_score_Activity$1@41f20a18
retrofit.RetrofitError: 415 Unsupported Media Type
这是我的对象:
@Entity
public class GameSet {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String question;
private String title1;
private String title2;
private String title3;
private String title4;
private int wrong;
private String explanation;
private int rates;
private double rate;
public GameSet() {
}
public GameSet(String question,String title1, String title2, String title3, String title4,String explain, int wrong) {
super();
this.question = question;
this.title1 = title1;
this.title2 = title2;
this.title3 = title3;
this.title4 = title4;
this.explanation = explain;
this.wrong = wrong;
this.rate = 0;
this.rates = 0;
}
// Getters
public String getQuestion() {
return question;
}
public String getTitle1() {
return title1;
}
public String getTitle2() {
return title2;
}
public String getTitle3() {
return title3;
}
public String getTitle4() {
return title4;
}
public String getExplanation() {
return explanation;
}
public int getWrong() {
return wrong;
}
public int getRates() {
return rates;
}
public double getRate() {
return rate;
}
// Setters
public String setQuestion(String question) {
return this.question = question;
}
public void setTitle1(String title1) {
this.title1 = title1;
}
public void setTitle2(String title2) {
this.title1 = title2;
}
public void setTitle3(String title3) {
this.title1 = title3;
}
public void setTitle4(String title4) {
this.title1 = title4;
}
public void setExplanation(String explain) {
this.explanation = explain;
}
public void setWrong(int wrong) {
this.wrong = wrong;
}
public void setRate(double rate) {
this.rate = rate;
}
public void setRates(int rate) {
this.rate = rate;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
解决方法:
您的客户端应用程序应包含HTTP标头Content-Type:application / json以使其起作用.但是我不是android开发人员,所以不知道该怎么做.
HTTP状态405-不支持请求方法“ POST”(Spring MVC)
我收到此错误: HTTP Status 405 - Request method ''POST'' not supported
我正在尝试做的是创建一个带有下拉框的表单,该表单会根据在另一个下拉框中选择的其他值进行填充。例如,当我在customerName
框中选择一个名称时,onChange
应运行.jsp页面中的函数,然后提交提交的页面,然后在customerCountry
框中再次加载相应的值。
但是我收到此HTTP状态405错误。我在互联网上搜索了解决方案,但找不到任何有帮助的方法。这是我的代码的相关部分:
jsp页面的一部分
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style> .error { color: red; } </style> <script> function repopulate(){ document.deliveryForm.submit(); } function setFalse(){ document.getElementById("hasId").value ="false"; document.deliveryForm.submit(); // document.submitForm.submit(); (This was causing the error) } </script> </head> <body> <h1>Create New Delivery</h1> <c:url var="saveUrl" value="/test/delivery/add" /> <form:form modelAttribute="deliveryDtoAttribute" method="POST" action="${saveUrl}" name="deliveryForm"> <table> <tr> <td><form:hidden id="hasId" path="hasCustomerName" value="true"/></td> </tr> <tr> <td>Customer Name</td> <td><form:select path="customerName" onChange="repopulate()"> <form:option value="" label="--- Select ---" /> <form:options items="${customerNameList}" /> </form:select> </td> <td><form:errors path="customerName" css/></td> </tr> <tr> <td>Customer Country</td> <td><form:select path="customerCountry"> <form:option value="" label="--- Select ---" /> <form:options items="${customerCountryList}" /> </form:select> </td> <td><form:errors path="customerCountry" css/></td> </tr> </form:form> <form:form name="submitForm"> <input type="button" value="Save" onClick="setFalse()"/> </form:form> </body></html>
控制器的一部分:
@RequestMapping(value = "/add", method = RequestMethod.GET) public String getDelivery(ModelMap model) { DeliveryDto deliveryDto = new DeliveryDto(); model.addAttribute("deliveryDtoAttribute", deliveryDto); model.addAttribute("customerNameList", customerService.listAllCustomerNames()); model.addAttribute("customerCountryList", customerService .listAllCustomerCountries(deliveryDto.getCustomerName())); return "new-delivery"; } // I want to enter this method if hasId=true which means that a value in the CustomerName // drop down list was selected. This should set the CountryList to the corresponding values // from the database. I want this post method to be triggered by the onChange in the jsp page @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=true") public String postDelivery( @ModelAttribute("deliveryDtoAttribute") DeliveryDto deliveryDto, BindingResult result, ModelMap model) { model.addAttribute("deliveryDtoAttribute", deliveryDto); model.addAttribute("customerNameList", customerService.listAllCustomerNames()); model.addAttribute("customerCountryList", customerService .listAllCustomerCountries(deliveryDto.getCustomerName())); return "new-delivery"; } // This next post method should only be entered if the save button is hit in the jsp page @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=false") public String postDelivery2( @ModelAttribute("deliveryDtoAttribute") @Valid DeliveryDto deliveryDto, BindingResult result, ModelMap model) { if (result.hasErrors()) { model.addAttribute("deliveryDtoAttribute", deliveryDto); model.addAttribute("customerNameList", customerService.listAllCustomerNames()); model.addAttribute("customerCountryList", customerService .listAllCustomerCountries(deliveryDto.getCustomerName())); return "new-delivery"; } else { Delivery delivery = new Delivery(); //Setters to set delivery values return "redirect:/mis/home"; } }
我怎么会得到这个错误?任何帮助将非常感激!谢谢
编辑: 更改hasId
为hasCustomerName
。我仍然收到HTTP Status 405 - Request method''POST'' not supported
错误。
EDIT2: 注释掉setFalse
导致错误的函数中的行
// D
答案1
小编典典我发现了导致HTTP错误的问题。
在“ setFalse()
保存”按钮触发的函数中,我的代码试图提交包含该按钮的表单。
function setFalse(){ document.getElementById("hasId").value ="false"; document.deliveryForm.submit(); document.submitForm.submit();
当我删除document.submitForm.submit();
它的作品:
function setFalse(){ document.getElementById("hasId").value ="false"; document.deliveryForm.submit()
@RogerLindsjö感谢您发现我没有传递正确参数的错误!
HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'
我使用freemarker模板作为视图部分创建了一个Spring mvc应用程序。在此尝试使用表格添加模型。我也在使用spring security这是代码
员工
<fieldset> <legend>Add Employee</legend> <form name="employee" action="addEmployee" method="post"> Firstname: <input type="text" name="name" /> <br/> Employee Code: <input type="text" name="employeeCode" /> <br/> <input type="submit" value=" Save " /> </form>
employeeController.java
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String addEmployee(@ModelAttribute("employee") Employee employee) { employeeService.add(employee); return "employee"; }
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!-- Spring MVC --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/appServlet/servlet-context.xml, /WEB-INF/spring/springsecurity-servlet.xml </param-value> </context-param> <!-- Spring Security --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"> <http security="none" pattern="/resources/**"/> <!-- enable use-expressions --> <http auto-config="true" use-expressions="true"> <intercept-url pattern="/login" access="isAnonymous()"/> <intercept-url pattern="/**" access="hasRole(''ROLE_ADMIN'')" /> <!-- access denied page --> <access-denied-handler error-page="/403" /> <form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password" /> <logout logout-success-url="/login?logout" /> <!-- enable csrf protection --> <csrf /> </http> <authentication-manager> <authentication-provider user-service-ref="userDetailsService" > <password-encoder hash="bcrypt" /> </authentication-provider> </authentication-manager></beans:beans>
单击提交按钮时,将返回错误`
HTTP状态405-不支持请求方法“ POST”
`我在ftl和controller上都给出了POST方法。那为什么会这样呢?
答案1
小编典典我不确定这是否有帮助,但是我遇到了同样的问题。
您正在使用带有CSRF保护的springSecurityFilterChain。这意味着通过POST请求发送表单时必须发送令牌。尝试将下一个输入添加到表单中:
<input type="hidden"name="${_csrf.parameterName}"value="${_csrf.token}"/>
关于Spring Boot 405 POST方法不受支持?和springboot报错不支持post的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Ajax POST导致405(方法不允许) – Spring MVC、android-Spring Boot 415上的控制器不受支持的媒体类型、HTTP状态405-不支持请求方法“ POST”(Spring MVC)、HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'等相关知识的信息别忘了在本站进行查找喔。
本文标签: