13.0、用户登录拦截器实现
InterceptorController.java文件
package com.hkl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping(value = "/user")
public class InterceptorController {
@RequestMapping(value = "/gomain")
public String gomain() {
return "main";
}
@RequestMapping(value = "/gologin")
public String gologin() {
return "login";
}
@RequestMapping(value = "/login")
public String login(String password, String name, Model model, HttpSession session) {
model.addAttribute("name",name);
session.setAttribute("name",name);
return "main";
}
@RequestMapping(value = "/goOut")
public String goOut(HttpSession session) {
session.removeAttribute("name");
return "index";
}
}
LoginInterceptor.java用户登录拦截器
package com.hkl.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//如果session中有值证明已经登录,直接放行
HttpSession session = request.getSession();
if(session.getAttribute("name") != null) {
return true;
}
//如果访问的是登录界面也直接放行
if(request.getRequestURI().contains("gologin")) {
return true;
}
//因为第一次登录的时候session肯定是空然后会直接拦截掉,所以login请求也必须放行才能对账号和密码进行判断处理登录
if(request.getRequestURI().contains("login")) {
return true;
}
//如果都没能放行说明该用户未登录,则直接跳转到登录界面
request.setAttribute("msg","尚未有账号登录,请先登录!");
request.getRequestDispatcher("/user/gologin").forward(request,response);
return false;
}
}
在spring-mvc.xml配置文件中加入以下配置代码即可:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="com.hkl.config.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>