Spring Controller's URL request mapping not working as expected

自作多情 提交于 2019-12-06 03:22:00

问题


I have created a mapping in web.xml something like this:

<servlet>  
        <servlet-name>dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
</servlet>
<servlet-mapping>  
        <servlet-name>dispatcher</servlet-name>  
        <url-pattern>/about/*</url-pattern>  
</servlet-mapping>

In my controller I have something like this:

import org.springframework.stereotype.Controller;  
@Controller  
public class MyController{  
    @RequestMapping(value="/about/us", method=RequestMethod.GET)
    public ModelAndView myMethod1(ModelMap model){  
        //some code  
        return new ModelAndView("aboutus1.jsp",model);  
    }  
    @RequestMapping(value="/about", method=RequestMethod.GET)
    public ModelAndView myMethod2(ModelMap model){  
        //some code  
        return new ModelAndView("aboutus2.jsp",model);  
    }  
}

And my dispatcher-servlet.xml has view resolver like:

<mvc:annotation-driven/>  
<bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:viewClass="org.springframework.web.servlet.view.JstlView"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp"/>

To my surprise: request .../about/us is not reaching to myMethod1 in the controller. The browser shows 404 error. I put a logger inside the method but it isn't printing anything, meaning, its not being executed.
.../about works fine! What can be the done to make .../about/us request work? Any suggestions?


回答1:


You need to use @RequestMapping(value="/us", method=RequestMethod.GET) or you need to request about/about/us




回答2:


Since you have mapped "/about" in your web.xml, the url it will pass will be like this www.xyz.com/about/*

As your configuration says it will work for

  1. www.xyz.com/about/about/us
  2. www.xyz.com/about/about

In order to to work properly either use /* in web.xml instead of /about

or change the controller's endpoint to

@RequestMapping(value="/us", method=RequestMethod.GET)

@RequestMapping(value="/", method=RequestMethod.GET)




回答3:


Okay I got the thing working, here are things I added in the dispatcher-servlet.xml:

<bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="alwaysUseFullPath" value="true" />
    </bean>

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="alwaysUseFullPath" value="true" />
</bean>


来源:https://stackoverflow.com/questions/11203907/spring-controllers-url-request-mapping-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!