2017-09-19 52 views
0

我得到這個index.html的表單按鈕無能爲力

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <meta charset="ISO-8859-1"> 
    <title>Store</title> 
</head> 
<body> 
    <form action="#" th:action="@{/redirectToAddProd}" method="post"> 
     <input type="submit" value="Submit" /> 
    </form> 
</body> 
</html> 

而且我得到了這個StoreController.java

@Controller 
@RequestMapping("/") 
public class StoreController { 
    @GetMapping("/") 
    public String index() { 
     return "index"; 
    } 

    @GetMapping("/addProduct") 
    public String addProduct() { 
     return "addProduct"; 
    } 

    @PostMapping("/redirectToAddProd") 
    public String redirectToAddProd() { 
     return "redirect:/addProduct"; 
    } 
} 

我的問題是,當我按下提交按鈕沒有任何反應(真的沒什麼)沒有得到請求,甚至沒有404。你有解決方案嗎? 謝謝

編輯: 我的web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> 
<display-name>MyStore</display-name> 

    <servlet> 
     <servlet-name>store</servlet-name> 
     <servlet-class> 
      org.springframework.web.servlet.DispatcherServlet 
     </servlet-class> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>/WEB-INF/store-servlet.xml</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>store</servlet-name> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 

</web-app> 

編輯:現在,我得到一個新的錯誤。現在的按鈕做一些事情,但給我的錯誤:

sept. 20, 2017 10:08:30 AM org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported 
AVERTISSEMENT: Request method 'POST' not supported 

回答

1

Your form should have a method of POST, not GET.

<form action="#" th:action="@{/redirectToAddProd}" method="post">

而且您的控制器必須要進行註釋處理POST請求,但是您認爲合適的:

@PostMapping("/redirectToAddProd") 
public String redirectToAddProd() { 
    return "redirect:/addProduct"; 
} 

最後,您可以從控制器的頂部刪除@RequestMapping("/"),因爲它是冗餘的並使用@GetMapping而不是代碼中的較長表單。

,您可以啓用像這些類的調試日誌記錄,以幫助您診斷路由問題:

<logger name="org.springframework.web.servlet.handler.AbstractUrlHandlerMapping" level="DEBUG" /> <logger name="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" level="DEBUG" />

+0

你好@bphilipnyc抱歉,但我不知道在哪裏使用註釋GetMapping。我做了所有其他更改,你問我,但現在我有這個錯誤信息:不支持請求方法'POST'感謝您的答案 –

+0

sept。 20,2017 9:48:06 AM org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported AVERTISSEMENT:不支持請求方法'POST' –

+0

哦,我明白你在說的GetMapping。感謝您的提示。 –