我有一个基于MVC的Spring应用程序,我想添加一些功能,其中一些控制器将返回相同的视图,具体取决于参数的值。
@RequestMapping("/someView")
public String returnView(Model model, HttpServletRequest request, String param){
if(param.equals("condition")){
return "commonView";
}
// do stuff
return "methodSpecificView";
}
有没有一种方法可以在xml中配置第一个if条件?由于类似的功能需要在许多控制器中实现,并且我不想编写样板代码,因此xml配置可以使事情变得更简单。
此外,如果第一个是可能的,是否可以扩展以从请求映射方法签名中删除参数param
并将其放入xml中?
答案 0 :(得分:1)
您可以使用@RequestMapping:
@RequestMapping(value = {"/someView", "/anotherView", ...}, params = "name=condition")
public String returnCommonView(){
return "commonView";
}
答案 1 :(得分:1)
在Spring 3.2中,基于以下代码片段的注释将为您提供问题的想法:
@RequestMapping("formSubmit.htm")
public String onformSubmit(@ModelAttribute("TestBean") TestBean testBean,BindingResult result, ModelMap model, HttpServletRequest request) {
String _result = null;
if (!result.hasErrors()) {
_result = performAction(request, dataStoreBean);//Method to perform action based on parameters recieved
}
if(testBean.getCondition()){
_result = "commonView";
}else{
_result = "methodSpecificView";
}
return _result;
}
TestBean//Class to hold all the required setters and getters
<强>说明:强> 当您的视图中的请求来到此方法时,如果从视图获取条件,则ModelAttribute引用将保留视图中的所有值,而不是直接从模型属性获取它并返回相应的视图。 如果在应用某些逻辑后获得条件,则可以在testBean中设置条件并再次使其返回相应的视图。
答案 2 :(得分:0)
您应该考虑通过以下AOP - Around
建议实施此操作。
@Around("@annotation(RequestMapping)") // modify the condition to include / exclude specific methods
public Object aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable {
Object args[] = joinpoint.getArgs();
String param = args[2]; // change the index as per convenience
if(param.equals("condition")){
return "commonView";
} else {
return joinpoint.proceed(); // this will execute the annotated method
}
}