2

I am using Java with Spring framework. Given the following url:

www.mydomain.com/contentitem/234

I need to map all requests that come to /contentitem/{numeric value} mapped to a given controller with the "numeric value" passed as a parameter to the controller.

Right now in my servlet container xml I have simple mappings similar to the following:

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

I am just wondering what I need to add to the mapping in order to achieve what I described?

Edit: I unaccepted the answer temporarily because I can't seem to figure out how to do the mapping in my web.xml (I am using annotations as described in axtavt's answer below). How do I add a proper <url-pattern>..</url-pattern> in my <servlet-mapping> so that the request for "/contentitem/{numeric_value}" gets properly picked up? Thanks!

oym
  • 6,983
  • 16
  • 62
  • 88

3 Answers3

4

It can be done using annotation-based controller configuration (see 15.3 Implementing Controllers):

@Controller
public class ContentItemController {

    @RequestMapping("/contentitem/{id}")
    public ModelAndView contentItem(@PathVariable("id") int id) {
        ...
    }
}
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Thanks..but my project is currently set up without annotations. Any way I could get the solution without using annotations? – oym Feb 18 '10 at 18:36
  • 2
    No. There is no ways configure extraction of path variables without annotations. – axtavt Feb 18 '10 at 18:44
  • really?? wow, thats surprising to me...okay thanks for ur help! – oym Feb 18 '10 at 18:45
  • hmm..when I try to add the @Controller annotation I get the following error: "Type mismatch: cannot convert from Controller to Annotation" not sure why this is... – oym Feb 18 '10 at 18:49
  • 4
    Check your `import` s. `Controller` interface is `org.springframework.web.servlet.mvc.Controller`, `@Controller` annotation is `org.springframework.stereotype.Controller`. – axtavt Feb 18 '10 at 18:53
  • @es11: For mapping options, see http://stackoverflow.com/questions/2129876/using-spring-mapping-to-root-in-web-xml-static-resources-arent-found/2129960#2129960 – axtavt Feb 18 '10 at 22:04
3

try to use @RequestMapping and @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
}

Watch this Spring MVC Framework Tutorial

0

You must import org.springframework.stereotype.Controller.

Pops
  • 30,199
  • 37
  • 136
  • 151
kth79
  • 1