开发者

How to achieve a certain url format using @RequestMapping in SpringMVC

开发者 https://www.devze.com 2023-02-09 23:07 出处:网络
I am trying to create a simple application using SpringMVC for learning purpose. I want to ha开发者_高级运维ve the urls for various actions in this format

I am trying to create a simple application using SpringMVC for learning purpose. I want to ha开发者_高级运维ve the urls for various actions in this format

http://localhost:8080/appname/controllername/actionname.html

The url-pattern specified inside the servlet-mapping for the DispatcherServlet is

<url-pattern>*.html</url-pattern>

here is one of my methods in the ContactController

@RequestMapping("list.html")
public ModelAndView showContacts() {        
    ModelAndView modelandview = new ModelAndView("list"); 

    modelandview.addObject("message","Your contact book");

    return modelandview;
}

Now everything works fine when i navigate to,

http://localhost:8080/appname/list.html

However I want the url to be,

http://localhost:8080/appname/contact/list.html

I tried using @RequestMapping("/contact/list.html") on top of the method but it doesnt help (shows 404 error with description The requested resource () is not available) .

How can this be done ?

Also, is it possible to have multiple url-patterns for servlet mapping for eg. *.html or *.do ?

PS. i am using apache-tomcat on Ubuntu desktop

Thanks


Add

@RequestMapping("/controllername")

before class Declaration.


Have you tried this?

@RequestMapping("/contact")
public class ContactController
{
  @RequestMapping("/list.html")
  public ModelAndView showContacts()
  {
    // ...
  }
}

Also, @RequestMapping accepts an array of strings to allow multiple mappings.


BTW, you may simplify even more!

This is easily remedied by using an XML-configured strategy for matching URI paths to controller classes and @RequestMapping annotations for method-level mapping only.

For details, see chapter Removing Class-Level Request Mappings at http://www.infoq.com/articles/spring-2.5-ii-spring-mvc

0

精彩评论

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