我正在尝试制作一个允许用户从登录页面index.htm登录的Web应用程序.此操作与LoginController映射,登录成功后,用户将用户返回到相同的index.htm,但登录用户并使用欢迎消息迎接用户.
index.htm还有另一个名为itemform的表单,它允许用户将项目名称添加为文本.此操作由itemController控制.
我的问题是我的LoginController和itemController都有相同的@RequestMapping,因此我收到此错误:
Error creating bean with name ‘org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0′ defined in ServletContext resource [/WEB-INF/tinga-servlet.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot map handler [loginController] to URL path [/index.htm]: There is already handler [com.tinga.LoginController@bf5555] mapped.
Cannot map handler [loginController] to URL path [/index.htm]: There is already handler [com.tinga.LoginController@bf5555] mapped.
我该如何解决这个问题?
最佳答案
@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>
这完全来自记忆,但它应该让你了解如何解决这个问题.