Can't access a Java servlet through its URL - eclipse

I'm trying to set up a very basic JEE project with Eclipse+Tomcat using a single servlet and JSP. However I'm getting a HTTP 500 Internal Server Error when trying to access its URL http://localhost:8080/test/toto. The exception message being displayed is:
Cannot invoke "javax.servlet.RequestDispatcher.forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)" because the return value of "javax.servlet.ServletContext.getRequestDispatcher(String)" is null.
Here is my Test servlet code:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException{
this.getServletContext().getRequestDispatcher( "/WEB-INF/test.jsp" ).forward( request, response );
}
}
The test.jsp file should just display a message : "Generated by a JSP"
Here's the content of web.xml for reference :
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.sdzee.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/toto</url-pattern>
</servlet-mapping>
</web-app>
The corresponding Tomcat log reads :
0:0:0:0:0:0:0:1 - - [10/Dec/2020:14:29:47 +0100] "GET /test/toto HTTP/1.1" 500 1606
This is the project arborescence
Edit: Other things I recently tried: Reinstall Eclipse+Tomcat on another pc and start again, move test.jsp directly to WebContent and access http://localhost:8080/test/test.jsp: results in a HTTP 404 ressource not found error.
I've just noticed that before I create my servlet I can access whatever file I create under WebContent at http://localhost:8080/test/whatever.jsp but I can't do that anymore once I add the servlet and establish the mapping in web.xml

I was editing the web.xml file of the Tomcat server and not the one of the project, that's why nothing was working as expected.

Related

cloud foundry 404 but local tomcat is fine

First lets get the code out of the way.
index.html in WebContent
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Child Tickets</title>
</head>
<body>
<h1>Find all child tickets affected user and their info</h1>
<hr>
<form name="f1" method="GET" action="/FindChildTicket4/FindChildTickets">
<input type="text" name="masterticket">
<button type="submit" value="main" name="btnSubmit">Hello</button>
<br>
<br>
<div id="results">
results html
</div>
</form>
</body>
</html>
web.xml in WebContent/WEB-INF
<?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>HelloWorld</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>
HelloAgain.java in Java Resources/src/hlo.hello.net
package hlo.hello.net;
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 HelloAgain
*/
#WebServlet("/HelloAgain")
public class HelloAgain extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloAgain() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #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);
}
}
when I deploy this in Eclipse to the local Apache7 server the html fires off and when I click the Hello button I get back the "Served at: /HelloWorld" in the browser.
Now when I push this to our internal Cloud Foundry setup VIA Eclipse I get this when I click on the Hello button
HTTP Status 404 - /HelloWorld/HelloAgain
type Status report
message /HelloWorld/HelloAgain
description The requested resource is not available.
Apache Tomcat/7.0.62
I have tried these sites...
HTTP Status 404 - on Eclipse with Tomcat
Java - Servlet 404 error
Getting HTTP Status 404 error when trying to run servlet
java servlet not found error 404 in eclipse
as well as a few others and non of the recommendations fixes the cloud foundry side. The HTML will work every singe time but it never finds the servlet. I also have looked at the cloud foundry server files I deployed and the class is there under WEB-INF/classes/hlo/hello/net/
Very odd. Also some of the recommendations in the linked sites broke the local apache deployemtn to where the server would shutdown. Just seeing if anyone has any insight since I cannot find any good data when searching for cloud foundry 404.
It appears that you're trying to access /HelloWorld/HelloAgain.
HTTP Status 404 - /HelloWorld/HelloAgain
Your Servlet is configured for /HelloAgain and /HelloWorld is the context (you can see this in the output from when you run locally, Served at: <context>).
When you deploy an application to a local Tomcat, it is typically done under a context and not the ROOT context. The difference is when you deploy to a context, everything is prefixed with that context name. When you deploy to Cloud Foundry, the Java build pack always deploys your application as the ROOT context. This means there is no prefix.
If you have hard coded URLs or links in your application that include the context name they will be incorrect when you deploy to CF and that would generate 404s.
One quick test would be to go to /HelloAgain when you deploy on CF. Since the app is deployed under the ROOT context, it should be accessible at that URL. I suspect you'll see "Served at: /" in the output.
One way to make sure URL's are generated correctly is with JSTL Core's <c:url> tag. Another way would be to build your URL's from parameters on the HttpServletRequest object. I'm sure there are many other ways. You just need to make sure the URL being used takes into account the context of where the application is being deployed.
Hope that helps!

Jersey tomcat and eclipse: error 404

