404 error while running jsp - java

Hi I am receiving the 404 HTTP status while submiting the below jsp.
HTTP Status 404 - /TestServlet1
Could you please help me to resolve this error
Note : The person and the dog class were defined
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<form id="a" action="/TestServlet1">
<input type="submit">
</form>
<%
%>
Name = '${person.name}'
Dog = '${person.dog.name}'
</body>
</html>
TestServlet1
package test;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Dog g = new Dog();
g.setName("dogeee");
Person p = new Person();
p.setDog(g);
p.setName("xxx");
request.setAttribute("person", p);
RequestDispatcher dispatch = request.getRequestDispatcher("/index.jsp");
dispatch.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Web.xml
<?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>GlobalWeather</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet1</url-pattern>
</servlet-mapping>
</web-app>

First and Third answers are right. Either write action="TestServlet1" or action="/Projectname/TestServlet1". If you put /testServet1 in action, it means you are specifying the path the desired file which in this case is wrong while if you use testservlet1 in action , it means you are searching for a file name testservlet1 in your project to run.

404 means that the URL was not found. I suspect that you need the web application name in your URL.
So rather than using a form action of:
/TestServlet1,
try
/name_of_your_web_app/TestServlet1

Just remove tha / in your form action:
<form id="a" action="/TestServlet1">
change it to
<form id="a" action="TestServlet1">
In HTML, adding a / means the relative URL and without a slash means absolute URL. Or better to use the context as mentioned here:
<form id="a" action=${pageContext.request.contextPath}/TestServlet1>

you have to put your contextroot + your servlet name...
contextRoot usually is the name of your project.
action="/nameProject/TestServlet1"
I hope this helps you

Related

Unable to send data to servlet using $post in jQuery

I am trying to pass a value to servlet through a custom jQuery confirmation box.
I searched the web and found that we can use $post to pass the data to servlet but somehow data was not getting passed to servlet.
My requirement is I need to provide two options to user to open or save the pdf document. I used custom jQuery box with these options but data is not getting passed to servlet.
Below is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.2/themes/redmond/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<!-- User Defined Js file -->
<script type="text/javascript">
$(document).ready(function(){
$('#Export').click(function(event) {
event.preventDefault();
var currentForm = $(this).closest('form');
var dynamicDialog = $('<div id="conformBox">'+
'<span style="float:left; margin:0 7px 20px 0;">'+
'</span>Open or save the document</div>');
dynamicDialog.dialog({
title : "Open/Save Dialog",
closeOnEscape: true,
modal : true,
buttons :
[{
text : "Export",
click : function() {
$(this).dialog("close");
$.POST({
type: "post",
url: "button",
data: $('#Export').attr("name"),
success: function(data) {
$('#results').show();
$('#results').html(data);
}
});
// currentForm.submit(); // if I use this then control going to servlet but data is not passed without nothing was happening
}
},
{
text : "Open",
click : function() {
$(this).dialog("close");
currentForm.submit();
}
}]
});
return false;
});
});
</script>
</head>
<body>
<form id="god" action="button">
<button type="button" id="Export">Export</button>
</form>
<div id="results"></div>
</body>
</html>
Servlet code:
package com.testcase.testing;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class button
*/
#WebServlet("/button")
public class button extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public button() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append(request.getParameter("data"));
System.out.println(request.getParameter("data"));
}
}
web.xml
<?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>Testcase</display-name>
<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>
<!-- <servlet>
<servlet-name>button</servlet-name>
<servlet-class>com.testcase.testing.button</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>button</servlet-name>
<url-pattern>/Buttonpage.jsp</url-pattern>
</servlet-mapping> -->
</web-app>
Unable to trace what I am doing wrong.
This is how to send data using $.post
var param = "value";
$.post('query.php', { param: param }, function(data) {
//do what you want with returned data
})

Dynamic Web Project (Eclipse)-->HTTP STATUS 404 Error

I'm making my first java web application following a tutorial on youtube. It is a Dynamic Web Application and the code I've written so far is fairly simple but I'm having an issue with HTTP 404 error.
My web.xml appears as followed:`
<?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>PuzzleProject</display-name>
<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>
<servlet>
<description> </description>
<display-name>MyServlet</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>BackEnd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
`
My Index.jsp:
`<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome, please enter a bunch of words.</h1>
<input type="text" name="words" value="">
<form action = "MyServlet">
<input type="submit" value="Send" />
</form>
</body>
</html>
MyServlet.java:
package BackEnd;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
/**
* Default constructor.
*/
public MyServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter print = response.getWriter();
String string = "My Name Is Steven";
print.println(string);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
`
Can someone please tell me what I'm doing wrong?

Http status 500 Error instantiating servlet class [duplicate]

