HTTP method POST is not supported by this URL 报错信息

一般的form表单提交方式要么是get要么是post,我打算自己在servlet里面写自定义的函数,比如login()函数,而不去实现dopost和doget方法,这样我form表单提交的时候加一个hidden参数method=login,于是运行的时候就一直报405method not allowed的错误,下面提示“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的表单代码

阅读 3.3k
2 个回答

你把 servlet 的 method 与 HTML form 的 method(即 HTTP method) 混淆了,它们并没有直接的关系。
而且 HTML form 的 method 属性值只能是 get 或 post。


要实现自定义 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() 类似,在此处添加处理逻辑。
    }
}

这时不能使用 HTML form 测试,应该使用接口测试工具,发送类似下面的请求

LOGIN  http://127.0.0.1:8080/xxx

譬如

curl -X LOGIN  http://127.0.0.1:8080/xxx

虽然你的想法是对的……但是HTTP设计出来就只支持这几种方法,如果你想用自定义的逻辑去处理的话,首先要用servlet的方法获得post的数据然后转发给自定义的处理模块。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题