2013-10-21 49 views
0

所以我有這個重定向視圖我的控制器之一:的Java Spring MVC的重定向使用正則表達式

@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 

謝謝

+0

我不明白你在期待什麼。 –

+0

所以現在如果我去mywebsite.com/shoes它會重定向到somewbsite.com,但如果我鍵入somewebsite.com/shoes/sandals.html它不會,它仍然會去.shoes/sandals.html。是否可以使用正則表達式,因此每個包含鞋子的請求都將仍然重定向到somewebsite.com? –

回答

2

你可以這樣做: -

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

由此,/shoes後的任何URI也將被重定向到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()); 
    } 
}