Spring MVC带注释的控制器
问题描述:
我有一个控制器,它有几个动作,这些动作是通过点击页面上的各种按钮触发的。我想要一个默认操作,但我不确定如何注释该方法。这里是一个例子:Spring MVC带注释的控制器
@Controller
@RequestMapping("/view.jsp")
public class ExampleController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView displayResults() {
ModelAndView mav = new ModelAndView("view");
mav.addObject("queryResults", methodToQueryDBForListing());
return mav;
}
@RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
ModelAndView mav = new ModelAndView("action1");
//Business logic
return mav;
}
@RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
ModelAndView mav = new ModelAndView("action2");
//Business logic
return mav;
}
//A few more methods which basically do what action1 and action2 do
}
如何注释一个方法将作用于任何提交按钮没有选择按键被按下的POST?
我曾尝试:
@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)
我真的很讨厌它,如果我必须设置所需=假每个的内搭RequestParams然后有条件地检查,看看是否一个进来与否的方法。有没有一种方法来注释这个工作正常?
答
我会做这个路径变量,而不是一个参数,并会摆脱.jsp
的:
@RequestMapping("/view")
...
@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")
更“平安”。
答
正确的注解是:
@RequestMapping(
method = RequestMethod.POST,
params = { "!selectedItemKey", "submit" }
)
这似乎很奇怪,虽然,它并没有触及此方法,直到补充说,第二个参数。
答
我不那么熟悉的注释弹簧MVC,但是我记得延伸的MultiActionController
时,你可以通过定义以下Spring配置指定一个默认入口点:
<bean name="myController"
class="foo.bar.MyController">
<property name="methodNameResolver">
<bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="defaultMethodName" value="init" />
</bean>
</property>
package foo.bar
public class MyController extends MultiActionController {
/**
* Called when no parameter was passed.
*/
public ModelAndView init(HttpServletRequest request,
HttpServletResponse response) {
return new ModelAndView("myDefaultView");
}
/**
* action=method1
*/
public void method1(HttpServletRequest request,
HttpServletResponse response) {
return new ModelAndView("method1");
}
/**
* action=method2
*/
public void method2(HttpServletRequest request,
HttpServletResponse response) {
return new ModelAndView("method2");
}
}
所以也许在这种情况下,你可以通过配置你的控制器而不是使用注释来解决这个问题。
+0
如果使用DefaultAnnotationHandlerMapping,则可以指定默认处理程序。 – Scott 2011-04-12 13:13:05
同意,这将是非常好的客户买这个。我不太确定他们会愿意让我们“走得那么远”,不幸的是...... – Scott 2011-04-12 13:14:44
标明你的答案是正确的,因为我认为它是技术上更好的解决方案。但是,如果有其他人出现,无法使用宁静的网址,请使用下面的答案。 – Scott 2011-04-12 16:32:16