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.
Related
I'm new to the micronaut framework, and I'm trying to get a simple web-app working. The app has one Controller "TestController", with two GET endpoints; one with a parameter and one without:
#Controller("/api/tests")
public class TestController
#Get
public HttpResponse<String> getAll()
#Get("/{id}")
public HttpResponse<String> getUserProfile(#NotBlank #PathVariable("id") long id)
This is just the class and method sigatures
I've generated the initial application code using the Micronaut Launch web-site (https://micronaut.io/launch/), selecting maven and JDK 1.8.
I compile and run the app using "mvn clean compile exec:exec" or "mvn mn:run".
When I attempt to call the endpoint with no parameters: "GET http://localhost:8080/api/tests"
I get: "More than 1 route matched the incoming request. The following routes matched /api/tests: GET - /api/tests, GET - /api/tests"
When I attempt to call the endpoint with a parameter: GET http://localhost:8080/api/tests/1
I get: "Page Not Found"
I'm running on Windows 10, using eclipse Version: 2019-12 (4.14.0) and JDK version 1.8.0_121-b13.
I've modified the POM to include for various micronaut processors. I've installed m2e in Eclipse and selected "Auto configure JDT APT" for annotation processing.
I would be grateful for any assistance on getting this simple application running. I've uploaded the source to Git Hub on https://github.com/phillwatson/upstart-failures
#JeffScottBrown Thank you for taking the time to look at this. Very much appreciated. Your example led me to the solution, although not quite as simple as using 2.0.0.RC2.
The cause of the issue was my inclusion of the micronauts.jaxrs library. Which, comparing your pom, you didn't have. I'm guessing that the jaxrs annotation processing was causing confusion with the micronaut http annotation. Whatever the underlying cause, removing any reference to jaxrs solved the issue.
Thanks again.
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;
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?
Short version: A restful spring web service crashes when I include a dependency: com.google.gdata: core: 1.47.1
Long Version:
I was trying to make a restfull web service that consume certain information from a spreadsheet in google drive
this is my sequence of steps:
preparing classes that made the connection and the data obtained from drive (not web, only backend classes, unit and integration tests included): all ok
prepare a restfull web service with spring, basically download a spring tutorial (http://spring.io/guides/tutorials/rest/3/) and execute: all ok
then remove tutorial's business classes and include my components, change controllers to invoke my components, plus add gdata dependence in file graddle.build, try execute: houston we have a problem
It's strange, when start app context, log print something like this:
C:\Users\Grubhart\Documents\proyectos\error_Rest_Gdata\complete\src\main\java\com\yummynoodlebar\config\WebAppInitializer.java:39: error: can not find symbol
servletContext.setInitParameter ("defaultHtmlEscape", "true");
^
symbol: method setInitParameter (String, String)
location: Variable of type ServletContext ServletContext
but when the rest app is just downloaded (whitout my code, neither gdata dependency) it works, the only thing I did was add my code and the google api dependence, so I started to see what could cause the error
remove all my code (but leave the gdata jar) and... wait for it.. same error,
remove gdata dependency: it works
then add gdata dependency again and test: the same error again
So I think that by including the gdata jar does something that prevents start the entire app context
I created a repo on github to illustrate the error:
https://github.com/Grubhart/error_spring_restWS_gdata
the master branch has the code of a service that works without gdata dependence
gdata_error branch as you can imagine has added gdata dependency (only dependency, no extra code) in gradle.build file:
compile 'com.google.gdata: core: 1.47.1'
and presents the error
no need install anything (even gradle) only have jdk, download the code and run it as stated in the readme file to see errors
i do my homework, look in google, stackoverflow (great site!), spring forum but can't find nothing
if anyone has experience with this problem, or know where i can found more information would be great if you can share experiences or if you know where to look for more info about this error
The original post doesn't contains:
yummynoodlebar\config\WebAppInitializer.java:39: error: cannot find symbol
servletContext.setInitParameter("defaultHtmlEscape", "true");
ServletContext needs import javax.servlet.*; Maybe the error is for that.
Since the spring context configuration in java classes for web applications works with Servlet 3.0 maybe you have overwritten troubles between some dependencies that comes with gdata which may do use of dependencies other than the servlet version you are using to deploy the application or which it was originally configured, I hope this helps you!.
I'm new to Java. I have a Java project. It runs perfectly on my Windows 7 machine. I want to use some of the functionalities of this project as Web Services to be able to use them in my Silverlight app. Both the Silverlight app and this Java project would be on the single server machine. The problem I have is that when I right click on the project there's no Web Service in the New menu. What should I do to add a web service to my project? Thanks.
Based on the article I linked in the comments above :: http://www.ibm.com/developerworks/webservices/tutorials/ws-eclipse-javase1/index.html
With the JWS annotations you can setup a Web Service in your java application to expose some of its functionality. There is no extra libraries needed. The below examples were written with Java 6.
An example of Defining your web service :
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public class MyWebService {
#WebMethod
public String myMethod(){
return "Hello World";
}
}
Note the 2 annotations of #WebService and #WebMethod. Read their API's which are linked and configure them as required. This example will work without changing a thing
You then only need to setup the Listener. You will find that in the class javax.xml.ws.Endpoint
import javax.xml.ws.Endpoint;
public class Driver {
public static void main(String[] args) {
String address = "http://127.0.0.1:8023/_WebServiceDemo";
Endpoint.publish(address, new MyWebService());
System.out.println("Listening: " + address);
}
}
Run this program and you will be able to hit your web service using http://127.0.0.1:8023/_WebServiceDemo?WSDL. At this point it is easy to configure what you want to send back and forth between the applications.
As you can see there is no need to setup a special web service project for your use.