簡體   English   中英

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

[英]Spring MVC Multiple Controllers with same @RequestMapping

我正在嘗試制作一個允許用戶從着陸頁index.htm登錄的Web應用程序。 此操作與LoginController映射,該登錄控制器在成功登錄后將用戶帶回相同的index.htm但以登錄用戶身份並用歡迎消息向用戶打招呼。

index.htm還具有另一個名為itemform的表格,該表格允許用戶以文字形式添加商品名稱。 此操作由itemController控制。

我的問題是我的LoginControlleritemController都具有相同的@RequestMapping ,因此出現此錯誤:

創建在ServletContext資源[/WEB-INF/tinga-servlet.xml]中定義的名稱為'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0'的bean時出錯:初始化bean失敗; 嵌套的異常為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
}

最后,您將需要一個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>

這些全都來自記憶,但是它應該使您大致了解如何進行此操作。

所有控制器的請求映射在Spring MVC中應該是唯一的。

也許在具有相同@RequestMapping的控制器中,您應該定義方法(GET,POST ...),如下所示:

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

帶有GET方法的控制器,用於呈現表單並將數據(某些對象)綁定到該表單。 通常使用帶有POST方法的控制器來處理表單的提交和驗證。

在表單中添加一個隱藏參數以區分它們,然后通過在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"})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM