开发者

Spring MVC request with no view rendered

开发者 https://www.devze.com 2023-02-18 04:54 出处:网络
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 rende

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" />开发者_如何学C;
</beans:bean>


Returning null did not work.

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

@ResponseBody


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.


I believe you can achieve that, by returning null.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号