具有相同@RequestMapping的Spring MVC多个控制器
我正在尝试制作一个允许用户从登录页面index.htm
登录的Web应用程序。 此操作使用LoginController映射,登录成功后,用户将用户返回到相同的index.htm
但登录用户并使用欢迎消息向用户打招呼。
index.htm还有另一个名为itemform的表单,它允许用户将项目名称添加为文本。 此操作由itemController控制。
我的问题是我的LoginController和itemController都有相同的@RequestMapping
,因此我收到此错误:
创建名为’org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0’的bean在ServletContext资源[/WEB-INF/tinga-servlet.xml]中定义时出错:bean的初始化失败; 嵌套exception是java.lang.IllegalStateException:无法将处理程序[loginController]映射到URL路径[/index.htm]:已经映射了处理程序[com.tinga.LoginController@bf5555]。
无法将处理程序[loginController]映射到URL路径[/index.htm]:已经映射了处理程序[com.tinga.LoginController@bf5555]。
我该如何解决这个问题?
@RequestMapping(value="/login.htm") public ModelAndView login(HttpServletRequest request, HttpServletResponse response) { // show login page if no parameters given // process login if parameters are given } @RequestMapping(value="/index.htm") public ModelAndView index(HttpServletRequest request, HttpServletResponse response) { // show the index page }
最后,您需要一个servletfilter来拦截请求,如果您没有请求login.htm页面,则必须检查以确保用户已登录。如果您,则允许过滤链继续。 如果没有,则向/login.htm发出转发
public class LoginFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest)request; boolean loggedIn = ...; // determine if the user is logged in. boolean isLoginPage = ...; // use path to see if it's the login page if (loggedIn || isLoginPage) { chain.doFilter(request, response); } else { request.getRequestDispatcher("/login.htm").forward(request, response); } } }
并在web.xml中
我的部署描述符示例:
LoginFilter LoginFilter LoginFilter /* REQUEST FORWARD
这完全来自记忆,但它应该让你大致了解如何解决这个问题。
Spring MVC中所有控制器的请求映射应该是唯一的。
也许在你的控制器中使用相同的@RequestMapping你应该像这样定义方法(GET,POST …):
@RequestMapping(value="/index.htm", method = RequestMethod.GET) @RequestMapping(value="/index.htm", method = RequestMethod.POST)
使用GET方法的控制器,用于呈现表单并将数据(某个对象)绑定到它。 使用POST方法的控制器通常用于处理表单的提交和validation。
在表单中添加隐藏参数以区分它们,然后通过在post方法的注释中添加params属性来区分它们。
@RequestMapping(method = RequestMethod.POST, params = {"hiddenAction=login"}) @RequestMapping(method = RequestMethod.POST, params = {"hiddenAction=item"})