Class Not Found when executing Java Web App - java

I'm very new to the Java landscape (Eclipse, Spring, etc.) and just walking through some introductory tutorials at the moment. I just finished a Hello World tutorial for Spring MVC, with a simple page that then posts to another action. Straightforward enough.
I then went on to tinker a bit with the working result of that tutorial. My first attempt is to create another project in Eclipse with just some simple packages containing POJOs. The idea being to have something portable which different applications could use. (Intended to be the equivalent of a "Class Library" project in the .NET world.)
That project has one package, with one interface (IWorld) and one class (HelloWorld). In my Spring MVC project I then add the other project to the build path and create an instance of that object in the controller. The compiler says everything's fine:
package com.sandbox.application.mvctest.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.sandbox.domain.models.*;
#Controller
public class HelloWorldController {
#RequestMapping("/")
public String hello() {
IWorld world = new HelloWorld();
world.speak();
return "hello";
//TODO: Return a ModelAndView instead
}
#RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi(#RequestParam("name") String name, Model model) {
String message = "Hi " + name + "!";
model.addAttribute("message", message);
return "hi";
}
}
The .speak() method doesn't do anything of note, just returns a value which the controller isn't using yet. The intent of course is to start building up some features in the models rather than just in the controllers and views, building more of a rich domain model.
Eclipse doesn't complain about the code, everything seems to compile just fine. But when executing on Tomcat I get an exception:
Jul 05, 2017 12:36:49 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [springDispatcher]
java.lang.ClassNotFoundException: com.sandbox.domain.models.IWorld
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
at java.lang.Class.getDeclaredMethods0(Native Method)
[and so on...]
My Googling has proved fruitless so far, likely because I don't always understand what I'm finding. For example, there are some posts which advise to correct something in a pom.xml file. I have no such file. Is this related to Spring's dependency injection? Should I be using that? I wouldn't have considered this to be an injectable dependency, I'm just creating an instance directly. But then I'm also approaching this from a deeply dogmatic .NET mindset, so all bets are off.
What am I missing here?

If I understand your question properly then you are expecting the project class-path and the web app class-path to be the same. All the dependencies would not be exported automatically when the web app is deployed. You can check the deployed web-app's WEB-INF/lib folder for your dependencies.
If you are using Tomcat as your servlet container then you can add the dependency jars in Tomcat's lib folder and then it should work.

you are using springframework, so you can create the bean of the com.sandbox.domain.models.IWorld and use the #Autowired tp Dependency Injection. refer code
#Autowired
private IWorld world;

Related

How do I get a sample Spring Boot server running on my existing website?

