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.
Related
We are starting a new project using Spring MVC, and we would like to move away from annotation-driven request/url mapping. We wish to implement the following use case:
Use Case A
User enters a URL.
The request mapping handler retrieves a list of mappings (e.g. from the DB), and based on this dynamic list of mappings, it calls the relevant controller.
This is because we want to be able to do the following as well:
Use Case B
We want to load a new Controller (perhaps a new reports module) into the web app without having to redeploy or do a server restart.
We will map this new Controller to a URL and persist it somewhere (most likely the DB).
We would like the Controller to be registered in the Spring app context (managed by Spring).
We would then like to use this new Controller in the request mapping.
We've taken an initial look at the different ways we can implement this, but we are unsure of the best architecture/method to go about this route. A couple of questions:
For Use Case A, how do we implement this within the Spring MVC framework (or if it's possible)?
For Use Case B, is there a good framework or way to be able to do dynamically loading and registering of this for web applications? We've taken a cursory look at OSGI but it seems to be advisable for use in non-web applications.
For Use case A :
Instead of DB you can keep the url mappings in a property file and then use property place holder to initialize beans using xml configuration on context up. This way remaining inside the spring framework, you can avoid annotations.
For Use Case B :
Tomcat supports dynamic reloading of classes but that to of only non structural changes in class file. But this has memory leaks as well as it doesnt cleans up old instance of class loader rather it creates a new instance.
Its quite achievable using spring-mvc-router API.
Please check below link
url-action mapping & routing in Spring MVC 3.0
Here the URL can be configured to controller.method using .conf file, but this can be achievable using java configuration, and i haven't tried so far.
Also if xml configuration chosen, then check out the property 'autoReloadEnabled', but its not adviceable for production use.
Hope this helps!!!
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.
I'm developing a web application using Spring MVC 3.0 and looking for a ready-made solution, if any, or a "best practices" reference for a url/action mapping and routing system that can achieve the following:
REST-friendly controller / method name to view mapping. The current mapping implementation translates the request to a view name, which may be problematic when using several parameters and is incompatible with REST urls
A service that accepts the name of a controller, a method and arguments values and renders the URL that's represented by them
Integration with Spring Security that can allow me to check for a given URL whether the current user is allowed to access it, so that I can decide whether or not to render a URL
A menuing system based on the above that can define menues composed of these actions and render them to page
Basically what I need is the ability to define URLs in one centralized place, so that changing a URL (during development; I'm aware of the don't-change-live-urls idea :) ) does not mean looking up and changing that URL in a zillion pages.
Any directions to such an existing solution / tutorial / guide would be great.
Thanjs
This is a feature I really miss in Spring MVC.
That's why I created the springmcv-router project, basically a port of PlayFramework's Router implementation in Spring MVC (HandlerMapping + HandlerAdapter).
I'm heavily using it in several real-world projects and the Router implementation itself is reliable.
Try using Spring Roo. It utilizes many best practices for spring MVC, and it has a scaffolding feature that automatically maintains a menu, jsp's and all the CRUD methods of a controller.
Setting up Spring Security with Roo is as simple as typing "security setup".
Hope this is helpful.
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.