HTTP Status 405 – HTTP method GET is not supported by this URL

The HTTP status 405 is a very common error message in Java Servlet.


HTTP Status 405 - HTTP method GET is not supported by this URL

type Status report
message HTTP method GET is not supported by this URL
description The specified HTTP method is not allowed for the requested resource
 (HTTP method GET is not supported by this URL).
Apache Tomcat/6.0.20

Solution

This is always caused by following two reasons

1) You do not have a valid doGet() method, when you type the servlet’s path in address bar directly, the web container like Tomcat will try to invoke the doGet() method.


	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		....		
	}		

2) You made a HTTP post request from a HTML form, but you do not have a doPost() method to handle it. The doGet() can not handle the “Post” request.


	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		....		
	}		

28 comments on “HTTP Status 405 – HTTP method GET is not supported by this URL

  1. When I run on Server a java servlet with apache tomcat 9 in eclipse, I don’t see console message Reloading context name with name [context name] showing up. Maybe that is why my project not working.and giving http status 405 – http method not allowed !!
    I am attaching doPost(), index.html and web.xml files

    package io.simplilearn.workshop;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * 
     * Servlet implementation class HandleHttpPostRequest
     *
     */
    
    
    public class HandleHttpPostRequest extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// System.out.println("Do Post Is Called");
    		response.setContentType("text/html");
    		
    		// read uername from HTTP request
    		String userName = request.getParameter("USER_NAME");
    		PrintWriter out = response.getWriter();
    		
    		out.println("<html><head><title>Simplilearn</title></head>");
    		out.println("<body>");
    		out.println("<h2>Welcome "+ userName + " to Simplilearn phase 2: Become Web Developer </h2>");
    		out.println("</body>");
    		out.println("</html>");
    		
    		out.close();
    				
    	}
    
    }
    	
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>simplilearn</title>
    </head>
    <body>
    <h2>HTTP Get Request</h2>
    <a href="/methods/getServlet">Get Servlet</a>
    
    <hr color="blue" size="5">
    
    <h2>HTTP Post Request</h2>
    <form action="/methods/postServlet" method="post">
    	username : <input type="text" name="USER_NAME" /> <br>
    <input type="submit"  value="submit">
    </form>
    </body>
    </html>
    
    
    Reply
  2. i m getting this type of problem
    HTTP Status 405 – Method Not Allowed

    Type Status Report

    Message HTTP method GET is not supported by this URL

    Description The method received in the request-line is known by the origin server but not supported by the target resource.
    Apache Tomcat/9.0.21

    Reply
      1. package com.user;

        import java.io.IOException;
        import java.sql.Connection;
        import java.sql.ResultSet;
        import java.sql.Statement;
        import java.util.UUID;

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

        import com.connection.DatabaseConnection;

        /**
        * Servlet implementation class UserLogin
        */
        @WebServlet(“/UserLogin”)
        public class UserLogin extends HttpServlet {

        /**
        *
        */
        private static final long serialVersionUID = 1L;

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter(“username”);
        String pass = request.getParameter(“password”);
        try {
        HttpSession hs = request.getSession();
        String tokens = UUID.randomUUID().toString();
        Connection con = DatabaseConnection.getConnection();
        Statement st = con.createStatement();
        ResultSet resultset = st.executeQuery(“select * from tbluser where uname='” + uname + “‘ AND password='” + pass + “‘”);
        if (resultset.next()) {
        String fullName=resultset.getString(2);
        hs.setAttribute(“uname”, uname);
        hs.setAttribute(“fullName”, fullName);
        hs.setAttribute(“mobileNo”, resultset.getString(3));
        response.sendRedirect(“user-dashboard.jsp?_tokens='” + tokens + “‘”);
        } else {
        String message = “Invalid credential”;
        hs.setAttribute(“message”, message);
        response.sendRedirect(“user-login.jsp”);
        }
        } catch (Exception e) {

        e.printStackTrace();
        }

        }

        }

        getting 405 error, Status Report Message HTTP method GET is not supported by this URL. Description The method received in the request-line is known by the origin server but not supported by the target resource.

        Reply
  3. i am trying to build a login logout session using cookies, but when clicking on logout link it generates a error 405 in glassfish server and states http method GET not supported by this url . And i have used doPost() method.

    Reply
  4. HTTP Status 405 – Method Not Allowed

    Type Status Report

    Message HTTP method GET is not supported by this URL

    Description The method received in the request-line is known by the origin server but not supported by the target resource.
    ———

    package com.telusko;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class AddServlet extends HttpServlet
    {

    public void Service(HttpServletRequest req,HttpServletResponse res) throws IOException
    {
    int i=Integer.parseInt(req.getParameter(“num1”));
    int j=Integer.parseInt(req.getParameter(“num2”));

    int k=i+j;

    PrintWriter out=res.getWriter() ;
    out.println(k);
    //System.out.println(“result is “+k);

    }
    }

    Reply
    1. service method is used in GenricServlet, try using doGet or doPost method

      Reply
      1. thanks a lot!! i spent hours on this..using doGet solved my problem

        Reply
  5. Hi…

    Sir I am getting some problem with below code please tell the solution for the same

    “web.xml”

    LoginServlet

    practice.harish.LoginServlet

    LoginServlet

    /login

    LoginServlet.java

    package practice.harish;

    import java.io.IOException;

    import java.io.PrintWriter;

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

    {

    response.setContentType(“text/html”);

    PrintWriter out=response.getWriter();

    String uname=request.getParameter(“uname”);

    String upwd=request.getParameter(“upwd”);
    out.println(“”);

    out.println(“”);

    out.println(“”);

    out.println(“”);

    if (uname.equals(“harish”)&&upwd.equals(“java007”))

    {

    out.println(“Login Success”);

    }else

    {

    out.println(“Login Failure”);

    }

    out.println(“”);

    out.println(“Login Page“);

    out.println(“”);

    }

    }

    Loginform.html

    Durga SoftWare Solutions

    User Login Page

    User name

    Password

    This is my first Servlet, after i Run the project i am getting the login page but it is not giving any success message when i click on login button.. as per my project..

    please help me in this..

    Reply
  6. Thanks. I had by mistake used a doGet method instead of a doPost method on the SERVER side and my CLIENT was using a HttpPost method. The mismatch caused the server to issue a 405 status.

    Reply
  7. I’v got the similar error HTTP Status 405 – Request method ‘POST’ not supported
    Here is the code of my update controller

    @Controller
    @RequestMapping(“/updateCd”)
    public class UpdateCdController {

    @Autowired
    private CdService cdService;

    @RequestMapping(value = “/{id}”, method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable int id, ModelMap model) {

    Cd cd = cdService.getCd(id);
    model.addAttribute(“updateCD”, cd);

    return “updateCd”;

    }

    @RequestMapping(method = RequestMethod.POST)
    public String updateForm(@ModelAttribute(value = “updateCD”) Cd cd, BindingResult result) {

    if (result.hasErrors()) {

    return “updateCd”;

    } else {

    cdService.updateCd(cd);
    return “redirect:content”;

    // }

    }
    }
    }

    But the similar controller works absolutely normally
    Here is the code of add controller

    @Controller
    @RequestMapping(“/addCd”)
    public class AddCdController {

    @Autowired
    private CdService cdService;

    @RequestMapping(method = RequestMethod.GET)
    public String showAddForm(ModelMap model) {
    Cd cd = new Cd();

    model.addAttribute(“addCD”, cd);

    return “addCd”;

    }

    @RequestMapping(method = RequestMethod.POST)
    public String addForm(@ModelAttribute(value = “addCD”) Cd cd, BindingResult result) {

    if (result.hasErrors()) {

    return “addCd”;

    } else {
    cdService.addCd(cd);
    return “redirect:content”;

    }

    }
    }

    Reply
  8. Mr Mkyong –

    Your “HTTP Status 405 – HTTP Method GET Is Not Supported By This URL” answer saved me much time and frustration in troubleshooting my project. I have come to your posts often as I deploy my first Google AppEngine project and the information you provide with such care is accurate and helpful. Thank you for the contribution to learning and success you are making.

    Regards,

    David Carlin

    Reply
  9. Needed to post you the little bit of note in order to give thanks as before for the superb things you’ve contributed here. It has been so surprisingly open-handed with you to give openly precisely what a number of us would have offered as an e-book to help with making some cash on their own, and in particular given that you might have done it if you considered necessary. The thoughts likewise acted like the fantastic way to be certain that other people have the identical dreams just like my own to know many more on the subject of this condition. I know there are lots of more enjoyable opportunities up front for folks who read through your site.

    Reply
  10. Hi,
    I am getting The same Error “Request method ‘GET’ not supported”.
    When i hit localhost:…./moving-cable-tv/confirm_address
    this error comes.
    This is how my controller class looks like. Can some one help me.

     
    @Controller
    @RequestMapping("/moving-cable-tv/confirm_address")
    public class MoversConfirmAddressController {
    
         @RequestMapping(value="/confirm_address", method = RequestMethod.GET)
            public View get(@ModelAttribute("moversCommand") MoversCommand moversCommand) {
            
            return new InternalResourceView("/WEB-INF/jsp/confirm_address.jsp");
        }
    
        @RequestMapping(method = RequestMethod.POST)
        public View post(@ModelAttribute("moversCommand") @Valid MoversCommand moversCommand,
                BindingResult result,
                RedirectAttributes attr) {
            if (result.hasErrors()) {
                logger.info("Validation Error(s) : {}", result.getAllErrors().size());
                attr.addFlashAttribute("org.springframework.validation.BindingResult.moversCommand", result);
                attr.addFlashAttribute("MoversCommand", moversCommand);
                return new RedirectView("/moving-cable-tv/moving_form");
            } else {
                if (moversCommand.getServiceAddr1().equalsIgnoreCase("noAddrAvailable")) {
                    logger.debug("Confirmed Address Error - NoMatch");
    
                    moversCommand.setStatus("NoMatch");
                    return new RedirectView("/moving-cable-tv/moving_form");
                }
    
                if (moversCommand.getCustomerIntent().equalsIgnoreCase("new")||moversCommand.getCustomerIntent().equalsIgnoreCase("current")) {
                    moversCommand.handleConfirmAddress(moversCommand, astService);
                }
            }
            MoversLeadService service = new MoversLeadService();
            moversCommand.setSpecialOffers(service.getOffer(moversCommand.getCurrentProvider(), Integer.parseInt(moversCommand.getClusterCode())));
            return new RedirectView("/moving-cable-tv/show_offers");
        }
    Reply
  11. hi,
    i had a same issue when try to post server return 405 method not allowed.

    i handle servlet dopost and doget

    in form if i use method get its working when use post i got 405 error

    how to solve this issue?

    Reply
  12. Reason #2 sounds like a bug in the web container. If it can’t handle POST, it should say that it can’t handle POST, rather than saying it can’t handle GET. 🙂

    Reply
  13. For Java

    public class Secure extends HttpServlet {
    
        /**
         * Processes requests for both HTTP GET and POST methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
               String username,secq;
                username=request.getParameter("un");
                secq=new model.Sec1().sec(username);
                HttpSession session=request.getSession();
                session.setAttribute("un", username);
    
                if(secq!=null)
                {
                session.setAttribute("sq",secq);
                response.sendRedirect("security.jsp");
                }
    
            } finally {
                out.close();
            }
        }
    
        // 
        /**
         * Handles the HTTP GET method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Handles the HTTP POST method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Returns a short description of the servlet.
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// 
    
    }
    
    model file(Sec.java)
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package model;
    import java.sql.*;
    import java.util.*;
    
    public class Sec {
                       Connection con;
                       public String secu(String username)
                       {
                          Statement st;
                          String secq="";
                           try
                           {
    
    
                                 con=new comm.connection().getConnection();
    
    
                                    st = con.createStatement();
                                    ResultSet rs=st.executeQuery("select securityquestion  from register where username='"+username+"'");
                                     if(rs!=null && rs.next())
                                     {
                                      secq=rs.getString(1);
                                     }
                        rs.close();
                                    st.close();
                                    con.close();
    
    
    
                                } catch (SQLException ex) {
    
                                }
                              return secq;
    
                       }
                       public boolean se(Vector v)
                      {
    
                           boolean b=false;
                                 con=new comm.connection().getConnection();
                                 Statement st;
                                 try {
                                       st=con.createStatement();
    
    
                                       PreparedStatement ps=con.prepareStatement("update register set password='"+v.get(2).toString()+"' where  securityanswer='"+v.get(1).toString()+"' ");
    
                                       int i=ps.executeUpdate();
    
                                       if(i>0)
                                           b=true;
                                   }
    
                                   catch (SQLException ex) {
    
                                }
    
    
    
    
                                                               return b;
                             }
    
               public boolean se1(String username,String confpass)
               {
                   boolean b=false;
    
              con=new comm.connection().getConnection();
                                 Statement st;
    
                                 try {
                                       st=con.createStatement();
    
    
                                       PreparedStatement ps=con.prepareStatement("update studentlogin set pass='"+confpass+"' where username='"+username+"' ");
    
                                       int i=ps.executeUpdate();
    
                                       if(i>0)
                                           b=true;
                                   }
    
                                   catch (SQLException ex) {
    
                                }
    
                   return b;
               }
    
    
    }
     

    i am having a problem as i am clicking on submit button..It says method POST is not supported by url..i have checked the mapping.m not able to find the solution..

    Reply
  14. I had same problem. The decision was to remove auto generated
    super.doGet(req, resp); in my doGet method

    Reply
    1. Your comment solved my problem… Thanks a ton!

      Reply
  15. In the past couple of weeks I have started getting the “HTTP Status 405 – HTTP method GET is not supported by this URL” message when I try to use some links from the MY MSN homepage. I’m not doing any programing just trying to go to a link on the page. I’m using Internet Explorer 8. Is there anything I should be changing to try and fix this?

    Reply
    1. This error is caused by the server site, nothing to do with the client. Please contact the link owner / website owner about this issue.

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *