要按请求URI过滤视图,可以使用Spring框架提供的请求映射注解和条件注解来实现。
首先,确保你的项目中引入了Spring MVC依赖,然后在控制器类的方法上使用@RequestMapping注解来定义请求映射。
示例代码如下:
@Controller
public class MyController {
@RequestMapping(value = "/example", method = RequestMethod.GET)
public ModelAndView exampleView() {
ModelAndView modelAndView = new ModelAndView("example");
// 添加视图数据
return modelAndView;
}
@RequestMapping(value = "/other", method = RequestMethod.GET)
public ModelAndView otherView() {
ModelAndView modelAndView = new ModelAndView("other");
// 添加视图数据
return modelAndView;
}
}
上述代码中,有两个方法分别映射到"/example"和"/other"的GET请求,并返回相应的视图。你可以根据自己的需求添加更多的方法和请求映射。
接下来,你可以使用Spring的条件注解@RequestParam来获取请求的URI,并进行过滤。修改上述示例代码如下:
@Controller
public class MyController {
@RequestMapping(value = "/example", method = RequestMethod.GET)
public ModelAndView exampleView(@RequestParam String uri) {
if (uri.equals("/example")) {
ModelAndView modelAndView = new ModelAndView("example");
// 添加视图数据
return modelAndView;
} else {
// 返回错误视图或其他处理逻辑
}
}
@RequestMapping(value = "/other", method = RequestMethod.GET)
public ModelAndView otherView(@RequestParam String uri) {
if (uri.equals("/other")) {
ModelAndView modelAndView = new ModelAndView("other");
// 添加视图数据
return modelAndView;
} else {
// 返回错误视图或其他处理逻辑
}
}
}
在修改后的代码中,我们为每个方法添加了一个@RequestParam注解,用于获取请求的URI。然后,我们可以根据URI的值进行过滤,选择返回相应的视图或执行其他逻辑。
请注意,这只是一个简单的示例,你可以根据自己的需求进行更复杂的过滤逻辑。