This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
I am beginner in Java servlets, whenever I try to submit a simple form (which is supposed to be handled by a servlet) it gives me a 404 error
Error Message:
Project directory structure:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Click here!</h1>
<form action="/AddServlet">
Enter Number 1: <input type="number" name="num1" ><br /><br />
Enter Number 2: <input type="number" name="num2" ><br /><br />
<input type="submit" name="submit" >
</form>
</body>
</html>
AddServlet.java:
package mycompany.webapplication;
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 AddServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AddServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AddServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int i = Integer.parseInt(request.getParameter("num1"));
int j = Integer.parseInt(request.getParameter("num2"));
int k = i + j;
PrintWriter out = response.getWriter();
out.println("result is " + k);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
index.html Output:
But if I click on the link that says "Click Here" it goes to AddServlet.java as expected
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>mycompany.webapplication.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/AddServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
You use a absolute URI path /AddServlet, but the correct path is of the form /<webapp>/AddServlet, where <webapp> is the name of your applications context.
Since you most certainly don't want to hardcode the name of your application, use a relative URI path AddServlet.
Related
I have written a sample code to pass form data from a html page to a servlet. Here are my source codes,
StudentForm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Form</title>
</head>Title
<body>
<form action="FormDataServlet" method="get">
FName:<input type="text" name="fName"> <br/>
LName:<input type="text" name="lName"><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
FormDataServlet
package com.kasun.student.form;
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 java.io.IOException;
import java.io.PrintWriter;
/**
* Created by kausn on 5/24/17.
*/
#WebServlet(name = "/FormDataServlet")
public class FormDataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.print("<html><head></head><body>");
printWriter.print("The F name of the student is "+request.getParameter("fName"));
printWriter.print("The L name of the student is "+request.getParameter("lName"));
printWriter.print("</body></html>");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.kasun.servlet.demo.ServletDemo1</servlet-class>
</servlet>
<servlet>
<servlet-name>FormDataServlet</servlet-name>
<servlet-class>com.kasun.student.form.FormDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/ServletDemo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FormDataServlet</servlet-name>
<url-pattern>/FormDataServlet</url-pattern>
</servlet-mapping>
</web-app>
But when I submit the form it says 404 error that is because it is calling the servlet that exists in http://localhost:63342/ServletDemo/web/FormDataServlet?fName=sfddfddfd&lName=dfdf this path. I know for sure that this is where the bug is, but how to fix this? (Please find the screenshot of package structure as below)
I'm new to Java EE and was about to learn to use asynchronous Servlets. I created a web application with a simple index.jsp from which the servlet is called after pressing a button. I always get the following exception:
java.lang.IllegalStateException: Request is within the scope of a
filter or servlet that does not support asynchronous operations
But I set async-supported to true as annotation in the servlet or in web.xml or in both ways. I was searching for hours through similar questions here but I couldn't find a solution. I'm using NetBeans 8.0.2 and glassfish server 4.1 that comes along with NetBeans. Here is my index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Async Test</h1>
<form method="get" action="Asynctest">
<input type="submit"
value="Start test">
</form>
</body>
</html>
the Asynctest servlet:
package Controller;
import java.io.IOException;
import javax.servlet.AsyncContext;
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(asyncSupported = true, name = "Asynctest", urlPatterns = {"/Asynctest"})
public class Asynctest extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AsyncContext ac = request.startAsync(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
and the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Asynctest</servlet-name>
<servlet-class>Controller.Asynctest</servlet-class>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Asynctest</servlet-name>
<url-pattern>/Asynctest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
It makes me crazy.. Thanks for your help!
Hello I am trying to create a simple servlet as follows
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Form extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
p.println("<html><head></head><body bgcolor=\"red\">The request came from"+req.getMethod()+"</body></html>");
}
}
The req.getMethod() should return POST but is giving me a null value.
I am taking the request from an html file coded as follows.
<html>
<body>
<form action="http://localhost:8080/Form" method="GET">
First Name: <input type="text" name="name"/>
<br>
<input type="submit" value="Submit form "/>
</form>
</body>
</html>
here is the web.xml file. Should I make any changes here.
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>Form</servlet-name>
<servlet-class>Form</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Form</servlet-name>
<url-pattern>/Form</url-pattern>
</servlet-mapping>
</web-app>
You can write this annotation to attach your servlet to your form:
#WebServlet("/Form")
public class Form extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
}
You will have to import javax.servlet.annotation.WebServlet.
Below are the web.xml, servlet and jsp code
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 MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
out.println("hello "+userName+" how are you ?");
}
}
JSPCode:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
This is First Servlet
<form action="firstTest">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2"><input name = "sumbit "type="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Web.xml Code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Trial</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/firstTest</url-pattern>
</servlet-mapping>
</web-app>
when i give URL http:localhost:8080/Trial the Index.jsp is coming but when i gave username and password the URL is chaning to http:localhost:8080/firstTest instead of http:localhost:8080/Trial/firstTest and i am getting 405 error "Tomcat error HTTP Status 405 - HTTP method GET is not supported by this URL" is anything wrong in my code
typo...
protected void doGost
change to doPost or doGet...
In your jsp code form tag you have not specified method name, and by default it use GET method, so just replace this code, I hope it will work :
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 MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
out.println("hello " + userName + " how are you ?");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
For to resolve this type of typo errors before we deploy into the server
We use #override annotation for to test whether the method is overloaded method or not. When ever you compiled the java it will throw exception. Actually compiler will check for syntactic errors etc. But in this scenario compiler treated doGost() is also a method by using above annotation at the compilation level only developer can understand where the problem occurred.
So. My suggition is #override for overriding methods.
I have little test page, but I can't get request parameters an don't understand why.
Test page have "href" links like this:
Show smth
Simple controller:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Controller extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
StringBuilder sb = new StringBuilder("Do SMTH<br>");
sb.append("Other will be later...<br>");
String s = sb.toString();
request.setAttribute("result", s);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request,response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>main.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/main.jspc</url-pattern>
</servlet-mapping>
</web-app>
and test page, where i want to show some obtained parameters:
test.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%
out.print("<br>" + "Parameter: ");
request.getParameter("param");
out.print("<br>"+ "URL:");
request.getRequestURL();
out.print("<br>" + "Result:");
request.getParameter("result");
%>
</body>
</html>
But test page showing empty parameters, I don't understand why.
The use of scriptlets (those <% %> things) in JSP is old one and discouraged since the birth of taglibs(JSTL) and EL(Expression Language, those ${} things).
Use below code access your parameter :
Parameter : ${params} <br>
Result : ${result} <br>
URL : ${pageContext.request.requestURI}