I'm trying to develop a web application as a side-project on my own. I'm a long-time code monkey, but I've never done much with project infrastructure, and my inexperience is showing.
I've decided to learn Spring Boot; I'm not familiar with the framework, but I've done a lot with Java, so it seemed like a decent choice. I'm following the Getting Started tutorial (https://spring.io/guides/gs/serving-web-content/), and have created the necessary files.
I have the files on a "demo" subdirectory on my existing website, blairhippo.com. I started the application via ./mvnw -e spring-boot:run, and all looks well; I get a bunch of info messages, including this guy:
2022-07-10 19:49:02.991 INFO 54726 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
So as far as I can tell, everything is running.
Except I can't actually get to the application.
According to the tutorial, the path /greeting should get me to my "Hello World" message. But the URLs that seem most likely (http://blairhippo.com:8080/greeting, http://blairhippo.com:8080/demo/greeting) don't actually do anything.
Is there a config file that needs some attention? What do I need to do to get this running on my server?
EDIT: Responding to Shivaji Pote below:
Thank you very much for the help. The host name is blairhippo.nfshost.com, and that DOES load a page (amusingly, one with no CSS defined). However, none of https://blairhippo.nfshost.com:8080/demo/greeting, https://blairhippo.nfshost.com:8080/greeting, or https://blairhippo.nfshost.com:8080 will return anything (and I've double-checked that the Tomcat server is running).
Both ./target/classes/application.properties and ./src/main/resources/application.properties exist, but are empty.
And the GreetingController.java code is boilerplate from the tutorial:
package com.example.servingwebcontent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class GreetingController {
#GetMapping("/greeting")
public String greeting(#RequestParam(name = "name", required = false, defaultValue = "World") String name,
Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
I think your blairhippo.com is running on different server(same machine but different application server) than sprig boot. When you run command ./mvnw -e spring-boot:run, it launches new server(tomcat) on some port(default 8080). So your spring boot application is running independently on same machine as your blairhippo.com server. If you check the hostname of your that server and access url http://<your-hostname>:8080/greeting, probably it will work. If it doesn't, share your controller definition, application.properties and blairhippo.com hostname.

How to create simple RESTful service in IntellijIDEA 2016? (JAX-RS)

My google-fu has failed me.
I have lost 2.5 hours trying to figure this out. I just want to make this simple RESTful service with get and post requests that generate hello world on get (i.e. localhost:9000/hello ) and on post prints to service console what was sent in bla variable.
I have found some simple examples
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Path("greeting")
public class Greeter {
#GET
public String sayHi() {
return "Hi!!";
}
}
But it doesn't work intellij doesnt recognize Path and GET annotations. It asks me if I want to implement them. I've tried on both NewProj->JavaEE->Restful Web Service and NewProj->Java->WebApp->WebServices.
Some sample generated code from one of them made this #webmethod annotation for which I wasn't able to find any info on the net. And the JetBrains video from 2013 looks like an overkill/a-bit-outdated?. This is really simple app, I don't need/know how to use/ Maven.
You need to download the jar-file containing the classes you have imported (from e.g. http://download.oracle.com/otndocs/jcp/jaxrs-2_0_rev_A-mrel-spec/index.html).
Open Project Structure, Go to Libraries, press the plus button, and add the jar-file to your project.

Open html file on Tomcat server in Restfull web service

I hava a small web service which is running on tomcat server and i want to open my html file on my tomcat server.
My web service is:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() throws Exception {
String url = "E:/this.html";
File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());
return "Got it!";
}
}
These answers are based on the potential questions in the comments section of the question.
Q: Which url do I put in your browser to see the message "Got it!"?
A: http://localhost:8080/myresource
However, that might not be the exact case for you. There are lots of ways of setting up a web container (like tomcat) and you will have to verify what port you're running on and what your servlet context is. The above answer assumes that you are running on your local machine, under port 8080 (which tends to be the default for java web servers) and under the ROOT context.
A more complete answer would be:
http://<host_name>:<port>:<context>/myresource
Q: How do I allow the End User to say which file they want to download?
A: This is a HUGE security risk. Allowing an End User to enter a path to a file on the server is just not smart. No offense...
The End User could just enter {/etc/passwd} and depending on which system user was used to start your web container, the web container will serve that file. Not a good situation.
Q: Ok, great, so how do I allow a user to download a file from my web container?
A: There are several ways of doing this and I won't go into great detail, but, you could allow the container to serve the files themselves directly. Meaning place the files inside of the /webapp directory itself. Then your web container will serve them automajically.
You could set a directory in your MyResource classes constructor and only serve requested files from that particular directory. You would need to do some serious validation on End User input to verify that they aren't asking for a file like this: ../../../../etc/passwd
Q: FINE, got it, so I'll do validation, NOW, how do I actually serve the file to the End User? I promise I'll be careful...
Well, that is easy, just go take a peek at this question here:
what's the correct way to send a file from REST web service to client?

404 on GET request to Servlet

I have been trying for 3 days now to create a Java EE project, that uses JSP, Servlet and EJB in a single project, as I need to do a course final assignment on this.
We were instructed to use JBOSS 4.2.3, and so that is what I try to use.
I set up my environment as follows:
http://community.linuxmint.com/tutorial/view/1372
Install IntelliJ Idea 13 Ultimate.
Download JBOSS and prepare a directory to use.
After those 3 days of hard work, I managed to get a sample app, created by this tutorial:
http://wiki.jetbrains.net/intellij/Developing_and_running_a_Java_EE_Hello_World_application#The_Hello_World_Java_EE_application
Now, the application compiles, I get the index.jsp on: http://localhost:8080/webWeb/
However, I get a 404 error if I click it, and submit to http://localhost:8080/webWeb/helloworld
I dont know what else to try, I think I Googled and read pretty much everything :(
Here is a link to the Project archive, so that you could (potentially) test out my project, see if you can solve this problem somehow...
https://www.dropbox.com/sh/9sma5vh7usy2h3p/AADA64KPyLH29iGz8OamWyNna
Thanks!
UPDATE:
For convenience, my HelloWorldServlet.java code:
package myservlets;
import mybeans.HelloWorldBean;
import javax.ejb.EJB;
import java.io.IOException;
#javax.servlet.annotation.WebServlet(name = "HelloWorldServlet", urlPatterns = "/helloworld")
public class HelloWorldServlet extends javax.servlet.http.HttpServlet {
#EJB
private HelloWorldBean helloWorldBean;
protected void doPost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, IOException {
}
#Override
protected void doGet(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, IOException {
String hello=helloWorldBean.sayHello();
request.setAttribute("hello",hello);
request.getRequestDispatcher("hello.jsp").forward(request,response);
}
}
I feel I really must add, that this extreme difficulty of setting up Java to just work and allow me to focus on CODING, is the reason I prefer something like PHP, which just works for example... Am I wrong?
The problem is that you're using JBoss 4.2.3 which works with Servlet 2.5 / JSP 2.1 (as noted by BalusC here: Servlet Spec for Jboss 4.2.3). Usage of #WebServlet and annotations is supported since Servlet 3.0. So, you have to configure your servlets directly in web.xml file.
Note that servet 2.5 doesn't support EJB injection either.

Eclipse Web Service: how to get current path

Sure this question has been asked some times already. Still, I don't get the right answer until now.
Using Eclipse, I did the following steps:
Create Dynamic Web Project
Implement my service class
Create new Web Service
It all works and the service more or less starts. Apparently, a WSDL (which I will use later) is generated as well.
In the constructor of my service implementation, I'm desperately trying to read a custom file - which resides in WebContent
I'm not very experienced at creating web services. But I'm using Tomcat 7, Axis 2 and some JPA. In any case, I cannot access the ServletContext class. I'm not implementing my own servlet either.
I tried all of these:
1
`new File(".").getAbsolutePath()`
--> returns my own home directory.
2
#Resource
private WebServiceContext context;
....
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
--> context is always null. I found somewhere, that this is only injected after calling a first service method. Not really my solution.
3
Don't have the code handy anymore, I used some snippet with NIO. Gotta find it... Didn't work either.
If you are trying to read a file in the service, you can place it in the package and access as a resource.
InputStream is = className.class.getResourceAsStream("filename.xml");

Categories

Resources