1、编写拦截器
public class LoginInterceptor implements HandlerInterceptor {
// 在拦截点执行前拦截,如果返回true则不执行拦截点后的操作(拦截成功)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
//如果已经登录,不拦截
if (session.getAttribute("user")!=null) {
return true;
}
//如果没有登录,则跳转到登录界面
else {
/**
* 以下是为了登录成功后返回到刚刚的操作,不跳到主界面
* 实现:通过将请求URL保存到session的beforePath中,然后在登录时判断beforePath是否为空
*/
String uri = request.getRequestURI();//拿到上一个页面地址
String path = uri.substring(request.getContextPath().length());//去掉项目地址长度的字符(因为我的默认项目地址是给出的)
String query = request.getQueryString();//得到参数
if(query == null) {
query="";
}
else {
query="?"+query;
}
String beforePath = path+query;
session.setAttribute("beforePath", beforePath);
response.sendRedirect(request.getContextPath()+"/login");
return false;
}
}
// 在处理过程中,执行拦截
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
// 执行完毕,返回前拦截
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
2、在spring-mvc.xml 的配置文件中配置
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置登陆拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 但是排除下面这些,也就是不拦截请求 -->
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/register"/>
<mvc:exclude-mapping path="/index"/>
<mvc:exclude-mapping path="/selectProductByCategoryId"/>
<mvc:exclude-mapping path="/showProductDetail"/>
<!-- ajax请求的action不进行拦截 -->
<mvc:exclude-mapping path="/*.ajax"/>
<bean class="com.wwz.eshop.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3、拦截后跳到登录界面,登录成功后跳到上一个操作,我们需要在登录控制器中配置
@Controller
public class LoginController {
@Autowired
UserService userService;
//跳转到登录界面
@RequestMapping(value="/login",method=RequestMethod.GET)
public String toLogin()
{
return "fore/login";
}
//登录成功跳转到主界面
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(User u,HttpSession session) throws CustomException
{
User user=userService.getUser(u);
if (user==null) {
return "fore/login";
}
session.setAttribute("user", user);
//判断beforePath是否有请求的URL,有的话取出来跳转
String beforePath=(String) session.getAttribute("beforePath");
if(beforePath!=null) {
return "redirect:"+beforePath;
}
return "redirect:/index";
}
}