Is there a way to build Spring Web calls that consume and produce application/json formatted requests and responses respectively?
Maybe this isn't Spring MVC, I'm not sure. I'm looking for Spring libraries that behave in a similar fashion to Jersey/JSON. The best case would be if there was an annotation that I could add to the Controller classes that would turn them into JSON service calls.
A tutorial showing how to build Spring Web Services with JSON would be great.
EDIT: I'm looking for an annotation based approach (similar to Jersey).
EDIT2: Like Jersey, I am looking for REST support (POST,GET,DELETE,PUT).
EDIT3: Most preferably, this will be the pom.xml entries and some information on using the spring-js with jackson Spring native version of things.
In case other ppl get here later:
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
was the most useful link for me. That finally made me understand the model (after less than a day of searching).
You can certainly have controllers that return a View which is in JSON output. Take a look at the Spring-JSON project.
To consume requests in JSON I would assume you would just want a controller to pass a request parameter off to a JSON library which could parse the data?
There is no pre-packaged way to do what you want as Jersey is nicely integrated with Spring via the Jersey-Spring API so there's really no reason to re-invent the wheel.
Check this one out
Adding support for JSON and XML views
Source code for Spring Finance Manager
Since spring-mvc 3.0 official support for Ajax remoting with JSON is provided as part of Spring MVC. This includes support for generating JSON responses and binding JSON requests using the Spring MVC #Controller programming model.
see here
This feature is now part of Spring since version 3.0. You can simply use the #ResponseBody annotation to specify that you want the return value from your request handler methods to be serialized to JSON and sent as the response body. See http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
It seems that DWR framework looks very close to what you want to get.
You can configure Spring MVC interceptors through handler mappings and then use the mappings to transform the returning data to JSON. The handler configuration can be done in xml (no need to recompile), and this can be completely transparent to the rest of the application.
It's fairly easy to annotate controllers with some annotation, and then hook up the BeanFactory bootstrap process to register the controllers within some handler mapping process.
I have used this approach to transform the result from spring controllers into GWT RPC calls.
You can also use Spring AOP to intercept controller method calls and unwrap/wrap the requests from/to JSON.
Related
My company has asked me to do a small project in Java Spring and I have never programmed in Spring nor Java before, so I am a bit lost.
I have been asked to make a series of endpoints, seeing the documentation does not seem difficult, where I find the difficulty is that I always receive as input a JSON with several key-value pairs, and with that, I have to search in an Oracle database using Hibernate and return another JSON with other key-value pairs.
Example:
Input:
{
"client_id": 123,
"shop_id": 22,
"id_contract": 233
}
Output:
{ "loan": "70%"
"percentage_point": "80%"
}
My question is, should I do it through a POST method? Is the output a status 200? How do I get from JSON, for example, the client id to map it in the database with hibernate / Spring?
Any advice will be welcome, even if it is simply articles, etc.
Well what you have been asking is not for a specific problem.It is an entire requirement. I can try helping with the steps that you may need to follow.
If you are not done creating a project, I would suggest you to use Spring Boot for your project.To create a spring boot app click here
And if you are using maven or gradle select it and then search for Spring Web,Spring Data JPA in search dependencies and generate a project.
Once you have a project ready and imported it into an IDE (for example Eclipse, IntelliJ Idea, Netbeans or any other Java IDE), and finally all you have to do is to write REST services to implement your requirements.
And to answer your questions.
should I do it through a POST method?
If you were told that the request you will be receiving is in a JSON format, then you need to use POST method.
What is post and why to use post method.check here
Is the output a status 200?
A status 200 in http means SUCCESS. It means when the data sent by the client is valid and the server has processed the request(in your case JSON body) successfully it returns 200.So incase of success your api will return 200.
More on http status codes
How do I get from JSON, for example, the client id to map it in the database with hibernate / Spring?
To understand more on how to create a rest controller, take JSON input, create a POST method, use Spring JPA for making database operations please follow the links below:
create a rest service
spring boot crud Database operations example from scratch
Spring boot Data JPA example
Hope this will help you to put you in right path.
Without code or a more specific post about requirements it's impossible to help. All I can do is provide links to potentially helpful articles. You need to look into the following;
Spring Boot RESTful service
Spring Boot Controller vs RestController
Spring Boot JPA
Spring Boot Consuming/Producing JSON
I am migrating a Spring MVC library to Spring WebFlux. There is a feature that lets our clients annotate their controller methods to perform custom validation (and applying some business rules) on incoming headers before granting access to the API.
In Spring MVC we had that accomplished by using HandlerInterceptorAdapter. Since WebFlux doesn't have anything similar I was trying out the solution as suggested by Rossen here. However it doesn't work for this use case since the method handler info is only available in onSuccess operator and its too late to get the info for annotation processing.
I was trying out the other approach suggested there using #ModelAttribute method on a #ControllerAdvice but that only work if the annotation is applied to the Controller class in our case the annotation is applied on methods of controller class.
Here is a sample https://github.com/ranarula/handleInterceptor with the issue
Any pointers on how to go about implementing the annotation processing in WebFlux will help.
I use spring mvc
I have controller for rest web service
Sometimes I want to returns xml, Sometimes - json. In classPath I have and jackson and jaxb
How I can switch between them?
What you want is the ContentNegotiatingViewResolver:
http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html
You'll need ContentNegotiatingViewResolver. Please check Spring documentation
on the matter especially the Returning multiple representations section.
We've got some Pure Servlets (pure Java classes following the Servlet API, no framework) that we'd like to include in a project that relies heavily on the Spring Framework.
What's the best way of including these servlets in the project, when all the new code we're writing is making heavy use of Spring 3 features?
your servlet container can run multiple servlets, spring is just one of them. why not just include your servlets in the web.xml and see if it works? it should work. spring is not that intrusive, yet (but obviously it already intruded the minds of many developers)
If you declare servlets in the web.xml, alongside the Spring front controller, it most certainly will work.
You just have to be careful when you declare which URLs map to the servlets. If you send "/*" to the Spring front controller, none of your requests will reach your other servlets. Be specific about what you need to send to each one.
As you might know, servlets cannot be configured as Spring beans. If your question is about colloborating with spring beans from a servlet, do refer this thread and also this
Spring provides a couple of classes to make this bridging easier.
ServletForwardingController
Spring Controller implementation that
forwards to a named servlet, i.e. the
"servlet-name" in web.xml rather than
a URL path mapping. A target servlet
doesn't even need a "servlet-mapping"
in web.xml in the first place: A
"servlet" declaration is sufficient.
Useful to invoke an existing servlet
via Spring's dispatching
infrastructure, for example to apply
Spring HandlerInterceptors to its
requests.
ServletWrappingController
Spring Controller implementation that
wraps a servlet instance which it
manages internally. Such a wrapped
servlet is not known outside of this
controller; its entire lifecycle is
covered here (in contrast to
ServletForwardingController).
From what I know of MVC outside of the Java world (PHP and Ruby on Rails), all requests are first sent to the front controller (or dispatcher... or boostrap, etc.), and the front controller looks to the request path pattern in the URL in order to determine what class/method should handle the request. In Java MVC, it appears that servlets are mapped with the url pattern in the deployment descriptor (web.xml), but the file extension and url pattern doesn't appear to be very flexible. Are there any Java MVC frameworks that use a front controller to read the request path exclusively to determine what classes should execute? Would it be fairly easy to hack Spring MVC to do this? Any examples? Thanks!
An example of one tool that works as you desire is web4j.
By default, it maps incoming URLS to the Action class whose package-qualified name maps in a fairly natural way the the incoming URL.
Example from its docs:
Request URL: 'http://www.blah.com/fish/main/member/MemberEdit.list'
Extracted part of URL: '/main/member/MemberEdit'
Maps (by default) to the Action: 'hirondelle.fish.main.member.MemberAction.java'
This is an example of how that particular tool performs the task. Since this is such a basic feature of web apps, I would imagine that nearly all such tools have similar mechanisms.
I am not a big user of Spring, but I can see from its docs that it has a number of ways of mapping requests to Actions :
SimpleUrlHandlerMapping
ControllerClassNameHandlerMapping
Java servlet mappings can also be by file extension.
Much like many non-Java frameworks, you could map all requests to a single servlet that then processes them but that tends to be discouraged in Java. It's certainly possible though.
If you want more REST-style URLs where you declare the mapping of path elements, you might want to look at the Spring MVC setup in Spring 3.0.
I agree the URL mapping is not very flexible but you can handle mapping with URLRewriteFilter
http://tuckey.org/urlrewrite/
For this purpose, the filter works almost like a controller.
Check out stripes:
http://www.stripesframework.org/display/stripes/Quick+Start+Guide
I've been looking at it as a possible upgrade from struts. There is an example on that page that is very similar to the web4j example given by John O.