鍍金池/ 問答/Java  Linux  數(shù)據(jù)庫/ HTTP method POST is not supported by thi

HTTP method POST is not supported by this URL 報(bào)錯(cuò)信息

一般的form表單提交方式要么是get要么是post,我打算自己在servlet里面寫自定義的函數(shù),比如login()函數(shù),而不去實(shí)現(xiàn)dopost和doget方法,這樣我form表單提交的時(shí)候加一個(gè)hidden參數(shù)method=login,于是運(yùn)行的時(shí)候就一直報(bào)405method not allowed的錯(cuò)誤,下面提示“HTTP method POST is not supported by this URL”
<form class="form-horizontal" method="post" action="${pageContext.request.contextPath }/user">
                        
                        <input type="hidden" name="method" value="login">
                        
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">用戶名</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" id="username" name="username"
                                    placeholder="請輸入用戶名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">密碼</label>
                            <div class="col-sm-6"> 
                                <input type="password" class="form-control" id="inputPassword3" name="password"
                                    placeholder="請輸入密碼">
                            </div>
                        </div>

jsp的表單代碼

回答
編輯回答
刮刮樂

你把 servlet 的 method 與 HTML form 的 method(即 HTTP method) 混淆了,它們并沒有直接的關(guān)系。
而且 HTML form 的 method 屬性值只能是 get 或 post。


要實(shí)現(xiàn)自定義 HTTP method "LOGIN",你要在 servlet 添加處理 HTTP LOGIN method 的邏輯,如

// 重寫 HttpServlet.service() 以支持自定義 HTTP method。
package demo;

import javax.servlet.http.HttpServlet;

class CustomHttpServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        if (req.getMethod().toLowerCase() == "login") {
            this.doLogin(req, res);
            return;
        }
        super.service(req, resp);
    }

    protected void doLogin(HttpServletRequest req, HttpServletResponse resp) {
        // 與 doGet() 類似,在此處添加處理邏輯。
    }
}

這時(shí)不能使用 HTML form 測試,應(yīng)該使用接口測試工具,發(fā)送類似下面的請求

LOGIN  http://127.0.0.1:8080/xxx

譬如

curl -X LOGIN  http://127.0.0.1:8080/xxx
2018年4月8日 03:29
編輯回答
拽很帥

雖然你的想法是對的……但是HTTP設(shè)計(jì)出來就只支持這幾種方法,如果你想用自定義的邏輯去處理的話,首先要用servlet的方法獲得post的數(shù)據(jù)然后轉(zhuǎn)發(fā)給自定義的處理模塊。

2017年2月20日 23:22