[英]Spring MVC Annotated Controller
我有一个控制器,该控制器具有一些操作,这些操作是通过单击页面上的各种按钮来触发的。 我想进行默认操作,但是不确定如何对方法进行注释。 这是一个例子:
@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,然后有条件地检查是否有一个方法进来,我真的会讨厌它。是否有办法对其进行注释才能正常工作?
我将其设置为路径变量而不是参数,并将摆脱.jsp
:
@RequestMapping("/view")
...
@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")
这更“宁静”。
正确的注释是:
@RequestMapping(
method = RequestMethod.POST,
params = { "!selectedItemKey", "submit" }
)
但是,在添加第二个参数之前没有使用此方法似乎很奇怪。
我对带注释的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 config上配置控制器而不是使用批注来解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.