Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC request with no view rendered

I am having trouble with a Spring configuration for the following functionality - I need the view requests to behave normally (render the view) and the service requests to simply execute without rendering anything. The problem I'm having is that, after the controller executes, somewhere down the line Spring decides that a ModelAndView should get instantiated even though the controller method doesn't return anything (void). This triggers a view to be rendered, when in fact I want to simply do nothing once the controller has done it's job. I'm sure it must be something I'm doing wrong in the Spring configuration (my guess is that it's related to the view resolver). Any help on this is appreciated. Thanks.

Here is the code:

@Controller
@RequestMapping( "actions" )
public final class ServiceController{
    private static final Logger logger = LoggerFactory.getLogger( ServiceController.class );
    @RequestMapping( value = "/submit.service",method = RequestMethod.POST )
    public void test( @RequestParam( "mail" ) String mail ){
        ServiceController.logger.info( mail );
    }
}

And the servlets in web.xml:

<servlet>
    <servlet-name>viewServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/viewServlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>viewServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The context is:

<annotation-driven />
<beans:bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
    <beans:property name="resourceLoaderPath" value="/WEB-INF/velocity/" />
</beans:bean>

<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
    <beans:property name="cache" value="true" />
    <beans:property name="prefix" value="" />
    <beans:property name="suffix" value=".vm" />
</beans:bean>
like image 383
Eugen Avatar asked Mar 20 '11 21:03

Eugen


Video Answer


2 Answers

Returning null did not work.

In the meantime, I found the solution - I needed to annotate the method with

@ResponseBody

like image 115
Eugen Avatar answered Sep 22 '22 16:09

Eugen


another solution would be to return a responseEntity, http://www.captaindebug.com/2011/07/using-spring-responseentity-class.html, after all you will need a way to signal an error back to the client, and with @ResponseEntity if an exception occurs spring renders this in a html page. with ResponseEntity you can respond with http 500 add custom data.

like image 22
cproinger Avatar answered Sep 21 '22 16:09

cproinger