0

所以我有这个重定向视图我的控制器之一:

    @RequestMapping(value = {"/shoes", "/shoes/"}, method = {RequestMethod.GET})
    public RedirectView shoesHome(HttpServletRequest request) {
        return new RedirectView("https://www.somewebsite.com/");
    }

是否可以添加正则表达式以便重定向发生

which currently is working fine and any other variation such as 
http://mywebsites.com/shoes 
http://mywebsites.com/shoes/sandals.html
http://mywebsites.com/shoes/boots.html
http://mywebsites.com/shoes/sport/nike.html

谢谢

4

1 回答 1

2

你可以这样做:-

@RequestMapping(value = "/shoes/**", method = RequestMethod.GET)
public RedirectView shoesHome() {
    return new RedirectView("https://www.somewebsite.com/");
}

这样,之后的任何 URI/shoes也将被重定向到http://somewebsite.com.

以下是测试用例:-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:springtest-test.xml"})
public class MyControllerTest {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Test
    public void testRedirect() throws Exception {
        assertRedirect("/shoes");
    }

    @Test
    public void testRedirect2() throws Exception {
        assertRedirect("/shoes/sandals.html");
    }

    @Test
    public void testRedirect3() throws Exception {
        assertRedirect("/shoes/sports/nike.html");
    }

    private void assertRedirect(String uri) throws Exception {
        MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
        MockHttpServletResponse response = new MockHttpServletResponse();

        Object handler = handlerMapping.getHandler(request).getHandler();
        ModelAndView modelAndView = handlerAdapter.handle(request, response, handler);

        RedirectView view = (RedirectView) modelAndView.getView();
        assertEquals("matching URL", "https://www.somewebsite.com/", view.getUrl());
    }
}
于 2013-10-21T23:02:37.343 回答