SSM项目整合——10SpringMVC拦截器
本节我们利用SpringMVC的拦截器来实现我们的登录功能。
新建
LoginController
:
@Controller
public class LoginController {
@RequestMapping("login")
public String login(){
return "items/login";
}
}
新建login.jsp
:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form method="post" action="/login.do">
姓名:<input type="text" name="name"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
新建Welcome.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>欢迎您的登录</title>
</head>
<body>
欢迎你的到来
</body>
</html>
接下来我们的做法就是实现访问localhost:8080/login.do
时:
1.如果已经登录,直接让拦截器放行到欢迎界面
2.如果没有登录但是姓名与密码均正确也放行到欢迎界面
3如果没有登录但是姓名与密码有误在回到登录界面(但是我们这里会把该用户注册再次登录即可成功)
上面的功能需要配置拦截器:
新建LoginInterceptor
,让其实现HandlerInterceptor
接口:
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
HandlerInterceptor
接口三个方法:
1.preHandle:在执行Controller之前执行该方法,如果它返回true则放行执行Controller
2.postHandle:在执行Controller之后未返回视图前执行该方法
3.afterCompletion:在执行Controller之后且返回视图后执行该方法
这里只用到第一个,接下来我们改写preHandle
的内容:
String name = httpServletRequest.getParameter("name");
String password = httpServletRequest.getParameter("password");
HttpSession session = httpServletRequest.getSession();
//如果用户存在,且已经登录直接跳到欢迎
if(session.getAttribute("name")!=null){
if(session.getAttribute("name").equals(name)&&session.getAttribute("password").equals(password)){
httpServletRequest.getRequestDispatcher("/WEB-INF/views/items/Welcome.jsp").forward(httpServletRequest,httpServletResponse);
return true;
}
}else{
session.setAttribute("name",name);
session.setAttribute("password",password);
httpServletRequest.getRequestDispatcher("/WEB-INF/views/items/login.jsp").forward(httpServletRequest,httpServletResponse);
}
return false;
我们还需配置那些路径可以拦截,下面的内容在springmvc.xml
里面:
<mvc:interceptors>
<mvc:interceptor>
<!--/**表示拦截所有路径,也有
<mvc:exclude-mapping path=""/>表示那些路径不拦截,虽然是拦截所有路径但前提是路径在服务器这边存在才会拦截-->
<mvc:mapping path="/**"/>
<bean class="web.Controller.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>