Json/Jackson ResponseEntity 406 Error - spring mvc 4 - java

sorry my english.
i try to solve this error but i donĀ“t know what could be
I'm new with spring and REST
i'm using:
*spring mvc 4.0.1
*NetBeans 8
*Hibernate
*Tomcat 8
*Oracle
*Json / Jackson REST
*AngularJS
the ERROR is 406 error when i try to get in my controller a object list with Json, when i try to get a simple String the answer is 200 (OK)
i try to add this line >> <mvc:annotation-driven/> in my dispatcher-servlet but then return:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.http.InvalidMediaTypeException: Invalid mime type "String": does not contain '/' <<<
so, next the code without the previous line and with 406 ERROR:
Dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="controller"/>
<context:annotation-config />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<property name="prefixJson" value="true"/>
</bean>
PerfilesController.java
...
#ResponseStatus(value=HttpStatus.OK)
#RequestMapping(value= "perfiles.serv", method = RequestMethod.GET, headers="Accept=*/*", produces= {"application/xml", "application/json", "String"})
public #ResponseBody ResponseEntity<List<Perfiles>> getAllProfiles() {
PerfilesService pService = new PerfilesService();
List<Perfiles> list = pService.getAllProfles();
return new ResponseEntity<List<Perfiles>>(list, HttpStatus.OK);
}
...
i call with angular JS
app.service
svservicios.service('PerfilesService',['$http', function ($http) {
function getPerfiles(pageNumber,size) {
pageNumber = pageNumber > 0?pageNumber - 1:0;
return $http({
method: 'GET',
headers: {
'Content-Type': 'application/json','Accept': 'application/json, */*'
},
url: 'perfiles.serv?page='+pageNumber+'&size='+size
});
}
return {
getPerfiles: getPerfiles
};
}]);
the view:
<div class="edit-contenedor">
<div class = "btnAddPerfil">
<md-button href="crearP.html" class = "col-md-12 md-raised">Agregar Perfil</md-button>
</div>
<div>
<div ng-controller="AdminPerfilesController">
<div ui-grid="gridOptions" class="grid-ap" ui-grid-pagination>
</div>
</div>
</div>
thanks

I resolve with this in my dispatcher-servlet:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
thanks to spring mvc not returning json content - error 406

Related

Handle error from wrong path in CXF Server

I'm trying to handle error in CXF rest service. Which i want to gain is a situation when user is trying to send request and he's choosing a wrong path. I would like to handle this situation. The default responses are:
2014-05-15 14:07:14 INFO [qtp811959489-40] LoggingOutInterceptor:234 - Outbound Message
---------------------------
ID: 1
Response-Code: 405
Content-Type:
Headers: {Allow=[POST, GET, OPTIONS, HEAD], Date=[Thu, 15 May 2014 12:07:14 GMT], Content-Length=[0]}
My resource class:
#Path("payment/v1/")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class OneApiResource {
#GET
#Path("/{endUserId}/transactions")
public PaymentTransactionListWrapper listTransactions(#PathParam("endUserId") String endUserId) {
return null;
}
}
endpoint:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
">
<bean id="jsonProviderFactory" class="model.oneApi.JsonProviderFactory"/>
<bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
<cxf:rsServer id="bieService"
address="http://{{endpoint.jetty.app.oneApi.host}}:{{endpoint.jetty.app.oneApi.service.port}}/{{endpoint.jetty.app.oneApi.service.ctx}}/"
loggingFeatureEnabled="true"
serviceClass="model.oneApi.OneApiResource"
loggingSizeLimit="-1"
skipFaultLogging="false">
<cxf:providers>
<bean factory-bean="jsonProviderFactory" factory-method="create"/>
</cxf:providers>
<cxf:inFaultInterceptors>
<ref bean="logOutbound"/>
</cxf:inFaultInterceptors>
<cxf:outFaultInterceptors>
<ref bean="logOutbound"/>
</cxf:outFaultInterceptors>
</cxf:rsServer>
</beans>
Is there any way to handle it?

SpringMVC with Annotated Controllers: URL "Resource Not Available"

