HttpServlet mapping doesn't work - java

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?

Related

404 Apache tomcat in a Java project

So this is my project:
Where Registro.java is:
package Ejer2;
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;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And registro.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
When I run registro.html everything goes as expected:
But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:
What can be the problem?
I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
<servlet-name>RegistroServlet</servlet-name>
<servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistroServlet</servlet-name>
<url-pattern>/Registro</url-pattern>
</servlet-mapping>
I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem

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>

404 error while running jsp

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

404 with simple java servlet/html form [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
ED: this question is not a duplicate. the alleged duplicate makes no mention of the error that was in my console, and the solution to my problem is not found in the linked question.
i'm using derek banas's tutorials to learn servlets right now. or at least, i'm trying to! i keep encountering a 404 error when i submit my form.
here is my code. first, the java class:
package helloservlets;
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 Lesson41
*/
#WebServlet
public class Lesson41 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String usersName = request.getParameter("yourname");
String theLang = request.getParameter("Language");
int firstNum = Integer.parseInt(request.getParameter("firstnum"));
int secondNum = Integer.parseInt(request.getParameter("secondnum"));
int sumONum = firstNum + secondNum;
response.setContentType("text/html");
PrintWriter output = response.getWriter();
output.println("<html><body><h3>Hello " + usersName);
output.println("</h3><br />" + firstNum + " + " + secondNum);
output.println(" = " + sumONum + "<br />Speaks " + theLang + "</body></html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
my web.xml file:
<?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">
<servlet>
<servlet-name>Lesson41</servlet-name>
<servlet-class>helloservlets.Lesson41</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Lesson41</servlet-name>
<url-pattern>/Lesson41</url-pattern>
</servlet-mapping>
</web-app>
and my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="http://localhost:8080/Lesson41/">
What's your name?<br /> <input name="yourname" /><br /> First
Number <input name="firstnum" /><br /> Second Number <input
name="secondnum" /><br /> <input type="hidden" name="Language"
value="English" /><br /> <input type="submit" />
</form>
</body>
</html>
in my console, i am getting this warning:
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Lesson41' did not find a matching property.
and that's the only warning i'm getting. i googled it and followed the advice i found here, but it hasn't fixed my problem.
thank you in advance for any help!
Are you sure the url in the form is correct? http://localhost:8080/Lesson41/
If you are using Eclipse, by default it deploys your application as http://localhost:8080/[Your-Project-Name-Here]/Lesson41/

JSF 2.0 call server side method on page load

let me give you an idea about how the system works.
I am using JAAS login module for login and role management. I can access specific pages depending on the role i have.
I type my url in the address bar, hit enter.
The login page appears and after correct login, it redirects me to the correct page(for now lets call it page1.jsf).
I want to call a server side method on page load.
Can you help me please?
** EDIT **
Assume i have to access page1.jsf which is accessible to role1 only.
In the address bar, i type http://localhost:8080/myapp/page1.jsf
JAAS shows up the login page and after correctly inputting the credentials, i am redirected to page1.jsf
As soon as page1.jsf is requested or on page load, i want to call a server side method from my class to reload page1.jsf
If you are using JSF 2, you can use the above page snippet:
<html xmlns="http://www.w3.org/1999/xhtml"
... >
<f:view contentType="text/html">
<f:event type="preRenderView" listener="#{permissionManager.checkRoles}" />
<f:attribute name="roles" value="ROLE" />
...
</f:view>
</html>
you can add an attribute containing the role and in the PermissionManager.checkRoles() perform redirect to the corret page.
#Named
#ApplicationScoped
class PermissionManager {
...
public void checkRoles(ComponentSystemEvent event) {
String acl = "" + event.getComponent().getAttributes().get("roles");
//Check user role
...
//Redirect if required
try {
ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) context
.getApplication().getNavigationHandler();
handler.performNavigation("access-denied");
} catch (Exception e) {
...
}
}
}
Check out this example
and take a look at this related question
Yes this works. Instead of accessing a jsp or jsf page, you can also access Servlets. So create a new servlet. E.g.:
import java.io.IOException;
import javax.servlet.ServletException;
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;
public static void yourMethod() {
// do something useful
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
yourMethod();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Then create a new entry in the web.xml file, in order to map the Servlet to /.
<servlet>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>your.packages.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
After this, you should be able to call localhost:8080/TestServlet which then calls your method.

Categories

Resources