I want to set up an application using RESTful principles and Spring. I found out the RESTemplate for the client-side but I don't know how to configure the server. First I want to create a simple application in which the server simply respond with an Hello {name} string after a myserverapp:8080/{name} request. Can someone help me, maybe with Java code? Thanks.
It really does sound like you need to read the Spring docs and have a look around for examples on the internet (there are a lot)!
Here is one which I think it very clear and straightforward to get you started.
You need to start researching a little bit via google.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#rest-resttemplate
sample:
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String delete(#PathVariable("id") Integer id)
Might also want to look into using Jersey, allows you to decouple your web layer from your REST layer. Using Spring's method, you need to init a controller etc. can take away from what the purpose of a controller is serving.
I have used both technologies, and it really depends on what you want to do, currently I'm writing an app using backbone.js which uses Jersey to serve up the REST, and Spring MVC as a front end to render the jsp pages.
Related
I have built a web app using Spring 4. The app allows search users, create elements and so on.
The requirements changed. Now I have to deliver search results as json instead of html (but keep html just in case).
The question is, should I use controllers and redirect to a jsp with json/html according a parameter? or use Spring restful web service?(I've never used this and need to learn how to) if I use Spring restful do I have to do the same job I've already did with the web version to generate json?
It depends on how did you design your previous MVC application.
My suggestion is follow:
But better to use Spring REST Controller. Mechanism is more or less same like MVC. I assume you have service layer for CRUD data of your application.
Better to use those Service and Repository and just create #RestController for your application. #ResponseBody should be your models which are you returning from controller. And #RequestBody will hold the data for generaly POST, PATCH, DELETE requests.
Good luck.
I have a spring mvc application which i use as only a server. I have deployed some html and javascript files on my hosting account and sending post requests to my server only. Retrieve data from database and send back the data to the html or javascript pages. I don't use any servlets,jsp or jsf. Everywhere i look it says that i should use them however. Am i doing something wrong? It feels like bad practice but i don't know the right way to do it i guess. Any help would be appreciated.
As I already mentioned in my comments, you can look into creating a webservice. Since you are using Spring already, try this guide on Building a RESTful Web Service.
After creating the service, you can call it up like this, where you pass in input parameters to your rest endpoints,
http://localhost:8080/greeting?name=User
Now your service will respond back to your GET request and you'll be output a JSON/xml string which you can process later at the client side. The sample json response looks like this,
{"id":1,"content":"Hello, User!"}
Here's another example blog article on Spring Restful Web Service Example with JSON, Jackson and Client Program
Well, I think you should first expand your question a bit since one needs to assume a lot to give you an answer.
IMO, JSF is not great and there are other better options for UI and JSPs are dead. But I'm biased since I used last time JSF 1.X and then went with Spring MVC and Angular or Spring and Apache Wicket more recently.
I used for instance Spring MVC to implement an HTTP RPC API with JSON payloads to which an Angular frontend connected and it worked just fine. I also had the feeling that everyone is doing that nowadays:).
I also guess you are using at least one servlet to configure Spring DispatcherServlet. Right?
I have a general question on a topic I am starting to learn, but having difficulty imagining the specific implementations for.
I want to implement a service broker for Cloud Foundry. The service broker API is as follows:
http://docs.cloudfoundry.org/services/api.html
I'm new to web programming. I have worked with web applications where I publish html files which reference servlets. But I'm not sure how one goes about implementing, for example:
Route
GET /v2/catalog
I was wondering if someone could give a high level rundown of what is involved in doing this. How do I implement a "path" like this? Let's say I wrote a servlet which hangs around at site.com/Servlet. The service broker will call site.com/Servlet/v2/catalog. How would my Servlet understand this? Would this URI even direct to my Servlet as written? I'm using Liberty (Websphere), but any answer would be useful.
I suggest using the Spring framework - website at https://spring.io/. It might take a bit of learning to understand what Spring is (it has many components that do different things), but Spring provides tools to make writing REST APIs very easy. Spring is well documented, has tons of users, and is quite modern.
For a REST API in Spring, you'd define a "Controller" class that controls incoming HTTP calls to the port you program is listening on.
For your concerns about how your programs understands a GET call to a particular endpoint - Spring provides the #RequestMapping annotation to do exactly this task. Within a class you've annotated with #Controller, you will have the #RequestMapping annotation over a method like this:
#Controller
public class CloudFoundryController {
...
#RequestMapping(value = {"/servlet/v2/catalog"}, method = RequestMethod.GET
public HttpResponse getV2Catalogue() {
...
}
}
When this application detects an HTTP GET request with "/servlet/v2/catalog" as the URL endpoint, then Spring will ensure that the getV2Catalogue() method is called. When the method returns, Spring sends back, over the network, an object of whatever type you've defined in the method header as an http response.
Building a REST service with Spring: https://spring.io/guides/gs/rest-service/
I am designing a Java web application that will be deployed to the Wildfly or Tomcat (not decided yet).
Basically it's about the offline java application that needs a REST interface for communication (to accept JSON data). The idea is that application runs all the time and processes the requests stored in redis cache (where the received JSON data is stored).
I used the Spring MVC framework for a web site in the past but I don't need the MVC pattern for the REST interface.
Is there a way you can point me to for using a Spring framework (or some other Java framework) to add the capability to recieve a POST requests to the existing offline application? Or it will be better to just write the REST service that will use the same cache as the existing application?
To illustrate my question I am attaching the simplified diagram of the architecture I am looking for:
As soon as you speak of receiving a POST request, you are automatically referring to a HTTP server.
The question is just whether that server is running as a service, or on-demand.
Is there a way you can point me to for using a Spring framework (or some other Java framework) to add the capability to recieve a POST requests to the existing offline application?
Not without introducing some sort of HTTP container, no.
Or it will be better to just write the REST service that will use the same cache as the existing application?
Yes, exactly. And as another mentioned, personally I'd stick with Spring MVC. But Jersey should also work very well for you for your usecase.
I think you should use any light ESB, like Camel, Mule or Spring Integration. If you have already worked with Spring probably the latter will be the easiest for you.
The purpose of this kind of apps is to facilitate the task of communicating anything with anything (on this case, an HTTP endpoint with your offline app).
Take a look at this:
https://www.google.ie/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=spring%20integration%20http-inbound
You can use Spring MVC for that.
The Model are your domain classes, the View is JSON in this case, and the Controllers handle the requests to perform logic operations, business as usual.
You can also take advantage of Spring's #RestController annotation to quickly create your endpoints, like in this java example:
#RestController
public class MovieController {
#Autowired
private MovieRepository movieRepository;
#RequestMapping(value = "/movies/{search}", method = RequestMethod.GET)
public List<Movie> findMovies(#PathVariable String search) {
return movieRepository.findByName(search);
}
#RequestMapping(value = "/movies", method = RequestMethod.POST)
public void postMovie(#RequestBody Movie movie) {
movieRepository.save(movie);
}
}
Answers from Andres, ESala and kervin pointed me to the right direction but the solution I found most suitable was:
implementation of REST services using Spring MVC and
transformation of the main process from the existing application to the Spring scheduled task.
Basically I need webservice where client can request with id one boolean value from our webservice. What technology would be most suitable for this small API? Of course it is possible that there will be more functions to interface, but now we need only one function. It also needs to have authentication, so that only auhtorized clients can access service. And every client have different auth credientials.
What would be good technology for this purpose?
I am using resteasy to build my webservices and it is pretty easy to use ... just need to use annotations on my methods to deliver the webservices.
Here is a comparison of different JAX-RS frameworks. Take a look at it
First of all: authentication and authorization. Don't do it yourself, pick an app server or servlet container and configure it to do the job.
For the web service....
The simplest thing to do it just implement a servlet that responds to a POST (not a GET if request modifies internal state) and returns the result in the body. This way you don't need any frames works, no learning to do (if you already know servlets). The downside is it won't scale as you add more features, and your not using enough buzz words.
If you want a SOAP based webservice, then look at JAX-WS. Now that it's backed into java 6 it's pretty easy.
At the simplest level JAX-WS lets you put a few annotations on your class, like #WebService, and it auto generates a wsdl and exposes an instance of your class via the web service.
There is plenty of documenation out around how to do it:
http://java.sun.com/webservices/docs/2.0/tutorial/doc/
http://www.java-tips.org/java-ee-tips/java-api-for-xml-web-services/developing-web-services-using-j.html
http://cwiki.apache.org/GMOxDOC20/simple-web-service-with-jax-ws.html
JAX-WS + any servlet container (Tomcat is usual choice)
#WebService(targetNamespace = "http://affinity.foo.com", name="RewardsStatus")
#SOAPBinding(style=SOAPBinding.Style.RPC, use=SOAPBinding.Use.LITERAL)
public interface RewardsStatusIF {
#WebMethod(operationName="GetLastNotificationDate", action="urn:GetLastNotificationDate")
#WebResult(name="return")
public Date getLastNotificationDate() throws AffinityException;
...
Actually, you don't even need a servlet container. JAX-WS has a way to run the service under a standalone Java application. It has some limitations (I have failed to make a stateful service work), but it's
very simple to create.
Given that you tagged your question as "Java", I suggest Jetty. It is a very good small servlet engine. It has support for sessions, so adding authentication should not be a problem.
If you are using Java 6, there is already a HTTP Server builtin, it supports Http authentication. That's all you need. Check out,
com.sun.net.httpserver
You could use some restful framework like jersey.
An alternative to SOAP-based web services with JAX-WS would be JAX-RS (for RESTful web services).
We have a lot of scenarios on our project where we want small amounts of data available via simple HTTP URLs while the app is running and in my experience, Restlet (http://www.restlet.org/) seems to be one of the easiest things available for setting up simple "web-service"-like interfaces (RESTful interfaces) within Java apps.