I am using SpringMVC 3 with Annotated Controllers. I successfully mapped my URL ("/HelloWorld) to a Controller and defined its GET processing method.
The error is that upon typing the (App)/HelloWorld URL, my web server (GlassFish) gives this error:
The requested resource is not available.
But in the GlassFish log I see that the URL was mounted.
Mapped "{[/HelloWorld],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView controllers.HelloWorldController.processHelloWorld()
My Files:
(1) HelloWorldController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
*
* #author */
#Controller
#RequestMapping("/HelloWorld")
public class HelloWorldController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView processHelloWorld()
{
ModelAndView model = new ModelAndView("HelloWorldPage");
model.addObject("msg", "Expanded string - hello world");
return model;
}
}
(2) Dispatcher-Servlet.xml. Note the MVC-Annotation-Driven approach. The indexController is not used.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="controllers" />
<mvc:annotation-driven />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
(3) HelloWorldPage.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Spring MVC Hello World Annotation Example</h1>
<h2>${msg}</h2>
</body>
</html>
Any ideas why the URL "/HelloWorld" is not being found? Thanks.
Problem solved. I had to invoke the URL "/HelloWorld.htm" for the mapping to work.
(The Dispatcher-Servlet's mapping in web.xml is "*.htm".) Thanks

How to properly return an image in the response in Spring app?

I 'm using Spring 3.0.1.RELEASE for my webapp (and i have no way for upgrading it) and i'm trying to render some images from database on web-page.
I have following simple Spring configs:
spring-application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.me" />
<bean id="hibernateSessionFactory" class="com.me.dbaccess.HibernateSessionFactory">
<constructor-arg ref="sessionFactory"/>
</bean>
</beans>
spring-mvc.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<bean id="tilesViewResolver" class="com.me.util.TilesExposingBeansViewResolver">
<property name="viewClass" value="com.me.util.TilesExposingBeansView"/>
<property name="exposeContextBeansAsAttributes" value="true"/>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/config/tiles-defs.xml</value>
</list>
</property>
</bean>
</beans>
I have following controller:
#Controller
public class PhotoController {
#RequestMapping("/carPhoto.html")
#ResponseBody
public byte[] getCarPhoto(
#RequestParam(UrlParameters.PHOTO_ID) Integer photoId,
#RequestParam(UrlParameters.PHOTO_TYPE) String photoType) {
//return image's bytes array from db by photo Id and Type;
}
}
And finally, I have simple jsp-page:
<%#page contentType="text/html; charset=utf-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<img id="photoImage" src="<c:url value="/carPhoto.html?photoType=1&photoId=22556793"/>" />
If I open this page - I can see this image without any problems.
But if I copy image "src" attribute and paste it in browser's address bar (Firefox 19.0.2) - then browser offers me to save carPhoto.html, instead of just render the image.
Should I perform some additional setup?
The problem is, that you have to specify the mime type (and if your image is larger you will need to specify its length too).
An other solution () is to return a Spring ResponseEntity or HttpEntity (HttpEntity is enough if you always return http status code 200, ResponseEntity (a subclass of HttpEntity) is for example needed if you want to return other http status codes, like not found).
#Controller
public class PhotoController {
#RequestMapping("/carPhoto.html")
#ResponseBody
public HttpEntity<byte[]> getCarPhoto(
#RequestParam(UrlParameters.PHOTO_ID) Integer photoId,
#RequestParam(UrlParameters.PHOTO_TYPE) String photoType) {
byte[] image = image's bytes array from db by photo Id and Type;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG); //or what ever type it is
headers.setContentLength(image.length);
return new HttpEntity<byte[]>(image, headers);
}
}
There are several ways. Easiest is to use #ResponseBody with a byte[] as your return type, set your Content-Type and such, the write the bytes to the output stream using the HttpServletResponse.
A more elegant solution (IMO) would be to return a ModelAndView, then set the View on that to a custom view that sets the proper headers (Content-Type and such) and writes out the bytes to the HttpServletResponse's output stream.

Jquery dialog - based on json submitted to Spring Controller that returns a view

I have used this code as the basis of my development so far : Ajax Simplifications from springsource.
Here is the html & jquery/javascript code:
<c:url var="Controller" value="/ControllerUrl" />
...
var previewDialog = $("<div></div>").dialog({
//all the dialog setttings
});
$(".opener").click(function() {
previewDialog.load("${Controller}",function(data) {
previewDialog.dialog('open');
});
return false;
});
And the controller :
#RequestMapping(value = "/ControllerUrl", method = RequestMethod.GET)
public String previewDialog(Model model) {
MyClass myClass = new MyClass();
myClass.setTitle("SUCCESS");
model.addAttribute(myClass);
return "dialogContent";
}
This is all almost working, except in dialogContent.jsp (which is indeed opened in my dialog) "SUCCESS" is not printed:
<div id="divContent">
Title : ${myClass.title} <br>
</div>
What am I missing/doing wrong ?
Secondly, what is the besy way to submit json data to server in this context - I attempted using $.ajax() and $.postJSON() but ran into problems as they work differently to the $.load() statement.
Thanks in advance.
Can you try:
In the Controller:
return new ModelAndView("view-name", "myclass", myClass);
In your JSP:
${myClass.title}
The trouble is that this would till return HTML rather than just plain text.
Also, you can probably return json or xml by changing your controller as follows:
#RequestMapping(value = "/ControllerURL", method = RequestMethod.GET, headers="Accept=application/xml, application/json")
public #ResponseBody DealManager homeXmlJson(Locale locale, Model model) {
MyClass myClass = new MyClass();
myClass.setTitle("SUCCESS");
return myClass;
}
Then when you call it using $.getJSON it should return a json representation of the object from which you should be able to extract the title.
Use a tool like REST-Client to see what is returned when you pass different Accept parameters to the controller URL. the parameter being:
Accept: text/html, Accept: application/json, Accept: application/xml
You will have to configure your rest context as well. Here is an example of one I'm using:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
<ref bean="marshallingConverter" />
<!-- <ref bean="atomConverter" /> -->
</list>
</property>
</bean>
<!-- Handle JSON Conversions -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<!-- Handle XML Conversion -->
<bean id="marshallingConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml" />
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.pack1.app.domain.MyEntity</value>
<value>com.pack1.app.service.MyEntityTwo</value>
</list>
</property>
</bean>
</beans>

