我有一个控制器,它有一些动作,可以通过点击页面上的各个按钮来触发。我想有一个默认操作,但我不确定如何注释该方法。这是一个例子:
@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的每个方法上设置required = false,然后有条件地检查是否有人进来,我真的很讨厌...有没有办法注释这个是否正常工作?
答案 0 :(得分:3)
我会把它变成路径变量而不是参数,并且会摆脱.jsp
:
@RequestMapping("/view")
...
@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")
它更“安静”。
答案 1 :(得分:1)
正确的注释是:
@RequestMapping(
method = RequestMethod.POST,
params = { "!selectedItemKey", "submit" }
)
虽然看起来很奇怪,但是在添加第二个参数之前它没有达到此方法。
答案 2 :(得分:0)
我不太熟悉带注释的spring-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");
}
}
因此,在这种情况下,您可以通过在Spring配置上配置控制器而不是使用注释来解决此问题。