具有相同@RequestMapping的Spring MVC多个控制器

时间:2012-07-23 06:25:26

标签: java spring spring-mvc

我正在尝试制作一个允许用户从着陆页index.htm登录的网络应用。此操作映射为 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的初始化失败;嵌套异常是java.lang.IllegalStateException:无法将处理程序[loginController]映射到URL路径[/index.htm]:已经映射了处理程序[com.tinga.LoginController@bf5555]。

     

无法将处理程序[loginController]映射到URL路径[/index.htm]:已经映射了处理程序[com.tinga.LoginController@bf5555]。

我应该如何处理这个问题?

4 个答案:

答案 0 :(得分:2)

@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
}

最后,你需要一个servlet过滤器来拦截请求,如果你没有请求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中

我的部署描述符示例:

<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>LoginFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>  
    <dispatcher>FORWARD</dispatcher> 
</filter-mapping>

这一切都来自记忆,但它应该让你大致了解如何解决这个问题。

答案 1 :(得分:0)

所有控制器的请求映射在Spring MVC中应该是唯一的。

答案 2 :(得分:0)

也许在你的控制器中使用相同的@RequestMapping你应该像这样定义方法(GET,POST ...):

@RequestMapping(value="/index.htm", method = RequestMethod.GET)
@RequestMapping(value="/index.htm", method = RequestMethod.POST)

使用GET方法的控制器,用于呈现表单并将数据(某个对象)绑定到它。使用POST方法的控制器通常用于处理表单的提交和验证。

答案 3 :(得分:0)

在表单中添加隐藏参数以区分它们,然后通过在post方法的注释中添加params属性来区分它们。

<form:hidden name="hiddenAction" value="login" />
<form:hidden name="hiddenAction" value="item" />

@RequestMapping(method = RequestMethod.POST, params = {"hiddenAction=login"})
@RequestMapping(method = RequestMethod.POST, params = {"hiddenAction=item"})
相关问题