【问题标题】:Spring URL mapping questionSpring URL映射问题
【发布时间】:2011-01-18 11:05:58
【问题描述】:

我正在使用 Java 和 Spring 框架。给定以下网址:

www.mydomain.com/contentitem/234

我需要将到达/contentitem/{numeric value} 的所有请求映射到给定控制器,并将“数值”作为参数传递给控制器​​。

现在在我的 servlet 容器 xml 中,我有类似于以下的简单映射:

...
<entry key="/index.html">
   <ref bean="homeController" />
</entry>
...

我只是想知道我需要在映射中添加什么才能实现我所描述的?

编辑:我暂时不接受答案,因为我似乎无法弄清楚如何在我的 web.xml 中进行映射(我正在使用下面的 axtavt 答案中描述的注释)。如何在我的&lt;servlet-mapping&gt; 中添加正确的&lt;url-pattern&gt;..&lt;/url-pattern&gt;,以便正确获取“/contentitem/{numeric_value}”的请求?谢谢!

【问题讨论】:

    标签: java spring spring-mvc url-mapping


    【解决方案1】:

    可以使用基于注解的控制器配置来完成(参见15.3 Implementing Controllers):

    @Controller
    public class ContentItemController {
    
        @RequestMapping("/contentitem/{id}")
        public ModelAndView contentItem(@PathVariable("id") int id) {
            ...
        }
    }
    

    【讨论】:

    • 谢谢..但是我的项目目前没有注释。有什么方法可以在不使用注释的情况下获得解决方案?
    • 没有。没有注释就无法配置路径变量的提取。
    • 真的吗?哇,这让我感到惊讶......好的,谢谢你的帮助!
    • hmm..当我尝试添加 @Controller 注释时,我收到以下错误:“类型不匹配:无法从控制器转换为注释”不确定这是为什么......
    • 检查您的import s。 Controller接口为org.springframework.web.servlet.mvc.Controller,@Controller注解为org.springframework.stereotype.Controller。
    【解决方案2】:

    尝试使用@RequestMapping 和@PathVariable

    @RequestMapping(value="/contentitem/{value}", method=RequestMethod.GET)
    public String demo(@PathVariable(value="nvalue") String name, ModelMap map) {
    
    int intValue = Integer.parseInt(nvalue);
    
    // Do manipulation
    
    return "something"; // Forward to something.jsp
    }
    

    观看此Spring MVC Framework Tutorial

    【讨论】:

      【解决方案3】:

      您必须导入org.springframework.stereotype.Controller。

      【讨论】:

        猜你喜欢
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 2012-10-21
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多