I was following vogella "REST with Java (JAX-RS) using Jersey - Tutorial".
I created a new dynamic web project named "project" generating web.xml file.
I added all jar files from jaxrs-ri-2.23.1 in "eclipseWorkspace/project/WebContent/WEB-INF/lib"
I created a new class named Hello and copied the content from vogella tutorial:
package project;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
// Plain old Java Object it does not extend as class or implements
// an interface
// The class registers its methods for the HTTP GET request using the #GET annotation.
// Using the #Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.
// The browser requests per default the HTML MIME type.
//Sets the path to base URL + /hello
#Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
I modified web.xml in this way:
<?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>project</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>project</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Right click on project name, run as, Run on server. Choosed the existing tomcat v7 server at localhost.
Restarted server.
When i go to:
http://localhost:8080/project/rest/hello
It shows 404 error:
HTTP Status 404 - Not Found
type Status report
message Not Found
description The requested resource is not available.
Apache Tomcat/7.0.70
Do you know how to solve this?
Solved unselecting the option "Build Automatically" in eclipse.
Then "Build project" and "Run on server" and it works.

Jersey REST service

Am using Jersey 1.19 for a REST service..
The URL pattern in web.xml is:
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
In the Java class am using a method which is doing a kind of redirect to another page saved in a web folder. It looks fine up to the point when I call a specific resource:
http://localhost:8084/userProfile/rest/user
This should redirect to:
http://localhost:8084/userProfile/signup/index.jsp
but it redirects to:
http://localhost:8084/userProfile/rest/signup/index.jsp
Which normally doesn't exist.
The method in the Java Class:
#Path("/user")
public class userProfile {
#GET
#Produces(MediaType.TEXT_HTML)
public Response returnForm() throws URISyntaxException {
URI uri = new URI("/signup/index.jsp");
return Response.temporaryRedirect(uri).build();
}
}
How can I avoid redirection to a URL including /rest/?
The solution is/was really simple... the Path should go one step back to
avoid the url-pattern /rest/*:
....
URI uri = new URI("../signup/index.jsp");
...
Thx!

Spring MVC Servlet being hit twice for a POST request

I've got an estrange issue while using Spring MVC in order to implement RESTful services for my web application. Everything seems to work OK while performing GET requests, however, the behaviour I'm dealing with when doing POST requests puzzles me. Well, I've implemented this very basic controller code:
#Controller
#RequestMapping("/services")
public class RestService {
#RequestMapping(value = "/test/post", method = RequestMethod.POST)
public void postTest(#RequestBody String postString)
throws PersistenceException {
System.out.println(postString);
}
}
When I perform a POST request against it using Curl:
curl --data "Hello world" http://localhost:8080/SpringMVC-REST/services/test/post
First time my Controller is reached properly and the String is displayed. However, don't know why, the Spring MVC servlet is being called again after that, in this case with a wrong url request. The framework is not finding the matching service case, obviously:
Jun 02, 2014 4:06:21 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC-REST/services/test/services/test/post] in DispatcherServlet with name 'mvc-dispatcher'
Debugger's stack seems to be slightly different for the first and second cases:
It seems like second time the Spring MVC framework is trying to render the output, even I'm not interested in it, cause I'm not accesing it via web UI. The servlet configuration I use is the standard one:
<web-app id="WebApp_ID" 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
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC REST</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
That happens to me with Tomcat 6 and 7 and spring-web 3.2.8.RELEASE. Can anybody see the problem here?
use #ResponseBody before method return type..it should solve your problem.
so it should be like
#Controller
#RequestMapping("/services")
public class RestService {
#RequestMapping(value = "/test/post", method = RequestMethod.POST)
public #ResponseBody void postTest(#RequestBody String postString)
throws PersistenceException {
System.out.println(postString);
}
}

REST Service - #POST call works while #GET doesn't

I am very new in REST services and I am facing a problem during the last two weeks. I am using Jersey. I am trying to use a simple REST client in order to call a POST method, which accepts a JSON object as a parameter and stores it to a database. My approach didn't work, but I decided to go one step behind, so now I am using an even simpler client with a simpler provider, in order to just test my POST and GET methods. The strange thing is that while I am able to call the POST method:
#POST
#Path("/store")
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String storeData(String str) throws SQLException {
String query = "insert into myDB.test (id, name) values ('1', '" + str + "')";
MyDB db = new MyDB();
db.runQuery(query);
return responseCode.toString();
}
This works just fine!
But in the same class, the #GET method is not working and returns a 404 error.
My code is as following:
#GET
#Path("/retrieve")
#Produces(MediaType.TEXT_PLAIN)
public String getResponse() {
return "Hello!";
}
I know that my question might be quite simple to many... but I'm trying to find out what I'm doing wrong so as to go on to my actual implementation...
Thanks a lot in advance.
Marina
here is my client-side code
public class TestClient {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/server_classes/rest/server/retrieve");
System.out.println(webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, "hello"));
}
}
And here is my 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>server_classes</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>server_classes</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My package is named server_classes and the resource's path is #Path("/server")
I tried the vogella tutorial again, from the beginning, just changing the annotation paths and the methods (for not just giving a "Hello Jersey" response). But now, I am not able to run anything. There is only a 404 error!
O also deleted Tomcat's instance, then the whole tomcat installation and re-installed it, the problem still the same. I am working on Ubuntu 12.04 if this helps..
Thanks!
try to change your request from post to get, as your servlet-mapping expects:
webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);