This question already has answers here:
How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?
(16 answers)
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I'm using Tomcat8 server and i'm getting following error.
It's url is http://localhost:8080/WeatherWebApp When i'm submitting the details then it's giving this error.
Here is WeatherServlet.java class
package org.akshayrahar;
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 WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
WeatherServlet(){
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Here is web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee">
<display-name>WeatherWebApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>
</web-app>
Here is index.html file too:-
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script >
function initMap() {
var input =document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACZhmkSaIz436Dt3kHt_cVEYKN-gHzfYo&libraries=places&callback=initMap"async defer></script>
</head>
<body>
<h1>Find weather of any city in the world</h1>
<h2>Enter City Name</h2>
<form id="form" action="CurrentWeather" method="GET">
<input id="pac-input" type="text" name="cityname">
</form><br>
<div class="button1">
<button type="submit" form="form" value="Submit">Submit</button>
</div>
</body>
</html>
I've also mentioned stylesheet.css file in comment. Please check it.
The error shows that Tomcat is unable to create an instance of your WeatherServlet class.
You should make its constructor and other methods public too. You can even make use of the default constructor by removing the less accessible constructor:
public class WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WeatherServlet(){
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Please provide a fully qualified class name on your web.xml. I was facing a similar issue and this is what fixed it.
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>org.akshayrahar.WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>

HttpServlet mapping doesn't work

I'm using Apache Tomcat v8.0 server and in Java EE application. Basically, I created an ResponseUpload servlet. I need to get JSON data from the web app through POST request. Here it is the code of the Servlet:
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RequestUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = request.getReader();
Gson gson = new Gson();
JSONObject json = gson.fromJson(reader, JSONObject.class);
uplRequest.upload(json);
PrintWriter out = response.getWriter();
out.print(json);
}
Then to test if it works I added a form to jsp file, doing POST to url:
http://localhost:8080/webApp/RequestUpload
The form:
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
But I got 404 error -
HTTP Status 404 - /webApp/RequestUpload
Can somebody show me where is my mistake?
My web.xml file:
<?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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>webApp</display-name>
<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>
P.S. Another form doing the same with RPC servlet (which structure is similar) is working.
After a research and with help of previous answer I found the problem in build path. The build path image
I had to allow output folders for source folder and change the output folder from build to WEB-INF/classes.
Servlet Class:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
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 com.google.gson.Gson;
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<String, String>();
options.put("first_name", request.getParameter("first_name"));
options.put("last_name", request.getParameter("last_name"));
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
JSP:home.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
if your context root of the web app is webApp and server is running on port:8080. you can see the home.jsp as follows:
When data are given in first_name as Minhajur and last_name as Rahman, After clicking the submit button,
following json response will be returned:
Note: make sure that you have added the required jar dependencies in lib folder. For example: gson-1.7.1.jar exists in webapp/WEB-INF/lib folder.
Trouble Shooting:
HTTP Status 404 - /webApp/RequestUpload
-> Check whether your webApp has been compiled successfuly and your compiled RequestUpload.class has been existed on your webapp/WEB-INF/classes directory on tomcat server.
if RequestUpload.class does not exist, then
1) It has not been compiled successfully.
or
2) the Compiled class files has not been moved to webapp/WEB-INF/classes directory.
So, follows the following steps:
i) Clean your tomcat working directory and compile run again and check the class file is existed there.
ii) Delete and Add Tomcat server on eclipse again. then follow the previous steps.
You can also read for further references:
How to use Servlets and Ajax?

In Servlet Post method did not call from html page?

i have problem how to call post method in java.When i pressed click button on login page after that did not show any thing on the browser.please tell me proper solution.my output show on console.so please tell me what is mistake.thanks in advance.
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/loginPage.css" />
<!-- <script src="js/jquery-ui.1.10.4.js"></script> -->
<title>Login Page</title>
</head>
<section class="login">
<div class="titulo">Staff Login</div>
<form action="/AdminLogin" name="AdminLogin" method="post">
<input type="text" title="Username required" placeholder="Username" data-icon="U">
<input type="password" title="Password required" placeholder="Password" data-icon="x">
<div class="olvido">
<div class="col">Register Student</div>
<div class="col">Fotgot Password?</div>
</div>
<button class="enviar">submit</button>
</form>
</section>
</html>
AdminLogin.java
package com.admin.main;
import java.beans.Statement;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
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 com.admin.dao.UserMasterConnection;
#WebServlet("/AdminLogin")
public class AdminLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
Statement stmt;
UserMasterConnection userMasterConnection = new UserMasterConnection();
public AdminLogin()
{
super();
}
public void init(ServletConfig config) throws ServletException {
}
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doget");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
System.out.println("doPost()");
/*System.out.println("dopost");
// connection with database
// Connection connection =
Connection connection = userMasterConnection.getConnection();
String selectTableSQL = "select * from user_detail where username=? and password=?";
try {
stmt = connection.createStatement();
// execute select SQL stetement
ResultSet rs = stmt.executeQuery(selectTableSQL);
while (rs.next())
{
// get username and password from login page
String username = request.getParameter("password");
String password = request.getParameter("username");
System.out.println(username);
}
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}*/
String username = request.getParameter("Password");
String password = request.getParameter("Username");
System.out.println("username :-"+username);
System.out.println("password"+password);
}
}
web.xml
<?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>SBTsystemAdminView</display-name>
<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>
<servlet>
<servlet-name>loginPage</servlet-name>
<servlet-class>com.Admin.main.AdminLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginPage</servlet-name>
<url-pattern>/loginPage/*</url-pattern>
</servlet-mapping>
</web-app>
Get rid of the empty service method override. Its making the servlet do absolutely nothing. Read the documentation for HTTPServlet concerning the service method:
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
Receives standard HTTP requests from the public service method and dispatches them
to the doXXX methods defined in this class. This method is an HTTP-specific version
of the Servlet.service(javax.servlet.ServletRequest,
javax.servlet.ServletResponse) method. There's no need to override
this method.
In other words, the standard implementation of this method figures out whether the request is GET or POST and routes to the doGet or doPost functions. If you override this method, especially with a blank function, then you are preventing the doGet and doPost functions from ever being reached.

Categories

Resources