Spring mvc controller issue

I'm trying to learn spring MVC, so far so good but I'm kind of stuck now. I'm trying to learn how to create json and get it with javascript(jquery).
But for testing purposes I tried to create something just so I can see that is displayed properly trough http request, then I'll try to create json and get it, but so far I can't even get the request to work. Here is my controller :
#Controller
#RequestMapping(value="/")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
Map<Long,Item> itemMap = createItemMap();
#RequestMapping(value="item/{itemId}", method=RequestMethod.GET)
public #ResponseBody Item get(#PathVariable Long itemId) {
Item item = itemMap.get(itemId);
if (status == null) {
throw new ResourceNotFoundException(itemId);
}
return item;
}
private Map<Long,Item> createItemMap(){
//omitted because its irrelevant
//I created 2 item objects , with id 1 and 2 for testing purposes
}
}
This is content of my servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Imports user-defined #Controller beans that process client requests -->
<beans:import resource="controllers.xml" />
</beans:beans>
And controllers.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<context:component-scan base-package="com.testing.mvc.controller" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
</beans>
My war is called Test.war, when I try localhost:8080/Test I get index view which is OK. But regardless of what I try:
localhost:8080/Test/item/1
localhost:8080/Test/item?itemId=1
localhost:8080/item?itemId=1
I end up with some kind of error, the most interesting is this one :
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
I've googled alot found these to be interesting :
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/
Mapping restful ajax requests to spring
Spring's Json not being resolved with appropriate response
Nothing helped so far, any idea what I'm missing. Sorry for providing too much info.
As far as I can tell you are missing this resolver like this in your dispatcher serlet:
<bean name="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
</bean>
Take look at this:
http://spring-json.sourceforge.net/quick_simpleform.html
You have to create file views.xml in yoru WEB-INF direcotry with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
</beans>

Categories

Resources