Main Tutorials

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{
		....		
	}		

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
28 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Valera
13 years ago

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

Kashish Dubey
3 years ago
Reply to  Valera

Your comment solved my problem… Thanks a ton!

AJIT BANKAR
4 years ago
Reply to  Valera

Thank you …. ur comment solved my problem

Jasneet
6 years ago
Reply to  Valera

It solved my issue as well. Thanks a lot Valera!

Nhan Nguyen
10 years ago
Reply to  Valera

Thanks! Your comment solved my problem.

Zing
12 years ago

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. 🙂

naresh
4 years ago

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

tomCat
4 years ago
Reply to  naresh

use doPost method

B R
1 year ago
Reply to  tomCat

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.

Kamidi Harish
8 years ago

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..

Abcd Poptani
4 years ago

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.

mani
5 months ago

Message HTTP method GET is not supported by this URL

mala
7 months ago

 HTTP method GET is not supported by this URL

Arun Thapa
3 years ago

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>

Anantha
5 years ago

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);

}
}

Twinkle Kaur
4 years ago
Reply to  Anantha

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

pranay gupta
3 years ago
Reply to  Twinkle Kaur

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

Simon
9 years ago

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.

Stanislav
10 years ago

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”;

}

}
}

David Carlin
10 years ago

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

Antonio
10 years ago

Very good. Problem resolved…

Best regards.

sites
10 years ago

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.

pam
11 years ago

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");
    }
suresh
11 years ago

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?

tushar
11 years ago
Reply to  suresh

Suresh please paste your code here

Larry Trussell
14 years ago

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?

RuchiBohra
12 years ago

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..