Using Spring and Jackson to Render JSON without affecting all Views
Spri开发者_JS百科ng MVC AJAX and JSON using Custom View Resolver, and Custom View
Here I've gotten a view to display JSON by adding ".json" to the end of a URL, but using this method a visitor to the site can just put .json at the end of any URL they please and often it will result in an exception that gives too much information regarding the back end code.
I could catch the exception and provide a more user friendly error message, but I'm not sure if that's the best way to handle this since the times that I'd want to convert an object to JSON is actually quite limited and will really only be used for administration pages, is there a way to limit this feature to specific URLs, controllers, or controller methods?
Edit: This isn't about URLs that aren't mapped giving exceptions, It's about real URL's with ".json" after it that are mapped trying to render their contents as JSON when that isn't what is needed
I'm not worried about the exception I'm getting, it makes sense that I'm getting it, I'm saying that some URL's, in fact MOST URLs shouldn't be able to be taken as JSON, and putting ".json" after it should just return a 404
I think is a problem more about security. If you're using a framework like Spring Security you can control that some URL like **.json can only be reached by some users (for instance the administrator, if they're only used in the admin pages).
You should have a look at this: Configure Spring's MappingJacksonHttpMessageConverter
Basically, you can do everything without views or viewresolvers by using @ResponseBody and MappingJacksonHttpMessageConverter
Something like this:
@RequestMapping(value = "/test/data")
@ResponseBody
public TestFormData dostuff() {
TestFormData data = new TestFormData();
data.setName("myname");
return data;
}
精彩评论