lord-ivan lord-ivan - 3 months ago 14
Java Question

why HTTP method POST is not supported by this URL

i am learning Java EE and Maven and i am trying a simple dopost.but i am getting (HTTP method POST is not supported by this URL) what could be the issues
login.jsp

<form action="/login" method="post" >
<div class="login-container less">
<div class="well-login">
<div class="control-group">
<div class="controls">
<div>
<input type="text" placeholder="Username or Email" class="login-input user-name">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<div>
<input type="password" placeholder="Password" class="login-input user-pass">
</div>
</div>
</div>
<div class="clearfix">
<button class="btn btn-inverse login-btn" type="submit" value="submit">Login</button>
</div>
<div class="remember-me">
<input class="rem_me" type="checkbox" value=""> Remeber Me
</div>
</div>
</div>
</form>


Login Servlet

package webapp;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

super.doPost(request, response);
response.getWriter().println("success");
}
}


can not see where the error is coming from ? and every thing seem oky from my side
SOS

Answer

when your page inside web-inf folder, resources which need to be protected from Http access are placed under WEB-INF and filter is attached to view (jsp/html/.doc/.txt/xml) to prevent direct access.

so use getServletContext() inside doGet()

request.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);

and since you wont be navigating any other page from doPost() method so use include() method

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
    response.getWriter().println("<h1>success</h1>  ");
    request.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp").include(request, response);
}

remove you override of super.doPost(request, response); inside dopost() and also <form action="login" method="post" > removing "/" from login