简体   繁体   中英

Spring 4.0 MVC RequestMapping at class and method level

I am new to annotation and exploring out things. In my sample program .. a simple hello world using annotations in spring 4.0.

This is the controller file code I have two annotated RequestMapping entries ie one at class level and another at method level :

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/Hybrid")
public class HybridController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String getDemo(String name) {
        System.out.println("/MVC/Demo");
        return "helloworld" ;
    }

}

If i put only the class level @RequestMapping it works with this url connecting to .../SpringRS/Hybrid or just only the method level to connect using .../SpringRS/test it works perfectly and displays me the helloworld.jsp.

But when i try to put class and method request mapping together and invoke using this url : .../SpringRS/Hybrid/test, it don't work.

Could some one explain what i need to make it work?.

View resolver mapping:

<context:component-scan base-package="com" />
<mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    </bean>

I think in your web.xml you have url-pattern for DispatcherServlet as /Hybrid which maps exactly to your annotation at class level.If your request is for .../Hybrid it is picked up by the DispatcherServlet since it is an exact match. If your request is for .../Hybrid/test it is not at all picked up by the DispatcherServlet. Instead if your url-pattern ends with a wildcard like /something/* the request .../something/Hybrid/test will first be picked up by the DispatcherServlet and then handed over to the controller to be resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM