本篇文章简单介绍一下如何用拦截器实现登录注册的功能
下面以我之前写的项目代码为例,介绍实现登录功能的案例和拦截器的配置和使用
①在spring-mvc中配置拦截器
首先要知道path表示的路径是从web根目录开始的,拦截器可以拦截web下的静态资源,也可以拦截对应url(两者其实是一个道理) 下面是总的代码,对于处理登录,注册的方法,以及登录界面和static下的静态资源选择放行不拦截,其他路径的文件和方法进行拦截
SessionInterceptor是写的拦截器的全类名
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--多级目录全部拦截-->
<mvc:mapping path="/**"/>
<!--特殊url不拦截-->
<!--登陆界面,静态资源,注册和登录功能对应的方法不拦截,不需要session也能进-->
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/static/**"/>
<mvc:exclude-mapping path="/handleLogin"/>
<mvc:exclude-mapping path="/handleRegister"/>
<bean class="com.shugou.utils.SessionInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
下面对path的三种写法的介绍
初始的url是http://localhost:9090/
<mvc:mapping path="/**"/> 表示拦截下面的所有文件,包括子文件夹中的文件(一般都写这个)
<mvc:mapping path="/*"/>表示拦截当前目录下的所有文件,不包括子文件夹
<mvc:mapping path="/"/>表示拦截是web项目的根目录(这个我测试不出来,也不知道网上为什么都这么说,可能是我测试的url有问题)
测试环境如下
当写成<mvc:mapping path="/**"/>时,显然两个bg2.jpg都访问不了
当写成<mvc:mapping path="/*"/>时,由于默认是从web目录下面开始的,所以此时
访问http://localhost:9090/bg2.jpg 会被拦截.
访问http://localhost:9090/static/bg2.jpg不会被拦截(因为多了一层static)
②在controller层写好处理登录的方法
做一下账号密码的校验工作,如果账号密码都正确,就设置一下session
③.写SessionUtilss方法(重点)
代码如下:
当handleLogin方法中验证账号密码都正确时,将账号密码相关的信息放进session中,即调用setAdmin方法。
而getAdmin是通过判断session中是否存在数据用来判断当前是否已经有登录成功的权限
(注意:这里还有Controller层一定要用形参的request,这样才能保证共享同一个HttpServletRequestt对象)
private static final String key = "admin";
public static void setAdmin(HttpServletRequest request, User admin){
request.getSession().setAttribute(key,admin);
}
public static User getAdmin(HttpServletRequest request){
if(request.getSession().getAttribute(key) != null){
return (User) request.getSession().getAttribute(key);
}else{
return null;
}
}
④.自定义拦截器并实现HandlerInterceptor接口(重点)
这个接口里有三个方法,我们只要重写preHandle即可.
先用SessionUtils.getAdmin(request)来看看是否能从session中获取到用户信息,如果获取不到则返回重定向到登录界面.
其中request.getContextPath()可以获取到当前url的前面部分,也就是http://localhost:9090(也就是ip地址:端口号),此时如果要拼接url的话要记得加上,比如下面的代码。且一定要返回false
如果当前已经有用户登录信息了,返回true,此时不再拦截资源
User user = SessionUtils.getAdmin(request);
if(user == null){
response.setContentType("text/html;charset=utf-8");
// response.getWriter().print("您没有权限,请<a href='login'>登录</a>");
System.out.println("request.getContextPath()"+request.getContextPath()+"\\login");
response.sendRedirect(request.getContextPath()+"\\login");
return false;
}
return true;