【问题标题】:Spring 3 check if there is a handler for a urlSpring 3检查是否有一个url的处理程序
【发布时间】:2013-01-14 23:55:05
【问题描述】:

我在 spring 3 中使用 java servlet。 有什么方法可以检查特定 URL 是否有处理程序?

我正在尝试实现一个测试,以确保处理我的 Jsp 文件中使用的所有 url。 如果我想进行 url 重构,我想确保我的 jsps 中没有任何“断开的链接”...

谢谢

【问题讨论】:

    标签: java spring url servlets


    【解决方案1】:

    如果您使用 JUnit 和 Spring 3,这里是一个测试 FooController 的示例:

    @Controller
    @RequestMapping(value = "/foo")
    public class FooAdminController {
    
        @RequestMapping(value = "/bar")
        public ModelAndView bar(ModelAndView mav) {
    
            mav.setViewName("bar");
            return mav;
        }
    }
    

    FooController 的测试用例:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"file:src/path/to/servlet-context.xml" })
    public class FooControllerTest {
    
        @Autowired
        private RequestMappingHandlerMapping handlerMapping;
    
        @Autowired
        private RequestMappingHandlerAdapter handleAdapter;
    
        @Test
        public void fooControllerTest() throws Exception{
    
            // Create a Mock implementation of the HttpServletRequest interface
            MockHttpServletRequest request = new MockHttpServletRequest();
    
            // Create Mock implementation of the HttpServletResponse interface
            MockHttpServletResponse response = new MockHttpServletResponse();
    
            // Define the request URI needed to test a method on the FooController
            request.setRequestURI("/foo/bar");
    
            // Define the HTTP Method
            request.setMethod("GET");
    
            // Get the handler and handle the request
            Object handler = handlerMapping.getHandler(request).getHandler();
            ModelAndView handleResp = handleAdapter.handle(request, response, handler);
    
            // Test some ModelAndView properties
            ModelAndViewAssert.assertViewName(handleResp ,"bar");
            assertEquals(200, response.getStatus());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2010-12-19
      • 2013-08-04
      • 2011-03-26
      • 1970-01-01
      相关资源
      最近更新 更多