0
点赞
收藏
分享

微信扫一扫

JavaWeb—HTTP状态 405 - 方法不允许【BUG已解决】

@[toc]

一.遇到的问题

这是一个JavaWeb工程,写了请求表单之后报了HTTP状态 405 - 方法不允许。此URL不支持Http方法POST。如下图:
在这里插入图片描述
我目前是写了应该表单,是使用了post方法,get可以正常请求,post就会405。
我的前端代码如下,没有错误:

    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name="password"> <br>
        我是:
        <input type="checkbox" name="yu" value="上进小菜猪"> 上进小菜猪
        <input type="checkbox" name="yu" value="菜猪"> 菜猪
        <input type="checkbox" name="yu" value="小菜"> 小菜
        <input type="checkbox" name="yu" value="小猪"> 小猪
        <br>
        <input type="submit">
    </form>

错误在后端,请看下文。

二.此URL不支持Http方法POST【解决方法】

后端我继承了HttpServlet,重写了doGet。如下

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String user = req.getParameter("username");
        String pass = req.getParameter("password");
        String[] yus = req.getParameterValues("yu");
        System.out.println("---------------------");
        System.out.println(user);
        System.out.println(pass);
        System.out.println(Arrays.toString(yus));
        System.out.println("---------------------");
        req.getRequestDispatcher("/sussess.jsp").forward(req,resp);

    }

为了解决这个HTTP状态 405 - 方法不允许的bug,我们需要重写一下doPost方法:
让doPost直接指向doGet,即可解决这个问题。
代码如下:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

在这里插入图片描述
HTTP状态 405 - 方法不允许/此URL不支持Http方法POST——BUG已解决。

举报

相关推荐

0 条评论