I know this has been asked before. However In spite of doing everything as suggested I am facing an issue.
if my path variable has .jpg extension, it is getting truncated.
Here are my settings
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>image/jpeg</value>
<value>image/jpg</value>
<value>image/png</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<util:list>
<ref bean="jsonMessageConverter" />
</util:list>
</property>
</bean>
<bean name="exceptionHandlerExceptionResolver"
class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
<property name="order" value="0" />
<property name="contentNegotiationManager" ref="contentNegotiationManager" />
</bean>
<bean name="handlerMapping"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="contentNegotiationManager" ref="contentNegotiationManager" />
<property name="useSuffixPatternMatch" value="false" />
<property name="useTrailingSlashMatch" value="true"></property>
</bean>
Controller
#RequestMapping(value = "image/{fileName}", method = RequestMethod.GET, produces = { MediaType.IMAGE_JPEG_VALUE,
MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE })
public #ResponseBody
byte[] getImage(#PathVariable("fileName") final String fileName);
Do I need to do more?
Try this (note the updated value for #RequestMapping)
#RequestMapping(value = "image/{fileName:[a-z]\\.[a-z]}}", method = RequestMethod.GET, produces = { MediaType.IMAGE_JPEG_VALUE,
MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE })
public #ResponseBody
byte[] getImage(#PathVariable("fileName") final String fileName);
See reference here.
Related
I'm building an application with Spring MVC (3.2). This application need to invoke to 2 web services. It's ok when I invoke each service separately. However, it's not work when I call both. My application config file:
<bean id="soapMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_11" />
</property>
</bean>
<!-- The first service-->
<bean id="local" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"
p:contextPath="com.ws" />
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="marshaller" ref="local" />
<property name="unmarshaller" ref="local" />
<property name="defaultUri"
value="http://localhost:9999/ws/ProcessService" />
</bean>
<!-- The second service-->
<bean id="preconvert" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"
p:contextPath="com.ws.preprocess" />
<bean id="wstemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory" />
<property name="marshaller" ref="preconvert" />
<property name="unmarshaller" ref="preconvert" />
<property name="defaultUri"
value="http://localhost:9999/jod/PreProcessService" />
</bean>
Help me please! Thanks.
Hi chicky I solved the problem
Beans XML
<bean id="webServiceTemplate1" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory"/>
<property name="marshaller" ref="marshaller1"/>
<property name="unmarshaller" ref="marshaller1"/>
<property name="defaultUri" value="http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"/>
</bean>
<bean id="webServiceTemplate2" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory"/>
<property name="marshaller" ref="marshaller2"/>
<property name="unmarshaller" ref="marshaller2"/>
<property name="defaultUri" value="http://www.w3schools.com/webservices/tempconvert.asmx?WSDL"/>
</bean>
webServiceTemplate1 service
#Autowired
private WebServiceTemplate webServiceTemplate1;
#Override
public double obtenerCambio(String from, String to) {
ConversionRate conversionRate = new ObjectFactory().createConversionRate();
conversionRate.setFromCurrency(Currency.fromValue(from));
conversionRate.setToCurrency(Currency.fromValue(to));
ConversionRateResponse conversionRateResponse = (ConversionRateResponse) webServiceTemplate1.marshalSendAndReceive(conversionRate);
return conversionRateResponse.getConversionRateResult();
}
And webServiceTemplate2
#Autowired
private WebServiceTemplate webServiceTemplate2;
#Override
public String obtenerConversion(String celcius) {
CelsiusToFahrenheit celsiusToFahrenheit = new ObjectFactory().createCelsiusToFahrenheit();
celsiusToFahrenheit.setCelsius(celcius);
CelsiusToFahrenheitResponse response = (CelsiusToFahrenheitResponse) webServiceTemplate2.marshalSendAndReceive(celsiusToFahrenheit);
return response.getCelsiusToFahrenheitResult();
}
I am using InternalResourceViewResolver for resolving file names. Till now I was using only JSP so it was completely fine. Now for few requests I need to send xml files residing in my WEB-INF folder, but not getting idea how to exclude or include support these XML files
My controller is like this:
#RequestMapping(value = "/sitemap/sitemap_index.xml", method = RequestMethod.GET)
public String viewXmlSitemapIndex(ModelMap model) {
return "/other/sitemap_index"; //sitemap_index.xml is actual xml file residing in other folder inside WEB-INF
}
And in dispatcherservlet I have defined InternalResourceViewResolver like this:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
I guess you should use a ContentNegotiatingViewResolver like this
<bean id="viewResolver"
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<property name="prefixJson" value="true" />
</bean>
</list>
</property>
</bean>
Here you can define multiple view resolver and you can choose the one to use for the XML
I hope this can help
Angelo
#ResponseBody
#RequestMapping(method = RequestMethod.DELETE)
public String deleteState(#RequestBody String message) {
System.out.println("controller");
int resp = stateService.delete(message);
return resp == 1 ? "State deleted successfully : HTTP 200"
: "delete operation failed : HTTP 400";
}
when I post a json { stateName: VA}, it returns 415 error, Can any one suggest something please?
#Override
#Transactional
public int delete(Object message) {
System.out.println("service");
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject((String) message);
Parameters p = new Parameters();
p.property = "state_name";
p.value = (String) jsonObj.getString("stateName");
System.out.println("service");
return stateDAO.delete(p);
} catch (Exception e) {
return 0;
}
}
This is what I am doing in the service...
Update : Here is my Spring Configuration:
<context:annotation-config />
<!-- Scans the classpath of this application for #Components to deploy as
beans -->
<context:component-scan base-package="com.tutorial.jquery" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="org.postgresql.Driver"
p:url="jdbc:postgresql://localhost:5432/processdb" p:username="postgres"
p:password="postgres" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- >bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"
/> <property name="order" value="0" /> <property name="prefix"> <value>/WEB-INF/views/</value>
</property> <property name="suffix"> <value>.html</value> </property> </bean -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="2" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
</list>
</property>
</bean>
<!-- If no extension matched, use JSP view -->
<bean id="htmlView"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="prefix">
<value>/views/</value>
</property>
<property name="suffix">
<value>.html</value>
</property>
</bean>
I updated the method to get it working:
#ResponseBody
#RequestMapping(method = RequestMethod.DELETE)
public String deleteState(HttpServletRequest request,
HttpServletResponse response) {
Map<String, String[]> parameters = request.getParameterMap();
//System.out.print("RequestParam: " + state_Name);
int resp = stateService.delete(parameters.get("state_name")[0]);
return resp == 1 ? "State deleted successfully : HTTP 200"
: "delete operation failed : HTTP 400";
}
This fixed the issue
Thanks!
Try this,
change
#RequestBody String message
to
#RequestParam String stateName
I am having a hard time configuring Jackson on my Spring application. I can get it to work, but it does not seem to accept any kind of configurations. Basically what i'm trying to achieve is have an ObjectMapper that scans for Spring format annotations.
What i am trying is this:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="jacksonObjectMapper" class="ro.softwin.cnfp.ConversionServiceAwareObjectMapper" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="false" />
<property name="objectMapper" value="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
The code for the mapper is :
public class ConversionServiceAwareObjectMapper extends ObjectMapper {
#Autowired
public ConversionServiceAwareObjectMapper(
ConversionService conversionService) {
AnnotationIntrospector introspector = AnnotationIntrospector.pair(
new FormatAnnotationIntrospector(conversionService),
DEFAULT_ANNOTATION_INTROSPECTOR);
this.setDeserializationConfig(this.getDeserializationConfig()
.withAnnotationIntrospector(introspector));
this.setSerializationConfig(this.getSerializationConfig()
.withAnnotationIntrospector(introspector).withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL));
}
}
When initializing the server the following error occurs:
java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.codehaus.jackson.map.ObjectMapper] for property 'objectMapper': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
... 55 more
I tried switching to a normal view resolver and just having the object mapper in the AnnotationMethodHandler, and that works regarding server start-up, but it just completely ignores any configuration.
I am completely at a loss as to what to do next.
Thanks for any help.
Update :
<property name="objectMapper" value="jacksonObjectMapper" />
with:
<property name="objectMapper" ref="jacksonObjectMapper" />
ref not value.
Does anyone have an example of using the Spring RssChannelHttpMessageConverter to generate a rss podcast?
This is what I have so far.
#Controller
public class FeedController {
private Jaxb2Marshaller jaxb2Mashaller;
#Autowired
public void setJaxb2Mashaller(Jaxb2Marshaller jaxb2Mashaller) {
this.jaxb2Mashaller = jaxb2Mashaller;
}
#RequestMapping(method= RequestMethod.GET, value="/emps",
headers="Accept=application/rss+xml")
public #ResponseBody SyndFeed getFeed(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query query = session.createQuery("from Show");
List<Show> l = query.list();
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss2.0");
feed.setTitle("some podcast");
feed.setLink("you");
feed.setDescription("description");
feed.setCopyright("c_me");
List<SyndEntry> entries = new ArrayList<SyndEntry>();
for(Show e : l) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle(e.getTitle());
entries.add(entry);
}
feed.setEntries(entries);
System.out.println(feed);
return feed;
}
}
When calling the controller I get a 406 Not Acceptable
Here is some snippets of my spring config
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="marshallingConverter" />
<ref bean="atomConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="atomConverter" class="org.springframework.http.converter.feed.RssChannelHttpMessageConverter">
<property name="supportedMediaTypes" value="application/rss+xml" />
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<!-- Client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<ref bean="marshallingConverter" />
<ref bean="atomConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jaxbMarshaller"
class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.Show</value>
</list>
</property>
</bean>