【问题标题】:Spring MVC restful pathSpring MVC 宁静路径
【发布时间】:2013-05-29 16:50:48
【问题描述】:

您好,我创建了一个 Spring MVC 应用程序,我有一个名为 Estimation 的控制器,它有两种方法。

我可以通过访问这个网址www.wesite.com/xyz/estimation

来访问这个控制器的home方法

但我尝试通过访问此网址 www.wesite.com/xyz/estimation/1 来访问 homeById 方法 我收到 404 错误,请求的资源不可用。

请任何人解释一下。

@Controller
@RequestMapping("/estimation")
public class EstimationController {

 @RequestMapping("")
 public ModelAndView home(HttpServletRequest request, HttpServletResponse  response) {

   ModelAndView mv = new ModelAndView("productEstimate");
   return mv; 

    }

   @RequestMapping(value="/{productId}", method = RequestMethod.GET)
    public ModelAndView homeById(HttpServletRequest request, HttpServletResponse response,@PathVariable int productId) {

     ModelAndView mv = new ModelAndView("productEstimate"); 

     return mv;
}

web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        WEB-INF/classes/spring/applicationContext.xml,
        WEB-INF/classes/spring/hibernateContext.xml
    </param-value>    </context-param>

<servlet>
    <servlet-name>projectName</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
    <servlet-name>projectName</servlet-name>
   <url-pattern>/estimation/*</url-pattern>
</servlet-mapping>

applicationContext.xml

<mvc:annotation-driven />

<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
         <property name="resourceLoaderPath" value="/views/" />
</bean>

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="cache" value="true"/>
        <property name="prefix" value=""/>
         <property name="layoutUrl" value="layout.vm"/>
        <property name="suffix" value=".vm"/>
</bean>

【问题讨论】:

  • 如果映射不匹配或视图无法呈现(但我看到您对两个请求使用相同的视图,所以如果第一个有效,那么应该第二)。看看你有没有类似WARNING: No mapping found for HTTP request with URI的错误

标签: spring rest model-view-controller


【解决方案1】:

当引用路径变量时,使用类似这样的东西

 @PathVariable("productId") int productId

这个包含的变量名与请求映射中的变量名相同

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

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多