The code below is from a book,so it’ll not be incorrect.But I don’t know how to solve this below error.When delete the method doGet(),the same error!
«HTTP Status 405 — HTTP method GET is not supported by this URL»
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PDFServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("application/pdf");
ServletOutputStream out=response.getOutputStream();
File pdf=null;
BufferedInputStream buf=null;
try{
pdf=new File("C:\Users\lk\Desktop\Desktop\ example.pdf");
response.setContentLength((int)pdf.length());
FileInputStream input=new FileInputStream(pdf);
buf=new BufferedInputStream(input);
int readBytes=0;
while((readBytes=buf.read())!=-1) out.write(readBytes);
}catch(IOException e){
System.out.println("file not found!");
}finally{
if(out!=null) out.close();
if(buf!=null) buf.close();
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
-<web-app xsi:.........." version="2.5">
-<servlet>
<description>This is the description of my Java EE component</description>
<display-name>This is the display name of my Java EE component</display-name>
<servlet-name>PDFServlet</servlet-name>
<servlet-class>PDFServlet</servlet-class>
</servlet>
-<servlet-mapping>
<servlet-name>PDFServlet</servlet-name>
<url-pattern>/PDFServlet</url-pattern>
</servlet-mapping>
-<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
BalusC
1.1m370 gold badges3585 silver badges3539 bronze badges
asked Aug 24, 2012 at 8:18
0
I had this same problem just now. «HTTP Status 405 — HTTP method GET is not supported by this URL». My solution was as follows:
public abstract class Servlet extends HttpServlet {
protected HttpServletRequest req;
protected HttpServletResponse resp;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.req = req;
this.resp = resp;
this.requestManager();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.req = req;
this.resp = resp;
this.requestManager();
}
protected abstract void requestManager() throws IOException;
}
I had problem in my constructor, because the «doGet» I was calling the super
answered May 28, 2013 at 18:20
Sileno BritoSileno Brito
4491 gold badge13 silver badges30 bronze badges
1
The Servlet code seems correct.
Provide web.xml
entry and Servlet calling URL.
There are two main reasons which cause this error:
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{
....
}
Read @BalusC’s answer for more details. : doGet and doPost in Servlets
answered Aug 24, 2012 at 9:06
Hardik MishraHardik Mishra
14.7k9 gold badges61 silver badges96 bronze badges
5
Replace the line
pdf=new File("C:\Users\lk\Desktop\Desktop\ example.pdf");
with
pdf=new File("C:/Users/lk/Desktop/Desktop/example.pdf");
and then proceed again.
nhahtdh
55.5k15 gold badges125 silver badges162 bronze badges
answered Mar 6, 2013 at 6:28
Ramesh JRamesh J
7842 gold badges11 silver badges24 bronze badges
you need to do
<form action="servlet name " method="post">
in your index.jsp file
Glorfindel
21.5k13 gold badges78 silver badges105 bronze badges
answered Jul 9, 2015 at 11:15
When the above error appears then override doGet()
method.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp); //To change body of generated methods, choose Tools | Templates.
}
answered Feb 2, 2016 at 9:57
I was using html file. To create web page.
So when I encountered with this error. My solution was:
Just to remove » index.html » path in my web.xml file.
becayse my html file name was the same as «index.html»
answered Aug 14, 2016 at 20:39
M.aliM.ali
11 bronze badge
Each servlet must contain a doGet() method, which is defaultly executed by server.
so see that you have doGet method.
answered Nov 20, 2013 at 6:40
RakeshRakesh
351 silver badge4 bronze badges
1
The 405 Method Not Allowed error is an HTTP response status code signaling that the server has rejected a method for the requested resource despite receiving and recognizing it. Although it’s technically a client error message (4xx HTTP status code), the error is caused by a server-side problem.
Unlike most of the other HTTP response codes in the 4xx category (client-side), the 405 Method Not Allowed error is considered to be a server-side problem. Below you have detailed information on why you’re seeing this error and why it’s probably the responsibility of the website operator.
Depending on the server that’s handling the request, the 405 HTTP message you’ll see might be different. Here are some of the more common phrases:
- 405 Method Not Allowed
- HTTP Status 405 – HTTP method GET is not supported by this URL
- 405 – HTTP verb used to access this page is not allowed
- 405 Not Allowed
- Method Not Allowed
- Error: 405 Method Not Allowed
- HTTP 405 Error
- HTTP 405 Method Not Allowed
- HTTP Error 405 – Method Not Allowed
Note: Keep in mind that web administrators might customize server-side and client-side errors. Depending on the site you’re visiting, you might see additional graphic elements on top of the status code response.
Server-side issue
The most common error HTTP codes are shared between 4xx Client errors and 5xx Server errors. The error 405 Method Not Allowed is special in the sense that although it’s supposed to be a client-side issue, the error is caused solely by a server-side problem in one way or another.
Most of the time, the server is misconfigured and handles requests improperly – this will result in the 405 Method Not Allowed error and other traffic routing problems. But even if the web server is the network object returning the error as a HTTP response code to the client, we can’t definitely rule out that the client request isn’t somehow causing the issue.
Similar to most of the other status response error codes, the 405 Method Not Allowed error is difficult to identify and fix. Given the complex relationship between the client, a web server, a web application and additional web services, determining the cause of this particular error might be a challenge for even the best web engineers.
What triggers the 405 HTTP error?
Basically, the 05 Method Not Allowed error acknowledges that the client requested resource is valid and exists, but the client has used an unacceptable HTTP method. To put this information into perspective – The Hypertext Transfer Protocol (HTTP) has a set of methods that indicate possible actions that can be performed on the web server that is being contacted. Here’s a list with every possible action:
- GET – Fetch the information associated with a specific URL resource.
- HEAD – Retrieve the header information linked to a URL resource.
- POST – Send data to this web server.
- PUT – Replace existing data for a particular URL with the new data currently transmitted by the client.
- DELETE – Delete the data from the specified URL.
- CONNECT – Established a tunnel to the server as identified by the target resource.
- OPTIONS – Describes the communication options for the specified target resource.
- TRACE: This method will trigger a loop-back test on the path to the target resource.
- PATCH: Applies partial modifications to a resource.
Note: Out of all the 9 methods, GET, HEAD, POST, PUT and DELETE are far more prevalent than the others.
Depending on the purpose of the web server, it’s administrator will configure it to allow certain methods and reject others. For e.g. – if the website in question holds no interactive content whatsoever, it makes no sense to allow the POST method on the web server. If this method is not allowed and a client contacts the server with a POST request, the 405 Method Not Allowed error will be displayed, informing the browser that the method is not allowed.
Diagnosing the 405 Method Not Allowed error
As we established above, the 405 Method Not Allowed error indicates that the user has requested (from the server) a valid resource with an invalid HTTP method. This is precisely why the error technically lies on the client side – from the server’s point of view, the client simply made a wrong request. Here are some of the most common scenarios that will trigger the 405 Method Not Allowed error:
- The error appears due to a misconfiguration of the web server or the software components that are tasked with performing the action on the respective URL resource.
- The website administrator imposed a ban on the HTTP method that is used by the user agent – this is commonly done for security reasons.
- The error is originating from the URL resource – It’s requiring a method that is not allowed by the web server.
- The HTTP method is not allowed by the hosting provider used by the website administrator. This is a common occurrence with the POST method – The method is blocked by some hosting providers when accessing HTML documents for security reasons.
How to fix the 405 Method Not Allowed error
If you encounter the 405 Method Not Allowed error on a certain website, there’s hardly anything significant that you can do about it. But since the most common cause of the error is an incorrect URL, you can double-check it or visit the root directory of the web project and navigate manually to that particular resource.
Nowadays, most web servers are tightly secured to discourage access from improper URLs. The issue can potentially arise because you’re trying to access a private page that was meant for users with enhanced authorization. Don’t bother trying common fixes for 4xx errors like refreshing the page, restarting your network or disabling proxy – they won’t work with the 405 Method Not Allowed error.
If you’re struggling with the issue and you’ve made sure that the URL is correct, all you can do is wait for the issue to be resolved by the site’s administrators. In the event that you’re in urgent need of that particular web resource, contact the web administrator and ask him to investigate the issue.
Kevin Arrows
Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.
Ошибка HTTP 405 указывает на то, что сервер отклонил конкретный метод HTTP, используемый веб-браузером. Узнайте, почему он может появиться на вашем сайте и как быстро исправить его, не нанося ущерба вашей репутации в интернете.
Нет ничего более неприятного для потребителя, который ищет мгновенного удовлетворения, чтобы наткнуться на ошибку на вашем сайте. Если вместо того, чтобы найти нужную им информацию, они наткнутся на страницу с надписью “ошибка”, скорее всего, подавляющее большинство потребителей покинут ваш сайт.
Но помимо того, что потребители быстро уходят, вы также можете испытать разрушительные последствия для ваших коэффициентов конверсии. Не говоря уже о том, что поисковые системы также обращают внимание на показатели отказов. Ошибка, которая может появиться на вашем сайте и вызвать разочарование у потребителей — это Ошибка HTTP 405.
К сожалению, эта ошибка похожа на что-то мистическое. Она говорит вам, что что-то пошло не так, но не дает более подробного объяснения.
Хорошая новость заключается в том, что с помощью небольшого исследования и усилий с вашего сайта вы можете быстро определить суть проблемы и исправить ее, прежде чем заметите падение активности и продаж.
В этой статье мы поговорим о том, что такое Ошибка HTTP 405, почему она может появиться на вашем сайте, а также о том, как ее исправить. Давайте начнем!
HTTP 405 – это код состояния ответа HTTP. Существует пять видов кодов состояния HTTP-ответа. Все они сообщают пользователю, был ли успешно выполнен определенный HTTP-запрос. Пять основных кодов состояния включают в себя:
1xx коды состояния: Информационные запросы 2xx коды состояния: Успешные запросы 3xx коды состояния: Перенаправление 4xx коды состояния: Ошибки клиента 5xx коды состояния: Ошибки сервера
Сообщение об Ошибке 405 Method Not Allowed – это ошибка клиента, которая указывает на то, что проблема заключается в чем-то на стороне клиента.
Ошибка HTTP 405 указывает на то, что веб-браузер запросил доступ к одной из ваших страниц, и ваш веб-сервер распознал этот запрос. Однако сервер отклонил конкретный метод HTTP, который он использует. В результате ваш веб-браузер не может получить доступ к запрошенной веб-странице. Когда это произойдет, ваши посетители увидят веб-страницу с ошибкой.
Варианты имен Ошибок HTTP 405
Различные веб-серверы, операционные системы и браузеры отображают ошибку по-разному. Важно отметить, что причина проблемы также может меняться от одного сервера к другому.
Наиболее распространенные способы появления Ошибки HTTP 405 для потребителей включают в себя:
- HTTP Ошибка 405 – Метод Не Дозволен
- HTTP Метод Не Дозволен
- 405 Не Дозволено
- Метод Не Дозволен
- HTTP Ошибка 405
Независимо от того, как появляется ошибка, будь то Ошибка HTTP 405 или Метод Не Дозволен, проблема одна и та же, и это то, что ее трудно исправить. Вы знаете, что что-то не так, но понятия не имеете, что это может быть. Вам предстоит найти суть проблемы и устранить ее до того, как она нанесет непоправимый ущерб.
Как исправить Ошибку 405?
Проверьте URL-адрес
Первое, что вам нужно сделать, когда вы видите Ошибку 405 на своем сайте – это проверить, правильно ли вы ввели URL-адрес.
Внимательно посмотрите на URL-адрес и убедитесь, что он содержит все правильные буквы.URL-адрес содержит какие-либо специальные символы, убедитесь, что они вставлены правильно.
Пока вы этим занимаетесь, вы также можете попробовать обновить страницу. Вы можете обнаружить, что обновление страницы может заставить ее правильно загрузиться. Если вы уверены, что ввели правильный URL-адрес, но все еще видите ошибку, выполните откат последних обновлений.
Откат последних обновлений
Большая часть веб-сайтов размещается на таких CMS, как WordPress или Wix. Вы можете обнаружить, что недавнее обновление системы может быть основной причиной проблемы.
Попробуйте подумать, когда вы впервые заметили Ошибку 405 на своем сайте. Это было сразу после того, как вы обновили CMS? Если это так, то подумайте о том, чтобы вернуться к предыдущей версии.
Удаление новых расширений, модулей или плагинов
Расширения и плагины могут быть полезны для улучшения возможностей вашего сайта, но они также могут нанести серьезный ущерб.
Некоторые расширения могут полностью контролировать вашу систему и вносить изменения в любой код, включая PHP, CSS, HTML, JavaScript и вашу базу данных. В этом случае рекомендуется удалить все новые расширения, которые вы недавно добавили в свою систему.
Если вам нужна помощь в удалении расширения, просто сделайте быстрый поиск в Google, чтобы найти официальную документацию для этого процесса.
Дважды проверьте изменения в своей базе данных
Иногда, даже если вы удалите расширение, изменения, внесенные этим расширением в систему, не могут быть полностью возвращены.
Есть некоторые расширения, особенно на CMS WordPress, которые имеют карт-бланш внутри приложения, который включает в себя полный доступ к базе данных. Расширение может изменять записи базы данных, которые не принадлежат самому расширению, а создаются и управляются другими расширениями. Когда это происходит, расширение может не знать, как вернуть изменения в записи базы данных, что приводит к тому, что расширение игнорирует такие вещи во время удаления.
Лучшее, что вы можете сделать в таком случае – это открыть базу данных и вручную просмотреть таблицы и записи, которые могли быть изменены расширением. Или вы можете провести быстрое исследование и попытаться найти людей, которые столкнулись с той же проблемой, чтобы увидеть, как они справились с этой проблемой.
Проверьте файлы конфигурации для вашего веб-сервера
Если двойная проверка изменений базы данных не помогла, попробуйте проверить файлы конфигурации программного обеспечения веб-сервера на наличие непреднамеренных инструкций перенаправления.
Ваше приложение работает либо на веб-серверах Apache, либо на веб-серверах nginx.
Если вы используете Apache, вам необходимо проверить как файл конфигурации сервера apache, так и файл конфигурации сервера apache файл .htaccess. После того, как вы найдете файл .htaccess, откройте его в текстовом редакторе и найдите строки, использующие указания RewriteXXX. В случае, если вы столкнетесь с какими-либо странными указаниями RewriteCond или RewriteRule, попробуйте временно сделать замечание, используя префикс символа #. Перезагрузите веб-сервер и посмотрите, устранена ли проблема.
Если вы используете nginx, вам нужно проверить nginx.conf файл. Файл находится в одном из нескольких общих каталогов: /usr/local/nginx/conf, /etc/nginx или /usr/local/etc/nginx. Как только вы найдете файл, откройте его в текстовом редакторе и выполните поиск указании, использующих флаг кода ответа 405. Сделайте замечания на любые аномалии, а затем перезагрузите сервер, чтобы увидеть, была ли проблема решена.
Проверьте журналы приложений
Журналы приложений содержат историю вашего веб-сайта, в том числе информацию о том, какие страницы были запрошены, к каким серверам он подключался и многое другое.
Открытие журналов приложений может указать вам правильное направление, в котором может возникнуть ошибка.
Расположение журналов приложений зависит от типа используемого сервера. Как только вы их найдете, запустите поиск Ошибок 405. Надеюсь, вы определите, что является основной причиной проблемы.
Отладка кода приложения или скриптов
Если вы перепробовали все вышеперечисленное и ничего не получилось, возможно, пришло время посмотреть, не является ли причиной ошибки проблема в каком-то пользовательском коде вашего приложения.
Вы можете поставить диагноз, вручную отладив приложение и проанализировав журналы приложений и серверов.
Сделайте копию приложения на локальную машину разработки и выполните пошаговую отладку. Вам удастся воссоздать точный сценарий, в котором произошел 405 Метод Не Дозволен, и просмотреть код приложения, когда что-то пойдет не так.
Заключение
Надеемся что наша подробная запись о кодах состояния HTTP, будет полезная для вас. Помните что регулярный контроль и техническое обслуживание помогут сохранить ваш сайт безупречным, а его владельца-беззаботным.
Понравилось то, что вы прочитали?
Подписывайтесь на нашу рассылку и получайте ежедневные обновления о новых учебниках, статьях, курсах и о многом другом!
Просто введите ваш адрес электронной почты, чтобы подписаться.
(Без спамов; ежемесячно два письма; отписаться от рассылки можно в любое время)