browser shows 404 error [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to servlet and making my first servlet using eclipse.I have made Index.html, Login.java and WelcomeServlet.java. But whenever I am trying to access the using
localhost:8080/ServletExample/
It shows 404 error.Here are the codes..
Index.html
<form action="Login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet")) {
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
} else {
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
package java.io;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

package java.io;
why u put this line in WelcomeServlet.java.

You're mapping to 'WelcomeServlet' not 'ServletExample'.
Try going to localhost:8080/WelcomeServlet
EDIT: There shouldn't be a trailing slash, sorry!

Make sure ur projrct name is ServletExample.
localhost:8080/ServletExample/index.html

Related

HTTP Status 405: HTTP method POST is not supported by this URL

I've tried all methods available on StackOverflow and the internet, but nothing seems to workout as intended, below's a list of what I've tried doing:
All declared methods in my java files are protected named doPost()
I tried using sendRedirect() method instead of RequestDispatcher()
I also tried using another method and calling it in doPost()
I also tried creating another web project in Eclipse, but that too didn't work
Any help would be appreciated, thanks!
Here is my login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="auth" method="post">
<table>
<tr>
<td>Email ID:</td>
<td><input type="email" name="userEmail"></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="userPassword"></td>
</tr>
<tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
authenticate.java
package newAuthentication;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class authenticate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userEmail = request.getParameter("userEmail");
String userPassword = request.getParameter("userPassword");
if (validateUser.checkUser(userEmail, userPassword))
{
HttpSession session = request.getSession();
session.setAttribute("userEmail", userEmail);
RequestDispatcher dispatch = request.getRequestDispatcher("home");
dispatch.forward(request, response);
}
else
{
out.println("Incorrect authentication credentials, please try again!");
RequestDispatcher dispatch = request.getRequestDispatcher("login.html");
dispatch.include(request, response);
}
}
}
validateUser.java
package newAuthentication;
import java.sql.*;
public class validateUser
{
public static boolean checkUser(String userEmail, String userPassword)
{
boolean state = false;
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/wad","root","root");
PreparedStatement fetchData = connect.prepareStatement("select * from studentData where email = ? and password = ?");
fetchData.setString(1, userEmail);
fetchData.setString(2, userPassword);
ResultSet data = fetchData.executeQuery();
state = data.next();
}
catch (Exception err)
{
err.printStackTrace();
}
return state;
}
}
home.java
package newAuthentication;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class home extends HttpServlet
{
protected void doPost(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException
{
doGet(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String userEmail = (String)session.getAttribute("userEmail");
out.println("Welcome user " + userEmail);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>newAuth</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>newAuthentication.authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Home</servlet-name>
<servlet-class>newAuthentication.home</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Why you have this problem in the first place:
This chunk of code is MUCH TOO LONG to try all in one step. Especially if you don't have experience working with servlets. If you are not yet sure if your servlets and basic mappings work, start small - a single servlet, a single GET mapping - that you can try in the browser, without any HTML. Just two files in the entire project: web.xml and MyServlet.java - and just leave the doGet method empty.
Right now, your code is so long, that you simply cannot guess the problem once you hit it - there's too many places to verify!
The magic formula is: "try just one thing at a time".
Solution:
Remove the doGet(request, response) call in your doPost method.
You don not provide your own doGet method, so it defaults to what's in the superclass. It so happens, that the default doGet method throws an exception stating that the GET method is not supported. Since you call it from your doPost, the propagating exception makes container think (rightly so) that it's your doPost that is throwing, and so that it is POST that is unsupported.
Also, the call makes no sense.
BTW: Notice that you would find this error in 5 seconds, if you first tried with the suggested two class approach: you would only have this one thing to verify.

404 error in tomcat, Java Servlet, Apache Netbeans [duplicate]

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.

Java servets request.getMethod() not working

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.

How to process href parameters jsp

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}

Issue passing JSON object to HttpServlet

I have an html form that I want to pass to a servlet when the form is submitted. The form info is:
<form method="post" action = "/directory" name="dirinit" id="srchform">
and the jQuery code I'm trying to use to post is:
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formData = JSON.stringify(jQuery("form").serializeArray());
$.post("/directory", formData)
});
});
The servlet is set up as:
public class NewDirectory extends HttpServlet{
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/json");
String form = request.getParameter("formData");
System.out.println(form);
}
}
My web.xml is:
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>NewDirectory</display-name>
<servlet>
<servlet-name>newdirectory</servlet-name>
<servlet-class>edu.msu.is.directory.newdirectory</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newdirectory</servlet-name>
<url-pattern>/directory</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
When I try to post the form data, I get a 404 error saying that the url was not found. I'm pretty new to servlets, so I'm not even sure I'm setting the the servlet up correctly.
Your code should be something like this :
Servlet :
package edu.msu.is.directory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewDirectory extends HttpServlet
{
private static final long serialVersionUID = 1L;
public NewDirectory()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/json");
String form = request.getParameter("formData");
System.out.println(form);
}
}
web.xml
...
<servlet>
<servlet-name>NewDirectory</servlet-name>
<servlet-class>edu.msu.is.directory.NewDirectory</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewDirectory</servlet-name>
<url-pattern>/directory</url-pattern>
</servlet-mapping>
...
Html Form :
<form method="post" action="directory" name="dirinit" id="srchform">
Javascript :
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formData = JSON.stringify(jQuery("form").serializeArray());
$.post("directory", formData)
});
});
Note : If you are getting 404 error that means either you are accessing different url or your servlet/jsp is not mapped properly.
Here you set your action url as /directory which should be either only directory or /YourProjectContextRootPath/directory.
<servlet-class>edu.msu.is.directory.newdirectory</servlet-class>
is case sensitive, should be
<servlet-class>edu.msu.is.directory.NewDirectory</servlet-class>

Categories