问题描述
我正在尝试制作一个允许用户从着陆页 index.htm
登录的网络应用。此操作映射为 LoginController ,成功登录后将用户返回到相同的 index.htm
但是已登录用户并使用欢迎消息欢迎用户。
I am trying to make a web app that allows user to login from landing page index.htm
. this action is mapped with a LoginController that after successful login takes user back to same index.htm
but as logged in user and greets user with welcome message.
index.htm还有另一个名为itemform的表单,它允许用户将项目名称添加为文本。这个动作由itemController控制。
index.htm also have another form named itemform, that allows user to add in item name as text. This action is controlled by itemController.
我的问题是我的 LoginController 和 itemController 有相同的 @RequestMapping
因此我收到此错误:
My problem is both my LoginController and itemController have same @RequestMapping
and hence I get this error:
无法将处理程序[loginController]映射到URL路径[/index.htm]:已经映射了处理程序[com.tinga.LoginController@bf5555]。
Cannot map handler [loginController] to URL path [/index.htm]: There is already handler [com.tinga.LoginController@bf5555] mapped.
我应该如何处理这个问题?
How should I go about tackling this problem?
推荐答案
@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页面,你必须检查,以确保在用户登录,如果是你,你让filterchain进行。如果没有,你发一个转发到/login.htm
Finally, you'll need a servlet filter to intercept the requests and if you're not requesting the login.htm page, you'll have to check to make sure the user is logged in. If you, you allow the filterchain to proceed. If not, you issue a forward to /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>
这一切都来自内存,但它应该让你大致了解如何解决这个问题。
This is all from memory, but it should give you the general idea of how to go about this.
这篇关于具有相同@RequestMapping的Spring MVC多个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!