1
votes

I have a controller in Spring MVC 3.2 which I want to allow the follow url's: http://localhost:8080/mypage http://localhost:8080/mypage/ http://localhost:8080/mypage/foo

I want to exclude anything else i.e. http://localhost:8080/mypage/bar should result in an error. Currently bar gets mapped to the getStuff method.

I assume I must be able to accomplish this without using a filter?

My servlet mapping looks like this:

<servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/mypage/*</url-pattern>
</servlet-mapping>

The controller request mapping:

@RequestMapping(method = RequestMethod.GET)
public String getView(HttpServletRequest request, @ModelAttribute("myform") final MyForm form)  {
        return "myview";
}
@ResponseBody
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@RequestMapping(value = "/save")
public String onSave(@RequestBody MyForm form, HttpServletRequest request, HttpServletResponse response)  {
        return "saved";
}
2

2 Answers

0
votes

The <url-pattern> Tag of servlet does not support exclusions. This is a limitation of the Servlet specification.
You have to create this functionality programmatically in a filter.

0
votes

You have to use the Spring MVC filters called Interceptors.

If you write your own Interceptor you have two options as below:

1. option:

Use the postHandle() method to check your conditions. If you use the postHandle() method you have access to the ModelAndView and if your url doesn't match with one of your 3 url's you just can throw an Exception or change the ModelAndView.

2. option:

Use the preHandle() method, check the url's and if they don't match throw a ModelAndViewDefiningException with a new ModelAndView() like this: ModelAndViewDefiningException(new ModelAndView("errorPage"))